'use client'

import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { useMutation } from '@apollo/client'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog'
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { useToast } from '@/components/ui/use-toast'
import { UPDATE_NETWORK_TOPOLOGY, GET_NETWORK_TOPOLOGIES } from '@/lib/graphql/queries/infrastructure'
import { topologyNodeSchema } from '@/lib/validation/schemas/infrastructure'
import type { TopologyNode, NetworkTopology } from '@/lib/types/infrastructure'
import { useState } from 'react'

interface EditTopologyNodeFormProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  node: TopologyNode
  topologyId: string
  onSuccess?: () => void
}

export function EditTopologyNodeForm({
  open,
  onOpenChange,
  node,
  topologyId,
  onSuccess,
}: EditTopologyNodeFormProps) {
  const { toast } = useToast()
  const [updateTopology, { loading }] = useMutation(UPDATE_NETWORK_TOPOLOGY, {
    refetchQueries: ['GetNetworkTopologies'],
  })

  const [metadataText, setMetadataText] = useState(JSON.stringify(node.metadata || {}, null, 2))

  const form = useForm<Partial<TopologyNode>>({
    resolver: zodResolver(topologyNodeSchema.partial()),
    defaultValues: {
      label: node.label,
      region: node.region,
      entity: node.entity,
      position: node.position,
    },
  })

  const onSubmit = async (data: Partial<TopologyNode>) => {
    try {
      // Parse metadata JSON
      let metadata = {}
      try {
        metadata = JSON.parse(metadataText)
      } catch (e) {
        toast({
          title: 'Invalid JSON',
          description: 'Metadata must be valid JSON',
          variant: 'error',
        })
        return
      }

      // Update the node in the topology
      const updatedNodes = topology.nodes.map((n) =>
        n.id === node.id
          ? {
              ...n,
              ...data,
              metadata,
            }
          : n
      )

        await updateTopology({
          variables: {
            id: topologyId,
          input: {
            nodes: updatedNodes,
            edges: topology.edges,
          },
        },
      })

      toast({
        title: 'Success',
        description: 'Node updated successfully',
        variant: 'success',
      })

      onSuccess?.()
      onOpenChange(false)
    } catch (error) {
      toast({
        title: 'Error',
        description: error instanceof Error ? error.message : 'Failed to update node',
        variant: 'error',
      })
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Edit Topology Node</DialogTitle>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <div className="grid grid-cols-2 gap-4 p-4 bg-studio-medium/20 rounded-lg">
              <div>
                <div className="text-sm text-studio-medium">Type</div>
                <div className="font-semibold">{node.type}</div>
              </div>
              <div>
                <div className="text-sm text-studio-medium">ID</div>
                <div className="font-semibold text-xs">{node.id}</div>
              </div>
            </div>

            <FormField
              control={form.control}
              name="label"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Label</FormLabel>
                  <FormControl>
                    <Input placeholder="Node label" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="region"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Region</FormLabel>
                    <FormControl>
                      <Input placeholder="Region" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="entity"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Entity</FormLabel>
                    <FormControl>
                      <Input placeholder="Entity" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="position.x"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Position X</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder="0"
                        {...field}
                        value={field.value || ''}
                        onChange={(e) => {
                          field.onChange(parseFloat(e.target.value) || 0)
                        }}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="position.y"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Position Y</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder="0"
                        {...field}
                        value={field.value || ''}
                        onChange={(e) => {
                          field.onChange(parseFloat(e.target.value) || 0)
                        }}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormItem>
              <FormLabel>Metadata (JSON)</FormLabel>
              <Textarea
                value={metadataText}
                onChange={(e) => setMetadataText(e.target.value)}
                rows={8}
                className="font-mono text-sm"
                placeholder='{"key": "value"}'
              />
              <FormMessage />
            </FormItem>

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
                Cancel
              </Button>
              <Button type="submit" disabled={loading}>
                {loading ? 'Saving...' : 'Save'}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}

