"use client"

import { useState, useEffect } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Search, Eye, Pencil, Trash2, ChevronLeft, ChevronRight } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { formatDate } from "@/lib/utils"
import { Label } from "@/components/ui/label"
import PrescriptionDialog from "./PrescriptionDialog"

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

type PrescriptionWithClient = {
  id: string
  clientId: string
  client: { name: string } | null
  visions: Vision[]
  pd: string | null
  createdAt: Date
}

type Client = {
  id: string
  name: string
}

type PrescriptionsTableProps = {
  prescriptions: PrescriptionWithClient[]
  visionTypes: (string | undefined)[]
  clients: Client[]
  total: number
  page: number
  totalPages: number
}

export default function PrescriptionsTable({ prescriptions, visionTypes, clients, total, page, totalPages }: PrescriptionsTableProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [searchQuery, setSearchQuery] = useState(searchParams.get('search') || '')
  const [visionTypeFilter, setVisionTypeFilter] = useState(searchParams.get('visionType') || 'all')
  const [deleteId, setDeleteId] = useState<string | null>(null)
  const [deleting, setDeleting] = useState(false)
  const [viewPrescription, setViewPrescription] = useState<PrescriptionWithClient | null>(null)
  const [editPrescription, setEditPrescription] = useState<PrescriptionWithClient | null>(null)

  useEffect(() => {
    const timer = setTimeout(() => {
      const params = new URLSearchParams()
      if (searchQuery) params.set('search', searchQuery)
      if (visionTypeFilter !== 'all') params.set('visionType', visionTypeFilter)
      params.set('page', '1')
      router.push(`?${params.toString()}`)
    }, 500)
    return () => clearTimeout(timer)
  }, [searchQuery, visionTypeFilter, router])

  const handlePageChange = (newPage: number) => {
    const params = new URLSearchParams()
    const search = searchParams.get('search')
    const visionType = searchParams.get('visionType')
    if (search) params.set('search', search)
    if (visionType) params.set('visionType', visionType)
    params.set('page', String(newPage))
    router.push(`?${params.toString()}`)
  }

  const handleDelete = async (id: string) => {
    setDeleting(true)
    try {
      const response = await fetch(`/api/prescriptions/${id}`, { method: 'DELETE' })
      if (response.ok) {
        router.refresh()
      }
    } catch (error) {
      console.error('Error deleting prescription:', error)
    } finally {
      setDeleting(false)
      setDeleteId(null)
    }
  }

  const formatOD = (v: Vision) => {
    const parts = []
    if (v.odSph) parts.push(`SPH ${v.odSph}`)
    if (v.odCyl) parts.push(`CYL ${v.odCyl}`)
    if (v.odAxis) parts.push(`AX ${v.odAxis}`)
    if (v.odAdd) parts.push(`ADD ${v.odAdd}`)
    return parts.length > 0 ? parts.join(' ') : '-'
  }

  const formatOG = (v: Vision) => {
    const parts = []
    if (v.ogSph) parts.push(`SPH ${v.ogSph}`)
    if (v.ogCyl) parts.push(`CYL ${v.ogCyl}`)
    if (v.ogAxis) parts.push(`AX ${v.ogAxis}`)
    if (v.ogAdd) parts.push(`ADD ${v.ogAdd}`)
    return parts.length > 0 ? parts.join(' ') : '-'
  }

  return (
    <>
      <div className="flex items-center gap-4">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input 
            placeholder="Rechercher une ordonnance..." 
            className="pl-10"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>
        <Select value={visionTypeFilter} onValueChange={setVisionTypeFilter}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Type de vision" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Tous les types</SelectItem>
            {visionTypes.map((type) => (
              <SelectItem key={type || ''} value={type || ''}>{type}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div className="rounded-lg border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Client</TableHead>
              <TableHead>Date</TableHead>
              <TableHead>Type de vision</TableHead>
              <TableHead>OD</TableHead>
              <TableHead>OG</TableHead>
              <TableHead>PD</TableHead>
              <TableHead className="text-right">Actions</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {prescriptions.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center text-muted-foreground py-8">
                  Aucune ordonnance trouvée
                </TableCell>
              </TableRow>
            ) : (
              prescriptions.map((prescription) => (
                <TableRow key={prescription.id}>
                  <TableCell className="font-medium">{prescription.client?.name || '-'}</TableCell>
                  <TableCell className="text-sm">{formatDate(prescription.createdAt.toString())}</TableCell>
                  <TableCell>
                    <div className="flex flex-col gap-1">
                      {prescription.visions.map((v, i) => (
                        <Badge key={i} variant="secondary" className="text-[10px] px-1.5 h-4 w-fit">
                          {v.type}
                        </Badge>
                      ))}
                      {prescription.visions.length === 0 && '-'}
                    </div>
                  </TableCell>
                  <TableCell className="text-[11px] max-w-[150px] truncate">
                    {prescription.visions.map((v, i) => (
                      <div key={i} className="truncate">
                        <span className="font-semibold">{v.type[0]}:</span> {formatOD(v)}
                      </div>
                    ))}
                    {prescription.visions.length === 0 && '-'}
                  </TableCell>
                  <TableCell className="text-[11px] max-w-[150px] truncate">
                    {prescription.visions.map((v, i) => (
                      <div key={i} className="truncate">
                        <span className="font-semibold">{v.type[0]}:</span> {formatOG(v)}
                      </div>
                    ))}
                    {prescription.visions.length === 0 && '-'}
                  </TableCell>
                  <TableCell>{prescription.pd || '-'}</TableCell>
                  <TableCell className="text-right">
                    <div className="flex items-center justify-end gap-1">
                      <Button variant="ghost" size="icon" onClick={() => setViewPrescription(prescription)}>
                        <Eye className="h-4 w-4" />
                      </Button>
                      <Button variant="ghost" size="icon" onClick={() => setEditPrescription(prescription)}>
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Dialog open={deleteId === prescription.id} onOpenChange={(open) => !open && setDeleteId(null)}>
                        <DialogTrigger asChild>
                          <Button variant="ghost" size="icon" className="text-red-500" onClick={() => setDeleteId(prescription.id)}>
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </DialogTrigger>
                        <DialogContent>
                          <DialogHeader>
                            <DialogTitle>Confirmer la suppression</DialogTitle>
                            <DialogDescription>
                              Êtes-vous sûr de vouloir supprimer cette ordonnance ? Cette action est irréversible.
                            </DialogDescription>
                          </DialogHeader>
                          <DialogFooter>
                            <Button variant="outline" onClick={() => setDeleteId(null)}>Annuler</Button>
                            <Button variant="destructive" onClick={() => handleDelete(prescription.id)} disabled={deleting}>
                              {deleting ? 'Suppression...' : 'Supprimer'}
                            </Button>
                          </DialogFooter>
                        </DialogContent>
                      </Dialog>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-between px-2 py-4">
          <div className="text-sm text-muted-foreground">
            Affichage de {((page - 1) * 10) + 1} à {Math.min(page * 10, total)} sur {total} résultats
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              disabled={page <= 1}
              onClick={() => handlePageChange(page - 1)}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <span className="text-sm">Page {page} sur {totalPages}</span>
            <Button
              variant="outline"
              size="sm"
              disabled={page >= totalPages}
              onClick={() => handlePageChange(page + 1)}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      <Dialog open={!!viewPrescription} onOpenChange={(open) => !open && setViewPrescription(null)}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>Détails de l'ordonnance</DialogTitle>
          </DialogHeader>
          {viewPrescription && (
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-muted-foreground text-sm">Client</Label>
                  <p className="font-medium">{viewPrescription.client?.name || '-'}</p>
                </div>
              </div>
              <div className="space-y-4 max-h-[400px] overflow-y-auto pr-2">
                {viewPrescription.visions.map((v, i) => (
                  <div key={i} className="border rounded-md p-3 bg-muted/20">
                    <div className="font-bold text-teal-700 mb-2 border-b pb-1 flex justify-between">
                      <span>{v.type}</span>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label className="text-[10px] text-muted-foreground uppercase">OD (Oeil Droit)</Label>
                        <p className="text-sm font-medium">{formatOD(v)}</p>
                      </div>
                      <div>
                        <Label className="text-[10px] text-muted-foreground uppercase">OG (Oeil Gauche)</Label>
                        <p className="text-sm font-medium">{formatOG(v)}</p>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
              <div className="grid grid-cols-2 gap-4 border-t pt-4">
                <div>
                  <Label className="text-muted-foreground text-sm">Distance pupillaire</Label>
                  <p className="font-medium">{viewPrescription.pd || '-'}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground text-sm">Date</Label>
                  <p className="font-medium">{formatDate(viewPrescription.createdAt.toString())}</p>
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setViewPrescription(null)}>Fermer</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <PrescriptionDialog clients={clients} prescription={editPrescription} trigger={<span />} open={!!editPrescription} onOpenChange={(open) => !open && setEditPrescription(null)} />
    </>
  )
}