'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,
  FormDescription,
} 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_COMPLIANCE_REQUIREMENT } from '@/lib/graphql/queries/infrastructure'
import { updateComplianceInputSchema } from '@/lib/validation/schemas/infrastructure'
import type { ComplianceRequirement } from '@/lib/types/infrastructure'
import type { UpdateComplianceInput } from '@/lib/validation/schemas/infrastructure'

interface EditComplianceFormProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  requirement: ComplianceRequirement
  onSuccess?: () => void
}

export function EditComplianceForm({
  open,
  onOpenChange,
  requirement,
  onSuccess,
}: EditComplianceFormProps) {
  const { toast } = useToast()
  const [updateCompliance, { loading }] = useMutation(UPDATE_COMPLIANCE_REQUIREMENT, {
    refetchQueries: ['GetComplianceRequirements'],
  })

  const form = useForm<UpdateComplianceInput>({
    resolver: zodResolver(updateComplianceInputSchema),
    defaultValues: {
      frameworks: requirement.frameworks,
      status: requirement.status,
      requirements: requirement.requirements,
      lastAuditDate: requirement.lastAuditDate,
      notes: requirement.notes,
    },
  })

  const onSubmit = async (data: UpdateComplianceInput) => {
    try {
      await updateCompliance({
        variables: {
          country: requirement.country,
          input: data,
        },
      })

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

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

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

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="country"
              render={() => (
                <FormItem>
                  <FormLabel>Country</FormLabel>
                  <FormControl>
                    <Input value={requirement.country} disabled />
                  </FormControl>
                  <FormDescription>Country cannot be changed</FormDescription>
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="frameworks"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Frameworks</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="GDPR, PCI-DSS, HIPAA (comma-separated)"
                      value={field.value?.join(', ') || ''}
                      onChange={(e) => {
                        const frameworks = e.target.value
                          .split(',')
                          .map((f) => f.trim())
                          .filter((f) => f.length > 0)
                        field.onChange(frameworks)
                      }}
                    />
                  </FormControl>
                  <FormDescription>Enter frameworks separated by commas</FormDescription>
                  <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="Compliant">Compliant</SelectItem>
                      <SelectItem value="Partial">Partial</SelectItem>
                      <SelectItem value="Pending">Pending</SelectItem>
                      <SelectItem value="Non-Compliant">Non-Compliant</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="requirements"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Requirements</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Enter requirements, one per line"
                      value={field.value?.join('\n') || ''}
                      onChange={(e) => {
                        const requirements = e.target.value
                          .split('\n')
                          .map((r) => r.trim())
                          .filter((r) => r.length > 0)
                        field.onChange(requirements)
                      }}
                      rows={5}
                    />
                  </FormControl>
                  <FormDescription>Enter requirements, one per line</FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />

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

            <FormField
              control={form.control}
              name="notes"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Notes</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Additional notes..."
                      {...field}
                      value={field.value || ''}
                      rows={3}
                    />
                  </FormControl>
                  <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>
  )
}

