'use client'

import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { useMutation, useQuery } 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 {
  CREATE_DEPLOYMENT_MILESTONE,
  UPDATE_DEPLOYMENT_MILESTONE,
  GET_DEPLOYMENT_MILESTONES,
} from '@/lib/graphql/queries/infrastructure'
import {
  createMilestoneInputSchema,
  updateMilestoneInputSchema,
} from '@/lib/validation/schemas/infrastructure'
import type { DeploymentMilestone } from '@/lib/types/infrastructure'
import type { CreateMilestoneInput, UpdateMilestoneInput } from '@/lib/validation/schemas/infrastructure'
import { useEffect } from 'react'

interface EditMilestoneFormProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  milestone?: DeploymentMilestone
  onSuccess?: () => void
}

export function EditMilestoneForm({
  open,
  onOpenChange,
  milestone,
  onSuccess,
}: EditMilestoneFormProps) {
  const { toast } = useToast()
  const isEdit = !!milestone

  const [createMilestone, { loading: creating }] = useMutation(CREATE_DEPLOYMENT_MILESTONE, {
    refetchQueries: ['GetDeploymentMilestones'],
  })

  const [updateMilestone, { loading: updating }] = useMutation(UPDATE_DEPLOYMENT_MILESTONE, {
    refetchQueries: ['GetDeploymentMilestones'],
  })

  const { data: milestonesData } = useQuery(GET_DEPLOYMENT_MILESTONES, {
    skip: !open,
  })

  const availableMilestones = milestonesData?.data?.deploymentMilestones || []

  const form = useForm<CreateMilestoneInput | UpdateMilestoneInput>({
    resolver: zodResolver(isEdit ? updateMilestoneInputSchema : createMilestoneInputSchema),
    defaultValues: milestone
      ? {
          title: milestone.title,
          region: milestone.region,
          entity: milestone.entity,
          priority: milestone.priority,
          startDate: milestone.startDate,
          endDate: milestone.endDate,
          status: milestone.status,
          dependencies: milestone.dependencies || [],
          cost: milestone.cost,
          description: milestone.description,
        }
      : {
          title: '',
          region: '',
          entity: '',
          priority: 'Medium',
          startDate: new Date().toISOString(),
          endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
          status: 'Planned',
          dependencies: [],
          cost: undefined,
          description: '',
        },
  })

  const loading = creating || updating

  const onSubmit = async (data: CreateMilestoneInput | UpdateMilestoneInput) => {
    try {
      if (isEdit && milestone) {
        await updateMilestone({
          variables: {
            id: milestone.id,
            input: data,
          },
        })
        toast({
          title: 'Success',
          description: 'Milestone updated successfully',
          variant: 'success',
        })
      } else {
        await createMilestone({
          variables: {
            input: data,
          },
        })
        toast({
          title: 'Success',
          description: 'Milestone created successfully',
          variant: 'success',
        })
      }

      onSuccess?.()
      onOpenChange(false)
      form.reset()
    } catch (error) {
      toast({
        title: 'Error',
        description: error instanceof Error ? error.message : 'Failed to save milestone',
        variant: 'error',
      })
    }
  }

  // Validate circular dependencies
  const validateDependencies = (deps: string[]): boolean => {
    if (!milestone || deps.length === 0) return true
    // Simple check - in a real implementation, you'd do a graph traversal
    return !deps.includes(milestone.id)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{isEdit ? 'Edit Milestone' : 'Create Milestone'}</DialogTitle>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="title"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Title</FormLabel>
                  <FormControl>
                    <Input placeholder="Milestone title" {...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="priority"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Priority</FormLabel>
                    <Select onValueChange={field.onChange} value={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="Select priority" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="Critical">Critical</SelectItem>
                        <SelectItem value="High">High</SelectItem>
                        <SelectItem value="Medium">Medium</SelectItem>
                        <SelectItem value="Low">Low</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="status"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Status</FormLabel>
                    <Select onValueChange={field.onChange} value={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="Select status" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="Planned">Planned</SelectItem>
                        <SelectItem value="In Progress">In Progress</SelectItem>
                        <SelectItem value="Complete">Complete</SelectItem>
                        <SelectItem value="Blocked">Blocked</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="startDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Start Date</FormLabel>
                    <FormControl>
                      <Input
                        type="datetime-local"
                        value={field.value ? new Date(field.value).toISOString().slice(0, 16) : ''}
                        onChange={(e) => {
                          field.onChange(new Date(e.target.value).toISOString())
                        }}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="endDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>End Date</FormLabel>
                    <FormControl>
                      <Input
                        type="datetime-local"
                        value={field.value ? new Date(field.value).toISOString().slice(0, 16) : ''}
                        onChange={(e) => {
                          field.onChange(new Date(e.target.value).toISOString())
                        }}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="dependencies"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Dependencies</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Milestone IDs (comma-separated)"
                      value={field.value?.join(', ') || ''}
                      onChange={(e) => {
                        const deps = e.target.value
                          .split(',')
                          .map((d) => d.trim())
                          .filter((d) => d.length > 0)
                        if (validateDependencies(deps)) {
                          field.onChange(deps)
                        } else {
                          toast({
                            title: 'Invalid dependency',
                            description: 'Cannot create circular dependencies',
                            variant: 'error',
                          })
                        }
                      }}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="cost"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Cost (USD)</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      placeholder="0"
                      {...field}
                      value={field.value || ''}
                      onChange={(e) => {
                        field.onChange(e.target.value ? parseFloat(e.target.value) : undefined)
                      }}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Description</FormLabel>
                  <FormControl>
                    <Textarea placeholder="Milestone description" {...field} rows={3} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

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

