'use client'

import { useForm, useWatch } 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 { useToast } from '@/components/ui/use-toast'
import { UPDATE_COST_ESTIMATE } from '@/lib/graphql/queries/infrastructure'
import { updateCostEstimateInputSchema } from '@/lib/validation/schemas/infrastructure'
import type { CostEstimate } from '@/lib/types/infrastructure'
import type { UpdateCostEstimateInput } from '@/lib/validation/schemas/infrastructure'
import { useEffect } from 'react'

interface EditCostEstimateFormProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  estimate: CostEstimate
  onSuccess?: () => void
}

export function EditCostEstimateForm({
  open,
  onOpenChange,
  estimate,
  onSuccess,
}: EditCostEstimateFormProps) {
  const { toast } = useToast()
  const [updateCostEstimate, { loading }] = useMutation(UPDATE_COST_ESTIMATE, {
    refetchQueries: ['GetCostEstimates'],
  })

  const form = useForm<UpdateCostEstimateInput>({
    resolver: zodResolver(updateCostEstimateInputSchema),
    defaultValues: {
      monthly: estimate.monthly,
      annual: estimate.annual,
      breakdown: estimate.breakdown,
      currency: estimate.currency,
    },
  })

  // Auto-calculate annual from monthly
  const monthly = useWatch({ control: form.control, name: 'monthly' })
  useEffect(() => {
    if (monthly && monthly > 0) {
      form.setValue('annual', monthly * 12, { shouldValidate: true })
    }
  }, [monthly, form])

  // Auto-calculate monthly from breakdown sum
  const breakdown = useWatch({ control: form.control, name: 'breakdown' })
  useEffect(() => {
    if (breakdown) {
      const sum =
        (breakdown.compute || 0) +
        (breakdown.storage || 0) +
        (breakdown.network || 0) +
        (breakdown.licenses || 0) +
        (breakdown.personnel || 0)
      if (sum > 0 && Math.abs(sum - (form.getValues('monthly') || 0)) > 0.01) {
        form.setValue('monthly', sum, { shouldValidate: true })
      }
    }
  }, [breakdown, form])

  const onSubmit = async (data: UpdateCostEstimateInput) => {
    try {
      await updateCostEstimate({
        variables: {
          region: estimate.region,
          entity: estimate.entity,
          category: estimate.category,
          input: {
            ...data,
            lastUpdated: new Date().toISOString(),
          },
        },
      })

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

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

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

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <div className="grid grid-cols-3 gap-4 p-4 bg-studio-medium/20 rounded-lg">
              <div>
                <div className="text-sm text-studio-medium">Region</div>
                <div className="font-semibold">{estimate.region}</div>
              </div>
              <div>
                <div className="text-sm text-studio-medium">Entity</div>
                <div className="font-semibold">{estimate.entity}</div>
              </div>
              <div>
                <div className="text-sm text-studio-medium">Category</div>
                <div className="font-semibold">{estimate.category}</div>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="monthly"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Monthly Cost (USD)</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        step="0.01"
                        placeholder="0.00"
                        {...field}
                        value={field.value || ''}
                        onChange={(e) => {
                          const value = parseFloat(e.target.value) || 0
                          field.onChange(value)
                        }}
                      />
                    </FormControl>
                    <FormDescription>Auto-calculates annual (×12)</FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="annual"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Annual Cost (USD)</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        step="0.01"
                        placeholder="0.00"
                        {...field}
                        value={field.value || ''}
                        disabled
                      />
                    </FormControl>
                    <FormDescription>Auto-calculated from monthly</FormDescription>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="space-y-2">
              <FormLabel>Cost Breakdown (USD)</FormLabel>
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="breakdown.compute"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Compute</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.01"
                          placeholder="0.00"
                          {...field}
                          value={field.value || ''}
                          onChange={(e) => {
                            field.onChange(parseFloat(e.target.value) || 0)
                          }}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="breakdown.storage"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Storage</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.01"
                          placeholder="0.00"
                          {...field}
                          value={field.value || ''}
                          onChange={(e) => {
                            field.onChange(parseFloat(e.target.value) || 0)
                          }}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="breakdown.network"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Network</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.01"
                          placeholder="0.00"
                          {...field}
                          value={field.value || ''}
                          onChange={(e) => {
                            field.onChange(parseFloat(e.target.value) || 0)
                          }}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="breakdown.licenses"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Licenses</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.01"
                          placeholder="0.00"
                          {...field}
                          value={field.value || ''}
                          onChange={(e) => {
                            field.onChange(parseFloat(e.target.value) || 0)
                          }}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="breakdown.personnel"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Personnel</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.01"
                          placeholder="0.00"
                          {...field}
                          value={field.value || ''}
                          onChange={(e) => {
                            field.onChange(parseFloat(e.target.value) || 0)
                          }}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
              <FormDescription>Breakdown sum should equal monthly cost</FormDescription>
            </div>

            <FormField
              control={form.control}
              name="currency"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Currency</FormLabel>
                  <Select onValueChange={field.onChange} value={field.value || 'USD'}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="Select currency" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="USD">USD</SelectItem>
                      <SelectItem value="EUR">EUR</SelectItem>
                      <SelectItem value="GBP">GBP</SelectItem>
                      <SelectItem value="JPY">JPY</SelectItem>
                    </SelectContent>
                  </Select>
                  <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>
  )
}

