"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Plus, Trash2, ChevronDown, ChevronUp } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"

const visionTypes = ["Loin", "Près", "Progressifs", "Lentilles"]
const cylinders = ["-4.00", "-3.50", "-3.00", "-2.50", "-2.00", "-1.50", "-1.00", "-0.75", "-0.50", "0"]
const spheres = ["+8.00", "+7.50", "+7.00", "+6.50", "+6.00", "+5.50", "+5.00", "+4.50", "+4.00", "+3.50", "+3.00", "+2.50", "+2.00", "+1.50", "+1.00", "+0.50", "0", "-0.50", "-1.00", "-1.50", "-2.00", "-2.50", "-3.00", "-3.50", "-4.00", "-4.50", "-5.00", "-5.50", "-6.00", "-6.50", "-7.00", "-7.50", "-8.00"]

type Client = {
  id: string
  name: string
}

type Vision = {
  id?: string
  type: string
  odSph: string | null
  odCyl: string | null
  odAxis: string | null
  odAdd: string | null
  odVa?: string | null
  ogSph: string | null
  ogCyl: string | null
  ogAxis: string | null
  ogAdd: string | null
  ogVa?: string | null
}

type Prescription = {
  id: string
  clientId: string
  visions: Vision[]
  pd: string | null
  notes?: string | null
}

type PrescriptionDialogProps = {
  clients: Client[]
  prescription?: Prescription | null
  trigger?: React.ReactNode
  open?: boolean
  onOpenChange?: (open: boolean) => void
}

