'use client'

import { useQuery } from '@tanstack/react-query'
import { useState, type ChangeEvent } from 'react'

import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card'
import { Input } from '@/components/ui/Input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'

interface Resource {
  id: string
  name: string
  type: string
  provider: string
  region: string
  status: string
  tags: string[]
}

export function ResourceExplorer() {
  const [search, setSearch] = useState('')
  const [filterProvider, setFilterProvider] = useState<string>('all')
  const [filterType, setFilterType] = useState<string>('all')

  const { data: resources, isLoading } = useQuery<Resource[]>({
    queryKey: ['resources', filterProvider, filterType],
    queryFn: async () => {
      const graphqlEndpoint = process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT || 'http://localhost:4000/graphql'
      
      const query = `
        query GetResourceInventory($filter: ResourceInventoryFilter) {
          resourceInventory(filter: $filter) {
            id
            name
            resourceType
            provider
            region
            tags
            metadata
          }
        }
      `
      
      const variables: Record<string, string> = {}
      if (filterProvider !== 'all') {
        variables.provider = filterProvider
      }
      if (filterType !== 'all') {
        variables.resourceType = filterType
      }
      
      const response = await fetch(graphqlEndpoint, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          query,
          variables: Object.keys(variables).length > 0 ? { filter: variables } : undefined,
        }),
      })
      
      if (!response.ok) {
        throw new Error(`Failed to fetch resources: ${response.statusText}`)
      }
      
      const result = await response.json()
      
      if (result.errors) {
        throw new Error(result.errors[0]?.message || 'GraphQL error')
      }
      
      // Transform GraphQL response to component format
      return (result.data?.resourceInventory || []).map(
        (item: {
          id: string
          name: string
          resourceType: string
          provider: string
          region?: string
          tags?: string[]
          metadata?: { status?: string }
        }) => ({
        id: item.id,
        name: item.name,
        type: item.resourceType,
        provider: item.provider,
        region: item.region || 'Unknown',
        status: item.metadata?.status || 'UNKNOWN',
        tags: item.tags || [],
      }))
    },
  })

  const filteredResources = resources?.filter((resource) => {
    const matchesSearch = resource.name.toLowerCase().includes(search.toLowerCase())
    const matchesProvider = filterProvider === 'all' || resource.provider === filterProvider
    const matchesType = filterType === 'all' || resource.type === filterType
    return matchesSearch && matchesProvider && matchesType
  })

  return (
    <div className="space-y-4">
      <div className="flex gap-4">
        <Input
          placeholder="Search resources..."
          value={search}
          onChange={(e: ChangeEvent<HTMLInputElement>) => setSearch(e.target.value)}
          className="flex-1"
        />
        <Select value={filterProvider} onValueChange={setFilterProvider}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Provider" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Providers</SelectItem>
            <SelectItem value="PROXMOX">Proxmox</SelectItem>
            <SelectItem value="KUBERNETES">Kubernetes</SelectItem>
            <SelectItem value="CLOUDFLARE">Cloudflare</SelectItem>
          </SelectContent>
        </Select>
        <Select value={filterType} onValueChange={setFilterType}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Type" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Types</SelectItem>
            <SelectItem value="VM">VM</SelectItem>
            <SelectItem value="CONTAINER">Container</SelectItem>
            <SelectItem value="STORAGE">Storage</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {isLoading ? (
        <div>Loading resources...</div>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {filteredResources?.map((resource) => (
            <Card key={resource.id}>
              <CardHeader>
                <CardTitle className="text-lg">{resource.name}</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-500">Provider:</span>
                    <Badge>{resource.provider}</Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-500">Type:</span>
                    <Badge variant="outline">{resource.type}</Badge>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-500">Region:</span>
                    <span className="text-sm">{resource.region}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-500">Status:</span>
                    <Badge
                      variant={
                        resource.status === 'RUNNING' ? 'default' : 'secondary'
                      }
                    >
                      {resource.status}
                    </Badge>
                  </div>
                  {resource.tags && resource.tags.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-2">
                      {resource.tags.map((tag) => (
                        <Badge key={tag} variant="outline" className="text-xs">
                          {tag}
                        </Badge>
                      ))}
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  )
}

