'use client'

import { useState, useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Separator } from '@/components/ui/separator'
import { Loader2, Eye, Activity } from 'lucide-react'

const visionSchema = z.object({
  odSphere: z.string().optional(),
  odCylindre: z.string().optional(),
  odAxe: z.string().optional(),
  ogSphere: z.string().optional(),
  ogCylindre: z.string().optional(),
  ogAxe: z.string().optional(),
  addition: z.string().optional(),
  pd: z.string().optional(),
  hauteur: z.string().optional(),
  notes: z.string().optional(),
})

type VisionFormValues = z.infer<typeof visionSchema>

interface Patient {
  id: string
  clientId: string
  dateCreation: string
  odSphere: number | null
  odCylindre: number | null
  odAxe: number | null
  ogSphere: number | null
  ogCylindre: number | null
  ogAxe: number | null
  addition: number | null
  pd: number | null
  hauteur: number | null
  notes: string | null
}

interface VisionFormProps {
  patient?: Patient | null
  clientId: string
  onSave: () => void
  onCancel: () => void
}

export function VisionForm({ patient, clientId, onSave, onCancel }: VisionFormProps) {
  const [loading, setLoading] = useState(false)

  const form = useForm<VisionFormValues>({
    resolver: zodResolver(visionSchema),
    defaultValues: {
      odSphere: '',
      odCylindre: '',
      odAxe: '',
      ogSphere: '',
      ogCylindre: '',
      ogAxe: '',
      addition: '',
      pd: '',
      hauteur: '',
      notes: '',
    },
  })

  // Reset form when patient changes
  useEffect(() => {
    if (patient) {
      form.reset({
        odSphere: patient.odSphere?.toString() || '',
        odCylindre: patient.odCylindre?.toString() || '',
        odAxe: patient.odAxe?.toString() || '',
        ogSphere: patient.ogSphere?.toString() || '',
        ogCylindre: patient.ogCylindre?.toString() || '',
        ogAxe: patient.ogAxe?.toString() || '',
        addition: patient.addition?.toString() || '',
        pd: patient.pd?.toString() || '',
        hauteur: patient.hauteur?.toString() || '',
        notes: patient.notes || '',
      })
    } else {
      form.reset({
        odSphere: '',
        odCylindre: '',
        odAxe: '',
        ogSphere: '',
        ogCylindre: '',
        ogAxe: '',
        addition: '',
        pd: '',
        hauteur: '',
        notes: '',
      })
    }
  }, [patient, form])

  const onSubmit = async (data: VisionFormValues) => {
    setLoading(true)
    try {
      const url = patient ? `/api/patients/${patient.id}` : '/api/patients'
      const method = patient ? 'PUT' : 'POST'

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          clientId: patient?.clientId || clientId,
          odSphere: data.odSphere ? parseFloat(data.odSphere) : null,
          odCylindre: data.odCylindre ? parseFloat(data.odCylindre) : null,
          odAxe: data.odAxe ? parseInt(data.odAxe) : null,
          ogSphere: data.ogSphere ? parseFloat(data.ogSphere) : null,
          ogCylindre: data.ogCylindre ? parseFloat(data.ogCylindre) : null,
          ogAxe: data.ogAxe ? parseInt(data.ogAxe) : null,
          addition: data.addition ? parseFloat(data.addition) : null,
          pd: data.pd ? parseFloat(data.pd) : null,
          hauteur: data.hauteur ? parseFloat(data.hauteur) : null,
          notes: data.notes || null,
        }),
      })

      if (response.ok) {
        onSave()
      } else {
        const error = await response.json()
        console.error('Error saving patient:', error)
        alert('Erreur lors de la sauvegarde de la fiche de vision')
      }
    } catch (error) {
      console.error('Error saving patient:', error)
      alert('Erreur lors de la sauvegarde de la fiche de vision')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog open={true} onOpenChange={onCancel}>
      <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Activity className="h-5 w-5" />
            {patient ? 'Modifier la Fiche de Vision' : 'Nouvelle Fiche de Vision'}
          </DialogTitle>
          <DialogDescription>
            Enregistrez les mesures de vision et les paramètres de prescription
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            {/* Right Eye (OD) */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base flex items-center gap-2">
                  <Eye className="h-4 w-4" />
                  Œil Droit (OD)
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-3 gap-4">
                  <FormField
                    control={form.control}
                    name="odSphere"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Sphère</FormLabel>
                        <FormControl>
                          <Input type="number" step="0.25" placeholder="0.00" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="odCylindre"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Cylindre</FormLabel>
                        <FormControl>
                          <Input type="number" step="0.25" placeholder="0.00" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="odAxe"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Axe (°)</FormLabel>
                        <FormControl>
                          <Input type="number" step="1" min="0" max="180" placeholder="0-180" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </CardContent>
            </Card>

            {/* Left Eye (OG) */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base flex items-center gap-2">
                  <Eye className="h-4 w-4" />
                  Œil Gauche (OG)
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-3 gap-4">
                  <FormField
                    control={form.control}
                    name="ogSphere"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Sphère</FormLabel>
                        <FormControl>
                          <Input type="number" step="0.25" placeholder="0.00" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="ogCylindre"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Cylindre</FormLabel>
                        <FormControl>
                          <Input type="number" step="0.25" placeholder="0.00" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="ogAxe"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Axe (°)</FormLabel>
                        <FormControl>
                          <Input type="number" step="1" min="0" max="180" placeholder="0-180" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </CardContent>
            </Card>

            {/* Additional Parameters */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Paramètres Additionnels</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-3 gap-4">
                  <FormField
                    control={form.control}
                    name="addition"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Addition</FormLabel>
                        <FormControl>
                          <Input type="number" step="0.25" placeholder="0.00" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="pd"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>DP (mm)</FormLabel>
                        <FormControl>
                          <Input type="number" step="0.5" placeholder="Distance pupillaire" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="hauteur"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>Hauteur (mm)</FormLabel>
                        <FormControl>
                          <Input type="number" step="0.5" placeholder="Hauteur" {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
              </CardContent>
            </Card>

            {/* Notes */}
            <Card>
              <CardHeader>
                <CardTitle className="text-base">Notes</CardTitle>
              </CardHeader>
              <CardContent>
                <FormField
                  control={form.control}
                  name="notes"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Textarea
                          placeholder="Notes supplémentaires sur la prescription..."
                          className="min-h-[80px]"
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </CardContent>
            </Card>

            <Separator />

            <div className="flex justify-end gap-3 pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={onCancel}
                disabled={loading}
              >
                Annuler
              </Button>
              <Button type="submit" disabled={loading}>
                {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {patient ? 'Mettre à jour' : 'Enregistrer la fiche'}
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
}