export default function PrescriptionDialog({ clients, prescription, trigger, open: externalOpen, onOpenChange: externalOnOpenChange }: PrescriptionDialogProps) {
  const router = useRouter()
  const [internalOpen, setInternalOpen] = useState(false)
  const [loading, setLoading] = useState(false)
  const defaultVision: Vision = {
    type: "Vision de loin",
    odSph: "", odCyl: "", odAxis: "", odAdd: "", odVa: "",
    ogSph: "", ogCyl: "", ogAxis: "", ogAdd: "", ogVa: "",
  }

  const [formData, setFormData] = useState({
    clientId: "",
    pd: "",
    notes: "",
    visions: [defaultVision] as Vision[],
  })
  const [expandedVisionIndex, setExpandedVisionIndex] = useState<number | null>(0)

  const isOpen = externalOpen !== undefined ? externalOpen : internalOpen
  const setIsOpen = externalOnOpenChange || setInternalOpen
  const isEdit = !!prescription

  useEffect(() => {
    if (prescription) {
      setFormData({
        clientId: prescription.clientId,
        pd: prescription.pd || "",
        notes: prescription.notes || "",
        visions: prescription.visions.length > 0 ? prescription.visions.map(v => ({
          ...v,
          odSph: v.odSph || "",
          odCyl: v.odCyl || "",
          odAxis: v.odAxis || "",
          odAdd: v.odAdd || "",
          odVa: (v as any).odVa || "",
          ogSph: v.ogSph || "",
          ogCyl: v.ogCyl || "",
          ogAxis: v.ogAxis || "",
          ogAdd: v.ogAdd || "",
          ogVa: (v as any).ogVa || "",
        })) : [defaultVision],
      })
    }
  }, [prescription])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)

    try {
      const url = isEdit ? `/api/prescriptions/${prescription.id}` : '/api/prescriptions'
      const method = isEdit ? 'PUT' : 'POST'
      
      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
      })

      if (response.ok) {
        setIsOpen(false)
        if (!isEdit) {
          setFormData({
            clientId: "",
            pd: "",
            notes: "",
            visions: [defaultVision],
          })
          setExpandedVisionIndex(0)
        }
        router.refresh()
      } else {
        const error = await response.json()
        alert(error.error || 'Failed to save prescription')
      }
    } catch (error) {
      console.error('Error saving prescription:', error)
      alert('Failed to save prescription')
    } finally {
      setLoading(false)
    }
  }

  const dialogTrigger = trigger || (
    <Button className="bg-teal-600 hover:bg-teal-700">
      <Plus className="mr-2 h-4 w-4" />
      Nouvelle ordonnance
    </Button>
  )

  return (
    <Dialog open={isOpen} onOpenChange={(open) => setIsOpen(open)}>
      <DialogTrigger asChild>
        {dialogTrigger}
      </DialogTrigger>
      <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{isEdit ? 'Modifier l\'ordonnance' : 'Nouvelle ordonnance'}</DialogTitle>
          <DialogDescription>
            {isEdit ? 'Modifier les informations de l\'ordonnance' : 'Enregistrer une nouvelle prescription'}
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit}>
          <div className="py-4 space-y-4">
            <div className="grid gap-2">
              <Label>Client</Label>
              <Select 
                value={formData.clientId}
                onValueChange={(value) => setFormData({ ...formData, clientId: value })}
                required
              >
                <SelectTrigger>
                  <SelectValue placeholder="Sélectionner un client" />
                </SelectTrigger>
                <SelectContent>
                  {clients.map((client) => (
                    <SelectItem key={client.id} value={client.id}>{client.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <Label>PD (Distance pupillaire)</Label>
              <Input 
                placeholder="Ex: 62" 
                value={formData.pd}
                onChange={(e) => setFormData({ ...formData, pd: e.target.value })}
              />
            </div>

            <div className="space-y-3 mt-4">
              {formData.visions.map((vision, visionIdx) => (
                <div key={visionIdx} className="border rounded-lg overflow-hidden border-teal-100 shadow-sm">
                  <div 
                    className={`flex items-center justify-between p-3 cursor-pointer select-none ${expandedVisionIndex === visionIdx ? 'bg-teal-50 text-teal-900 border-b border-teal-100' : 'bg-white text-slate-700 hover:bg-slate-50'}`}
                    onClick={() => setExpandedVisionIndex(expandedVisionIndex === visionIdx ? null : visionIdx)}
                  >
                    <div className="flex items-center gap-2">
                      <Badge variant="outline" className="bg-teal-100 text-teal-800 border-teal-200">Vision</Badge>
                      <span className="font-semibold text-sm">{vision.type}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      {formData.visions.length > 1 && (
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          className="h-7 w-7 text-destructive"
                          onClick={(e) => {
                            e.stopPropagation()
                            const newVisions = formData.visions.filter((_, i) => i !== visionIdx)
                            setFormData({ ...formData, visions: newVisions })
                            if (expandedVisionIndex === visionIdx) setExpandedVisionIndex(null)
                          }}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      )}
                      {expandedVisionIndex === visionIdx ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                    </div>
                  </div>
                  
                  {expandedVisionIndex === visionIdx && (
                    <div className="p-4 space-y-4 bg-white animate-in slide-in-from-top-1 duration-200">
                      <div className="grid gap-2">
                        <Label className="text-xs text-muted-foreground uppercase tracking-wider font-bold">Type de vision</Label>
                        <select 
                          className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:ring-2 focus:ring-teal-500 outline-none transition-shadow"
                          value={vision.type}
                          onChange={(e) => {
                            const newVisions = [...formData.visions]
                            newVisions[visionIdx].type = e.target.value
                            setFormData({ ...formData, visions: newVisions })
                          }}
                        >
                          <option value="Vision de loin">Vision de loin</option>
                          <option value="Vision de près">Vision de près</option>
                          <option value="Vision intermédiaire">Vision intermédiaire</option>
                          <option value="Progressifs">Progressifs</option>
                          <option value="Bifocaux">Bifocaux</option>
                        </select>
                      </div>

                      <div className="grid grid-cols-2 gap-6 text-sm">
                        <div className="space-y-4">
                          <h4 className="text-sm font-bold border-b border-teal-50 pb-1 text-teal-700">Oeil Droit (OD)</h4>
                          <div className="grid grid-cols-3 gap-2">
                            <div className="grid gap-1.5">
                              <Label className="text-[10px] uppercase text-muted-foreground">Sph</Label>
                              <Select value={vision.odSph || ""} onValueChange={(val) => {
                                const newVisions = [...formData.visions]; newVisions[visionIdx].odSph = val; setFormData({...formData, visions: newVisions});
                              }}>
                                <SelectTrigger className="h-8"><SelectValue placeholder="-" /></SelectTrigger>
                                <SelectContent>{spheres.map(s => <SelectItem key={s} value={s}>{s}</SelectItem>)}</SelectContent>
                              </Select>
                            </div>
                            <div className="grid gap-1.5">
                              <Label className="text-[10px] uppercase text-muted-foreground">Cyl</Label>
                              <Select value={vision.odCyl || ""} onValueChange={(val) => {
                                const newVisions = [...formData.visions]; newVisions[visionIdx].odCyl = val; setFormData({...formData, visions: newVisions});
                              }}>
                                <SelectTrigger className="h-8"><SelectValue placeholder="-" /></SelectTrigger>
                                <SelectContent>{cylinders.map(c => <SelectItem key={c} value={c}>{c}</SelectItem>)}</SelectContent>
                              </Select>
                            </div>
                            <div className="grid gap-1.5">
                              <Label className="text-[10px] uppercase text-muted-foreground">Axe</Label>
                              <Input className="h-8 px-2" value={vision.odAxis || ""} onChange={(e) => {
                                const newVisions = [...formData.visions]; newVisions[visionIdx].odAxis = e.target.value; setFormData({...formData, visions: newVisions});
                              }} />
                            </div>
                          </div>
                          <div className="grid grid-cols-2 gap-2">
                            <div className="grid gap-1.5">
                              <Label className="text-[10px] uppercase text-muted-foreground">Add</Label>
                              <Select value={vision.odAdd || ""} onValueChange={(val) => {
                                const newVisions = [...formData.visions]; newVisions[visionIdx].odAdd = val; setFormData({...formData, visions: newVisions});
                              }}>
                                <SelectTrigger className="h-8"><SelectValue placeholder="-" /></SelectTrigger>
                                <SelectContent>{["+1.00", "+1.25", "+1.50", "+1.75", "+2.00", "+2.25", "+2.50", "+2.75", "+3.00"].map(a => <SelectItem key={a} value={a}>{a}</SelectItem>)}</SelectContent>
                              </Select>
                            </div>
                            <div className="grid gap-1.5">
                              <Label className="text-[10px] uppercase text-muted-foreground">Av</Label>
                              <Input className="h-8 px-2" value={vision.odVa || ""} onChange={(e) => {
                                const newVisions = [...formData.visions]; newVisions[visionIdx].odVa = e.target.value; setFormData({...formData, visions: newVisions});
                              }} />
                            </div>
                          </div>
                        </div>

                        <div className="space-y-4">
                          <h4 className="text-sm font-bold border-b border-teal-50 pb-1 text-teal-700">Oeil Gauche (OG)</h4>
                          <div className="grid grid-cols-3 gap-2">
                            <div className="grid gap-1.5">
                              <Label className="text-[10px] uppercase text-muted-foreground">Sph</Label>
                              <Select value={vision.ogSph || ""} onValueChange={(val) => {
                                const newVisions = [...formData.visions]; newVisions[visionIdx].ogSph = val; setFormData({...formData, visions: newVisions});
                              }}>
                                <SelectTrigger className="h-8"><SelectValue placeholder="-" /></SelectTrigger>
                                <SelectContent>{spheres.map(s => <SelectItem key={s} value={s}>{s}</SelectItem>)}</SelectContent>
                              </Select>
                            </div>
                            <div className="grid gap-1.5">
                              <Label className="text-[10px] uppercase text-muted-foreground">Cyl</Label>
                              <Select value={vision.ogCyl || ""} onValueChange={(val) => {
                                const newVisions = [...formData.visions]; newVisions[visionIdx].ogCyl = val; setFormData({...formData, visions: newVisions});
                              }}>
                                <SelectTrigger className="h-8"><SelectValue placeholder="-" /></SelectTrigger>
                                <SelectContent>{cylinders.map(c => <SelectItem key={c} value={c}>{c}</SelectItem>)}</SelectContent>
                              </Select>
                            </div>
                            <div className="grid gap-1.5">
                              <Label className="text-[10px] uppercase text-muted-foreground">Axe</Label>
                              <Input className="h-8 px-2" value={vision.ogAxis || ""} onChange={(e) => {
                                const newVisions = [...formData.visions]; newVisions[visionIdx].ogAxis = e.target.value; setFormData({...formData, visions: newVisions});
                              }} />
                            </div>
                          </div>
                          <div className="grid grid-cols-2 gap-2">
                            <div className="grid gap-1.5">
                              <Label className="text-[10px] uppercase text-muted-foreground">Add</Label>
                              <Select value={vision.ogAdd || ""} onValueChange={(val) => {
                                const newVisions = [...formData.visions]; newVisions[visionIdx].ogAdd = val; setFormData({...formData, visions: newVisions});
                              }}>
                                <SelectTrigger className="h-8"><SelectValue placeholder="-" /></SelectTrigger>
                                <SelectContent>{["+1.00", "+1.25", "+1.50", "+1.75", "+2.00", "+2.25", "+2.50", "+2.75", "+3.00"].map(a => <SelectItem key={a} value={a}>{a}</SelectItem>)}</SelectContent>
                              </Select>
                            </div>
                            <div className="grid gap-1.5">
                              <Label className="text-[10px] uppercase text-muted-foreground">Av</Label>
                              <Input className="h-8 px-2" value={vision.ogVa || ""} onChange={(e) => {
                                const newVisions = [...formData.visions]; newVisions[visionIdx].ogVa = e.target.value; setFormData({...formData, visions: newVisions});
                              }} />
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              ))}

              <Button
                type="button"
                variant="outline"
                size="sm"
                className="w-full mt-2 border-dashed border-teal-300 text-teal-700 hover:bg-teal-50"
                onClick={() => {
                  const newVisions = [...formData.visions, { ...defaultVision, type: "Vision de près" }]
                  setFormData({ ...formData, visions: newVisions })
                  setExpandedVisionIndex(newVisions.length - 1)
                }}
              >
                <Plus className="h-4 w-4 mr-2" />
                Ajouter un type de vision
              </Button>
            </div>
          <div className="grid gap-2">
            <Label>Notes</Label>
            <Input 
              placeholder="Notes supplémentaires..." 
              value={formData.notes}
              onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
            />
          </div>
        </div>
          <DialogFooter className="mt-4">
            <Button type="submit" className="bg-teal-600 hover:bg-teal-700" disabled={loading}>
              {loading ? 'Enregistrement...' : isEdit ? 'Mettre à jour' : 'Enregistrer'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
