'use client'

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { gql } from 'graphql-tag'
import { apolloClient } from '@/lib/graphql/client'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Server, Play, Pause, Trash2, Loader2 } from 'lucide-react'

const GET_RESOURCES = gql`
  query GetResources($filter: ResourceFilter) {
    resources(filter: $filter) {
      id
      name
      type
      status
      site {
        id
        name
        region
      }
      createdAt
      updatedAt
    }
  }
`

const UPDATE_RESOURCE = gql`
  mutation UpdateResource($id: ID!, $input: UpdateResourceInput!) {
    updateResource(id: $id, input: $input) {
      id
      status
    }
  }
`

const DELETE_RESOURCE = gql`
  mutation DeleteResource($id: ID!) {
    deleteResource(id: $id)
  }
`

export function ResourceList({ filter }: { filter?: any }) {
  const [deletingId, setDeletingId] = useState<string | null>(null)
  const queryClient = useQueryClient()
  
  const { data, isLoading, error } = useQuery({
    queryKey: ['resources', filter],
    queryFn: async () => {
      const result = await apolloClient.query({
        query: GET_RESOURCES,
        variables: { filter },
      })
      return result.data.resources
    },
  })

  const updateResourceMutation = useMutation({
    mutationFn: async ({ id, status }: { id: string; status: string }) => {
      const result = await apolloClient.mutate({
        mutation: UPDATE_RESOURCE,
        variables: {
          id,
          input: { metadata: { status } },
        },
      })
      return result.data.updateResource
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['resources'] })
    },
  })

  const deleteResourceMutation = useMutation({
    mutationFn: async (id: string) => {
      const result = await apolloClient.mutate({
        mutation: DELETE_RESOURCE,
        variables: { id },
      })
      return result.data.deleteResource
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['resources'] })
      setDeletingId(null)
    },
  })

  const handleStart = (resourceId: string) => {
    updateResourceMutation.mutate({ id: resourceId, status: 'RUNNING' })
  }

  const handleStop = (resourceId: string) => {
    updateResourceMutation.mutate({ id: resourceId, status: 'STOPPED' })
  }

  const handleDelete = (resourceId: string) => {
    if (confirm('Are you sure you want to delete this resource? This action cannot be undone.')) {
      setDeletingId(resourceId)
      deleteResourceMutation.mutate(resourceId)
    }
  }

  if (isLoading) return <div className="text-gray-400">Loading resources...</div>
  if (error) return <div className="text-red-400">Error: {error.message}</div>

  return (
    <div className="space-y-4">
      {data?.map((resource: any) => (
        <Card key={resource.id} className="border-studio-medium bg-studio-dark">
          <CardHeader>
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <Server className="h-5 w-5 text-phoenix-fire" />
                <div>
                  <CardTitle className="text-white">{resource.name}</CardTitle>
                  <p className="text-sm text-gray-400">{resource.site?.name}</p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Badge
                  variant={
                    resource.status === 'RUNNING'
                      ? 'default'
                      : resource.status === 'ERROR'
                      ? 'destructive'
                      : 'secondary'
                  }
                >
                  {resource.status}
                </Badge>
                <Badge variant="outline">{resource.type}</Badge>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="flex items-center gap-2">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleStart(resource.id)}
                disabled={updateResourceMutation.isPending || resource.status === 'RUNNING'}
                title="Start resource"
              >
                {updateResourceMutation.isPending ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Play className="h-4 w-4" />
                )}
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleStop(resource.id)}
                disabled={updateResourceMutation.isPending || resource.status === 'STOPPED'}
                title="Stop resource"
              >
                {updateResourceMutation.isPending ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Pause className="h-4 w-4" />
                )}
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleDelete(resource.id)}
                disabled={deleteResourceMutation.isPending || deletingId === resource.id}
                title="Delete resource"
                className="text-red-400 hover:text-red-300"
              >
                {deletingId === resource.id ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Trash2 className="h-4 w-4" />
                )}
              </Button>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  )
}

