"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { cn } from "@/lib/utils"
import { ShoppingBag, ArrowLeft, Glasses, User, MapPin, Phone, Mail, ArrowUpDown, ArrowUp, ArrowDown, Pencil, ShieldCheck, Lock, Check, Download, Calendar, Plus } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Input } from "@/components/ui/input"
import PrescriptionDialog from "@/app/(dashboard)/prescriptions/PrescriptionDialog"

type InvoiceItem = {
  id: string
  quantity: number
  unitPrice: any
  total: any
  product: {
    id: string
    name: string
    sku: string
    category: string
  }
}

type Invoice = {
  id: string
  invoiceNumber: string
  total: any
  discount: any
  paidAmount: any
  paymentMethod: string | null
  status: string
  seller?: { id: string; name: string } | null
  lastPaymentSeller?: { id: string; name: string } | null
  createdAt: Date
  items: InvoiceItem[]
}

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
  createdAt: Date
  visions: Vision[]
  pd: string | null
  notes: string | null
  products: {
    id: string
    name: string
    sku: string
    salePrice: any
  }[]
}

type Appointment = {
  id: string
  clientId: string
  date: Date
  duration: number
  type: string
  status: string
  notes: string | null
  createdAt: Date
}

type ClientData = {
  id: string
  name: string
  phone: string
  email: string | null
  cin: string | null
  address: string | null
  notes: string | null
  createdAt: Date
  totalPurchases: number
  invoiceCount: number
  invoices: Invoice[]
  prescriptions: Prescription[]
  appointments: Appointment[]
}

export default function ClientDetails({ client }: { client: ClientData }) {
  const router = useRouter()
  const [sortBy, setSortBy] = useState<keyof Invoice | 'seller.name'>('createdAt')
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')

  const [editInvoice, setEditInvoice] = useState<Invoice | null>(null)
  const [additionalPayment, setAdditionalPayment] = useState("")
  const [updating, setUpdating] = useState(false)
  
  const [editClient, setEditClient] = useState(false)
  const [clientForm, setClientForm] = useState({
    name: client.name,
    phone: client.phone,
    email: client.email || '',
    cin: client.cin || '',
    address: client.address || '',
    notes: client.notes || '',
  })
  const [savingClient, setSavingClient] = useState(false)
  
  type Seller = { id: string; name: string }
  const [sellers, setSellers] = useState<Seller[]>([])
  const [showPinDialog, setShowPinDialog] = useState(false)
  const [selectedSeller, setSelectedSeller] = useState("")
  const [pin, setPin] = useState("")
  const [verifyingPin, setVerifyingPin] = useState(false)

  useEffect(() => {
    fetch('/api/sellers').then(r => r.json()).then(setSellers).catch(() => {})
  }, [])

  const handleSaveClient = async () => {
    if (!clientForm.name || !clientForm.phone) return
    
    setSavingClient(true)
    try {
      const response = await fetch(`/api/clients/${client.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(clientForm),
      })

      if (response.ok) {
        setEditClient(false)
        router.refresh()
      } else {
        const error = await response.json()
        alert(error.error || 'Erreur lors de la mise à jour')
      }
    } catch (error) {
      console.error('Error updating client:', error)
      alert('Erreur lors de la mise à jour')
      } finally {
      setSavingClient(false)
    }
  }

  const [newAppointment, setNewAppointment] = useState(false)
  const [appointmentForm, setAppointmentForm] = useState({
    date: '',
    time: '',
    duration: '30',
    type: 'CONSULTATION',
    notes: '',
  })
  const [savingAppointment, setSavingAppointment] = useState(false)

  const handleSaveAppointment = async () => {
    if (!appointmentForm.date || !appointmentForm.time) return
    
    setSavingAppointment(true)
    try {
      const dateTime = new Date(`${appointmentForm.date}T${appointmentForm.time}`)
      const response = await fetch('/api/appointments', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          clientId: client.id,
          date: dateTime.toISOString(),
          duration: parseInt(appointmentForm.duration),
          type: appointmentForm.type,
          notes: appointmentForm.notes || null,
        }),
      })

      if (response.ok) {
        setNewAppointment(false)
        setAppointmentForm({ date: '', time: '', duration: '30', type: 'CONSULTATION', notes: '' })
        router.refresh()
      } else {
        const error = await response.json()
        alert(error.error || 'Erreur lors de la création du rendez-vous')
      }
    } catch (error) {
      console.error('Error creating appointment:', error)
      alert('Erreur lors de la création du rendez-vous')
    } finally {
      setSavingAppointment(false)
    }
  }

  const [editPrescription, setEditPrescription] = useState<Prescription | null>(null)

  const handleUpdatePayment = async () => {
    if (!editInvoice || !additionalPayment) return
    
    const amount = parseFloat(additionalPayment)
    if (isNaN(amount) || amount <= 0) return

    setShowPinDialog(true)
  }

  const validatePinAndUpdate = async () => {
    if (!editInvoice || !selectedSeller || !pin) return

    setVerifyingPin(true)
    try {
      const verifyRes = await fetch('/api/sellers/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sellerId: selectedSeller, pin }),
      })

      if (!verifyRes.ok) {
        const err = await verifyRes.json()
        alert(err.error || 'PIN invalide')
        return
      }

      setVerifyingPin(false)
      setShowPinDialog(false)
      setPin("")
      setUpdating(true)
      try {
        const amount = parseFloat(additionalPayment)
        const currentPaid = Number(editInvoice.paidAmount)
        const newPaid = Math.min(currentPaid + amount, Number(editInvoice.total))
        const newStatus = newPaid >= Number(editInvoice.total) ? 'PAID' : 'PENDING'

        const response = await fetch(`/api/invoices/${editInvoice.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ paidAmount: newPaid, status: newStatus }),
        })

        if (response.ok) {
          setEditInvoice(null)
          setAdditionalPayment("")
          setSelectedSeller("")
          router.refresh()
        } else {
          const error = await response.json()
          alert(error.error || 'Failed to update payment')
        }
      } catch (error) {
        console.error('Error updating payment:', error)
        alert('Failed to update payment')
      } finally {
        setUpdating(false)
      }
    } catch (error) {
      console.error('Error verifying PIN:', error)
      alert('Erreur de vérification')
    } finally {
      setVerifyingPin(false)
    }
  }

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('fr-MA', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(amount) + ' DH'
  }

  const handleSort = (column: keyof Invoice | 'seller.name') => {
    if (sortBy === column) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
    } else {
      setSortBy(column)
      setSortOrder('asc')
    }
  }

  const sortedInvoices = [...client.invoices].sort((a: any, b: any) => {
    let aValue: any, bValue: any
    
    if (sortBy === 'seller.name') {
      aValue = a.seller?.name || ''
      bValue = b.seller?.name || ''
    } else {
      aValue = a[sortBy]
      bValue = b[sortBy]
    }

    if (aValue < bValue) return sortOrder === 'asc' ? -1 : 1
    if (aValue > bValue) return sortOrder === 'asc' ? 1 : -1
    return 0
  })

  const SortHeader = ({ column, label, align = 'left' }: { column: keyof Invoice | 'seller.name', label: string, align?: 'left' | 'right' }) => {
    const isSorted = sortBy === column
    return (
      <TableHead 
        className={cn("cursor-pointer hover:bg-muted/50 transition-colors group", align === 'right' && "text-right")}
        onClick={() => handleSort(column)}
      >
        <div className={cn("flex items-center gap-1", align === 'right' && "justify-end")}>
          {label}
          <span className="text-muted-foreground group-hover:text-foreground transition-colors">
            {!isSorted && <ArrowUpDown className="h-3 w-3 opacity-0 group-hover:opacity-100" />}
            {isSorted && sortOrder === 'asc' && <ArrowUp className="h-3 w-3 text-primary" />}
            {isSorted && sortOrder === 'desc' && <ArrowDown className="h-3 w-3 text-primary" />}
          </span>
        </div>
      </TableHead>
    )
  }

  const formatDate = (date: Date) => {
    return new Date(date).toLocaleDateString('fr-MA', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    })
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'PAID':
        return <Badge className="bg-green-100 text-green-800 hover:bg-green-100 border-green-200">Payée</Badge>
      case 'PENDING':
        return <Badge variant="outline" className="text-orange-600 border-orange-200 bg-orange-50 hover:bg-orange-50">En attente</Badge>
      case 'CANCELLED':
        return <Badge variant="destructive">Annulée</Badge>
      default:
        return <Badge>{status}</Badge>
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Button variant="outline" size="icon" onClick={() => router.push('/clients')}>
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div>
          <h1 className="text-3xl font-bold text-slate-800">{client.name}</h1>
          <p className="text-muted-foreground">Client depuis le {formatDate(client.createdAt)}</p>
        </div>
      </div>

      <div className="grid gap-6 md:grid-cols-4">
        <Card className="md:col-span-1 h-fit">
          <CardHeader>
            <CardTitle>Résumé</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center gap-3 text-sm">
              <Phone className="h-4 w-4 text-muted-foreground shrink-0" />
              <span className="break-all">{client.phone}</span>
            </div>
            {client.email && (
              <div className="flex items-center gap-3 text-sm">
                <Mail className="h-4 w-4 text-muted-foreground shrink-0" />
                <span className="break-all">{client.email}</span>
              </div>
            )}
            {client.cin && (
              <div className="flex items-center gap-3 text-sm">
                <User className="h-4 w-4 text-muted-foreground shrink-0" />
                <span>CIN: {client.cin}</span>
              </div>
            )}
            {client.address && (
              <div className="flex items-start gap-3 text-sm">
                <MapPin className="h-4 w-4 text-muted-foreground shrink-0 mt-0.5" />
                <span className="line-clamp-3">{client.address}</span>
              </div>
            )}
            <div className="pt-4 border-t mt-4 space-y-2">
              <div className="flex justify-between items-center px-1">
                <span className="text-muted-foreground text-sm">Total achats</span>
                <span className="font-bold text-primary">{client.totalPurchases.toLocaleString()} DH</span>
              </div>
              <div className="flex justify-between items-center px-1">
                <span className="text-muted-foreground text-sm">Factures</span>
                <Badge variant="secondary">{client.invoiceCount}</Badge>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="md:col-span-3">
          <Tabs defaultValue="invoices" className="w-full">
            <CardHeader className="pb-0 border-b">
              <TabsList className="w-full justify-start rounded-none border-b-0 bg-transparent p-0">
                <TabsTrigger 
                  value="info" 
                  className="data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none border-b-2 border-transparent rounded-none px-6 py-3"
                >
                  Informations
                </TabsTrigger>
              <TabsTrigger 
                  value="products"
                  className="data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none border-b-2 border-transparent rounded-none px-6 py-3"
                >
                  Produits achetés
                </TabsTrigger>
                <TabsTrigger 
                  value="invoices"
                  className="data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none border-b-2 border-transparent rounded-none px-6 py-3"
                >
                  Achats
                </TabsTrigger>
                <TabsTrigger 
                  value="prescriptions"
                  className="data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none border-b-2 border-transparent rounded-none px-6 py-3"
                >
                  Ordonnances
                </TabsTrigger>
                <TabsTrigger 
                  value="appointments"
                  className="data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none border-b-2 border-transparent rounded-none px-6 py-3"
                >
                  Rendez-vous
                </TabsTrigger>
              </TabsList>
            </CardHeader>
            <CardContent className="pt-6">
              
              <TabsContent value="info" className="space-y-4 mt-0 focus-visible:outline-none focus-visible:ring-0">
                <div className="flex justify-end">
                  <Button variant="outline" size="sm" onClick={() => {
                    setClientForm({
                      name: client.name,
                      phone: client.phone,
                      email: client.email || '',
                      cin: client.cin || '',
                      address: client.address || '',
                      notes: client.notes || '',
                    })
                    setEditClient(true)
                  }}>
                    <Pencil className="h-4 w-4 mr-2" />
                    Modifier
                  </Button>
                </div>
                <div className="grid grid-cols-2 gap-y-6 gap-x-4">
                  <div>
                    <h3 className="font-medium text-sm text-muted-foreground mb-1">Nom Complet</h3>
                    <p className="text-base">{client.name}</p>
                  </div>
                  <div>
                    <h3 className="font-medium text-sm text-muted-foreground mb-1">Téléphone</h3>
                    <p className="text-base">{client.phone}</p>
                  </div>
                  <div>
                    <h3 className="font-medium text-sm text-muted-foreground mb-1">Email</h3>
                    <p className="text-base">{client.email || '-'}</p>
                  </div>
                  <div>
                    <h3 className="font-medium text-sm text-muted-foreground mb-1">CIN</h3>
                    <p className="text-base">{client.cin || '-'}</p>
                  </div>
                  <div className="col-span-2">
                    <h3 className="font-medium text-sm text-muted-foreground mb-1">Adresse</h3>
                    <p className="text-base">{client.address || '-'}</p>
                  </div>
                  <div className="col-span-2">
                    <h3 className="font-medium text-sm text-muted-foreground mb-1">Notes</h3>
                    <p className="whitespace-pre-wrap text-base bg-muted/30 p-4 rounded-md min-h-[100px] border">
                      {client.notes || <span className="text-muted-foreground italic">Aucune note</span>}
                    </p>
                  </div>
                </div>
              </TabsContent>

              <TabsContent value="products" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
                {client.invoices.flatMap(inv => inv.items || []).length === 0 ? (
                  <div className="text-center py-12 bg-muted/20 rounded-lg border border-dashed">
                    <ShoppingBag className="h-10 w-10 mx-auto mb-3 text-muted-foreground opacity-50" />
                    <p className="text-muted-foreground">Aucun produit acheté pour ce client.</p>
                  </div>
                ) : (
                  <div className="rounded-md border">
                    <Table>
                      <TableHeader className="bg-muted/50">
                        <TableRow>
                          <TableHead>Produit</TableHead>
                          <TableHead>Catégorie</TableHead>
                          <TableHead>N° Facture</TableHead>
                          <TableHead>Date</TableHead>
                          <TableHead className="text-right">Qté</TableHead>
                          <TableHead className="text-right">Prix unit.</TableHead>
                          <TableHead className="text-right">Total</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {client.invoices.flatMap(inv =>
                          (inv.items || []).map((item: InvoiceItem) => (
                            <TableRow key={item.id}>
                              <TableCell>
                                <div>
                                  <p className="font-medium">{item.product.name}</p>
                                  <p className="text-xs text-muted-foreground">{item.product.sku}</p>
                                </div>
                              </TableCell>
                              <TableCell>
                                <Badge variant="secondary" className="text-xs">{item.product.category}</Badge>
                              </TableCell>
                              <TableCell className="text-primary font-medium text-sm">{inv.invoiceNumber}</TableCell>
                              <TableCell className="text-sm">{formatDate(inv.createdAt)}</TableCell>
                              <TableCell className="text-right font-semibold">{item.quantity}</TableCell>
                              <TableCell className="text-right text-sm">{Number(item.unitPrice).toLocaleString()} DH</TableCell>
                              <TableCell className="text-right font-medium text-teal-700">{Number(item.total).toLocaleString()} DH</TableCell>
                            </TableRow>
                          ))
                        )}
                      </TableBody>
                    </Table>
                  </div>
                )}
              </TabsContent>

              <TabsContent value="invoices" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
                {client.invoices.length === 0 ? (
                   <div className="text-center py-12 bg-muted/20 rounded-lg border border-dashed">
                     <p className="text-muted-foreground">Aucun achat enregistré pour ce client.</p>
                   </div>
                ) : (
                  <div className="rounded-md border">
                    <Table>
                      <TableHeader className="bg-muted/50">
                        <TableRow>
                          <SortHeader column="invoiceNumber" label="N° Facture" />
                          <SortHeader column="seller.name" label="Vendeur" />
                          <SortHeader column="createdAt" label="Date" />
                          <TableHead>Statut</TableHead>
                          <SortHeader column="discount" label="Remise" align="right" />
                          <SortHeader column="total" label="Total" align="right" />
                          <TableHead className="text-right">Actions</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {sortedInvoices.map((invoice) => (
                          <TableRow key={invoice.id}>
                            <TableCell className="font-medium text-primary">{invoice.invoiceNumber}</TableCell>
                            <TableCell>
                              <Badge variant="outline" className="font-normal">
                                {invoice.seller?.name || '-'}
                              </Badge>
                            </TableCell>
                            <TableCell>{formatDate(invoice.createdAt)}</TableCell>
                            <TableCell>
                              {invoice.status === 'PENDING' ? (
                                <div className="text-sm">
                                  <div className="text-muted-foreground">Payé: {formatCurrency(Number(invoice.paidAmount))}</div>
                                  <div className="text-amber-600">Reste: {formatCurrency(Number(invoice.total) - Number(invoice.paidAmount))}</div>
                                </div>
                              ) : (
                                getStatusBadge(invoice.status)
                              )}
                            </TableCell>
                            <TableCell className="text-right text-red-600">{Number(invoice.discount) > 0 ? `-${Number(invoice.discount).toLocaleString()} DH` : '-'}</TableCell>
                            <TableCell className="text-right font-medium">{Number(invoice.total).toLocaleString()} DH</TableCell>
                            <TableCell className="text-right">
                              <div className="flex items-center justify-end gap-1">
                                <Button 
                                  variant="ghost" 
                                  size="icon" 
                                  onClick={(e) => { e.stopPropagation(); window.open(`/api/invoices/${invoice.id}/pdf`, '_blank') }}
                                >
                                  <Download className="h-4 w-4" />
                                </Button>
                                {invoice.status === 'PENDING' && (
                                  <Button 
                                    variant="ghost" 
                                    size="icon" 
                                    className="text-green-600 hover:text-green-700 hover:bg-green-50"
                                    onClick={(e) => { 
                                      e.stopPropagation(); 
                                      setEditInvoice(invoice)
                                      if (invoice.seller) {
                                        setSelectedSeller(invoice.seller.id)
                                      }
                                    }}
                                  >
                                    <Pencil className="h-4 w-4" />
                                  </Button>
                                )}
                              </div>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                )}
              </TabsContent>

              <TabsContent value="prescriptions" className="mt-0 space-y-4 focus-visible:outline-none focus-visible:ring-0">
                {client.prescriptions.length === 0 ? (
                  <div className="text-center py-12 bg-muted/20 rounded-lg border border-dashed">
                    <p className="text-muted-foreground">Aucune ordonnance enregistrée pour ce client.</p>
                  </div>
                ) : (
                  <div className="grid gap-6">
                    {client.prescriptions.map((px) => (
                      <Card key={px.id} className="overflow-hidden shadow-sm hover:shadow transition-shadow">
                        <div className="px-6 py-4 bg-muted/30 border-b flex justify-between items-center">
                          <div className="flex items-center gap-3">
                            <div className="p-2 bg-primary/10 rounded-full">
                              <Glasses className="h-5 w-5 text-primary" />
                            </div>
                            <div>
                              <h3 className="font-semibold text-slate-800">Ordonnance</h3>
                              <p className="text-xs text-muted-foreground">{formatDate(px.createdAt)}</p>
                            </div>
                          </div>
                          <Button variant="ghost" size="icon" onClick={() => setEditPrescription(px)}>
                            <Pencil className="h-4 w-4" />
                          </Button>
                        </div>
                        <CardContent className="p-0">
                          <div className="divide-y">
                            {px.visions.map((vision, vIdx) => (
                              <div key={vision.id || vIdx} className="p-6">
                                <div className="flex items-center gap-2 mb-4">
                                  <Badge variant="outline" className="bg-teal-50 text-teal-700 border-teal-200">
                                    {vision.type}
                                  </Badge>
                                </div>
                                <div className="grid md:grid-cols-2 gap-6 text-sm">
                                  <div className="space-y-3">
                                    <div className="font-semibold text-primary pb-2 border-b">Oeil Droit (OD)</div>
                                    <div className="grid grid-cols-5 gap-2 text-center">
                                      <div className="bg-muted/30 p-2 rounded"><span className="text-muted-foreground text-[10px] uppercase font-bold block mb-1">Sph</span><span className="font-medium text-slate-800">{vision.odSph || '-'}</span></div>
                                      <div className="bg-muted/30 p-2 rounded"><span className="text-muted-foreground text-[10px] uppercase font-bold block mb-1">Cyl</span><span className="font-medium text-slate-800">{vision.odCyl || '-'}</span></div>
                                      <div className="bg-muted/30 p-2 rounded"><span className="text-muted-foreground text-[10px] uppercase font-bold block mb-1">Axe</span><span className="font-medium text-slate-800">{vision.odAxis || '-'}</span></div>
                                      <div className="bg-muted/30 p-2 rounded"><span className="text-muted-foreground text-[10px] uppercase font-bold block mb-1">Add</span><span className="font-medium text-slate-800">{vision.odAdd || '-'}</span></div>
                                      <div className="bg-muted/30 p-2 rounded"><span className="text-muted-foreground text-[10px] uppercase font-bold block mb-1">Av</span><span className="font-medium text-slate-800">{vision.odVa || '-'}</span></div>
                                    </div>
                                  </div>
                                  <div className="space-y-3">
                                    <div className="font-semibold text-primary pb-2 border-b">Oeil Gauche (OG)</div>
                                    <div className="grid grid-cols-5 gap-2 text-center">
                                      <div className="bg-muted/30 p-2 rounded"><span className="text-muted-foreground text-[10px] uppercase font-bold block mb-1">Sph</span><span className="font-medium text-slate-800">{vision.ogSph || '-'}</span></div>
                                      <div className="bg-muted/30 p-2 rounded"><span className="text-muted-foreground text-[10px] uppercase font-bold block mb-1">Cyl</span><span className="font-medium text-slate-800">{vision.ogCyl || '-'}</span></div>
                                      <div className="bg-muted/30 p-2 rounded"><span className="text-muted-foreground text-[10px] uppercase font-bold block mb-1">Axe</span><span className="font-medium text-slate-800">{vision.ogAxis || '-'}</span></div>
                                      <div className="bg-muted/30 p-2 rounded"><span className="text-muted-foreground text-[10px] uppercase font-bold block mb-1">Add</span><span className="font-medium text-slate-800">{vision.ogAdd || '-'}</span></div>
                                      <div className="bg-muted/30 p-2 rounded"><span className="text-muted-foreground text-[10px] uppercase font-bold block mb-1">Av</span><span className="font-medium text-slate-800">{vision.ogVa || '-'}</span></div>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            ))}
                          </div>

                          {(px.pd || px.notes || px.products?.length > 0) && (
                            <div className="p-6 bg-slate-50 border-t space-y-4">
                              <div className="flex flex-wrap gap-x-8 gap-y-3 text-sm">
                                {px.pd && <div className="flex items-center gap-2"><span className="text-muted-foreground font-medium">Écart Pupillaire (EP):</span> <Badge variant="outline" className="bg-white">{px.pd}</Badge></div>}
                                {px.notes && <div className="flex-1 min-w-[200px]"><span className="text-muted-foreground font-medium block mb-1">Notes:</span> <p className="bg-white border p-2 rounded text-slate-700 shadow-sm">{px.notes}</p></div>}
                              </div>
                              
                              {px.products?.length > 0 && (
                                <div className="space-y-2">
                                  <span className="text-muted-foreground font-medium text-sm block">Produits associés:</span>
                                  <div className="flex flex-wrap gap-2">
                                    {px.products.map(product => (
                                      <Badge key={product.id} variant="secondary" className="px-3 py-1 bg-white border shadow-sm">
                                        {product.name} ({product.sku})
                                      </Badge>
                                    ))}
                                  </div>
                                </div>
                              )}
                            </div>
                          )}
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                )}
              </TabsContent>

              <TabsContent value="appointments" className="mt-0 focus-visible:outline-none focus-visible:ring-0">
                <div className="flex justify-end mb-4">
                  <Button onClick={() => setNewAppointment(true)} className="bg-teal-600 hover:bg-teal-700">
                    <Plus className="mr-2 h-4 w-4" />
                    Programmer un rendez-vous
                  </Button>
                </div>
                {client.appointments.length === 0 ? (
                  <div className="text-center py-12 bg-muted/20 rounded-lg border border-dashed">
                    <Calendar className="h-10 w-10 mx-auto mb-3 text-muted-foreground opacity-50" />
                    <p className="text-muted-foreground">Aucun rendez-vous enregistré pour ce client.</p>
                  </div>
                ) : (
                  <div className="rounded-md border">
                    <Table>
                      <TableHeader className="bg-muted/50">
                        <TableRow>
                          <TableHead>Date</TableHead>
                          <TableHead>Heure</TableHead>
                          <TableHead>Type</TableHead>
                          <TableHead>Statut</TableHead>
                          <TableHead>Notes</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {client.appointments.map((apt) => (
                          <TableRow key={apt.id}>
                            <TableCell>
                              {new Date(apt.date).toLocaleDateString('fr-MA', {
                                year: 'numeric',
                                month: 'long',
                                day: 'numeric'
                              })}
                            </TableCell>
                            <TableCell>
                              {new Date(apt.date).toLocaleTimeString('fr-MA', {
                                hour: '2-digit',
                                minute: '2-digit'
                              })}
                              <span className="text-muted-foreground ml-1">({apt.duration} min)</span>
                            </TableCell>
                            <TableCell>
                              <Badge variant="outline">
                                {apt.type === 'CONSULTATION' ? 'Consultation' :
                                 apt.type === 'CONTROL' ? 'Contrôle' :
                                 apt.type === 'DELIVERY' ? 'Livraison' :
                                 apt.type === 'REPAIR' ? 'Réparation' : 'Autre'}
                              </Badge>
                            </TableCell>
                            <TableCell>
                              <Badge className={
                                apt.status === 'SCHEDULED' ? 'bg-blue-100 text-blue-800' :
                                apt.status === 'CONFIRMED' ? 'bg-green-100 text-green-800' :
                                apt.status === 'COMPLETED' ? 'bg-gray-100 text-gray-800' :
                                apt.status === 'CANCELLED' ? 'bg-red-100 text-red-800' :
                                'bg-yellow-100 text-yellow-800'
                              }>
                                {apt.status === 'SCHEDULED' ? 'Programmé' :
                                 apt.status === 'CONFIRMED' ? 'Confirmé' :
                                 apt.status === 'COMPLETED' ? 'Terminé' :
                                 apt.status === 'CANCELLED' ? 'Annulé' : 'Absent'}
                              </Badge>
                            </TableCell>
                            <TableCell className="text-sm text-muted-foreground">{apt.notes || '-'}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                )}
              </TabsContent>
            </CardContent>
          </Tabs>
        </Card>
      </div>

      <Dialog open={!!editInvoice} onOpenChange={(open) => { if (!open) { setEditInvoice(null); setAdditionalPayment("") } }}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>Ajouter un paiement</DialogTitle>
            <DialogDescription>
              Facture {editInvoice?.invoiceNumber}
            </DialogDescription>
          </DialogHeader>
          {editInvoice && (() => {
            const remaining = Number(editInvoice.total) - Number(editInvoice.paidAmount)
            const parsed = parseFloat(additionalPayment) || 0
            const isOverMax = parsed > remaining
            return (
              <div className="space-y-4 py-4">
                {selectedSeller && (
                  <div className="bg-teal-50 border border-teal-200 rounded-md px-3 py-2 text-sm flex items-center gap-2">
                    <span className="text-teal-700 font-medium">Vendeur:</span>
                    <span className="text-teal-800 font-bold">{sellers.find(s => s.id === selectedSeller)?.name}</span>
                  </div>
                )}
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <Label className="text-muted-foreground">Total facture</Label>
                    <p className="font-medium">{formatCurrency(Number(editInvoice.total))}</p>
                  </div>
                  {Number(editInvoice.discount) > 0 && (
                    <div>
                      <Label className="text-muted-foreground">Remise</Label>
                      <p className="font-medium text-red-600">-{formatCurrency(Number(editInvoice.discount))}</p>
                    </div>
                  )}
                  <div>
                    <Label className="text-muted-foreground">Déjà payé</Label>
                    <p className="font-medium text-green-600">{formatCurrency(Number(editInvoice.paidAmount))}</p>
                  </div>
                </div>
                <div className="bg-amber-50 border border-amber-200 rounded-md px-3 py-2 text-amber-700 font-semibold text-sm">
                  Restant à payer : {formatCurrency(remaining)}
                </div>
                <div className="grid gap-2">
                  <Label>Montant à ajouter</Label>
                  <Input
                    type="number"
                    placeholder={`Max ${formatCurrency(remaining)}`}
                    value={additionalPayment}
                    min={0.01}
                    max={remaining}
                    onChange={(e) => {
                      const val = parseFloat(e.target.value)
                      if (!isNaN(val) && val > remaining) {
                        setAdditionalPayment(String(remaining))
                      } else {
                        setAdditionalPayment(e.target.value)
                      }
                    }}
                    className={isOverMax ? 'border-red-500' : ''}
                  />
                  {isOverMax && (
                    <p className="text-xs text-red-500">Le montant ne peut pas dépasser le restant ({formatCurrency(remaining)})</p>
                  )}
                </div>
              </div>
            )
          })()}
          <DialogFooter>
            <Button variant="outline" onClick={() => { setEditInvoice(null); setAdditionalPayment("") }}>Annuler</Button>
            <Button
              className="bg-teal-600 hover:bg-teal-700"
              onClick={handleUpdatePayment}
              disabled={updating || !additionalPayment || parseFloat(additionalPayment) <= 0 || parseFloat(additionalPayment) > (Number(editInvoice?.total) - Number(editInvoice?.paidAmount))}
            >
              {updating ? 'Mise à jour...' : 'Ajouter le paiement'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={showPinDialog} onOpenChange={(open) => { if (!open) { setShowPinDialog(false); setPin("") } }}>
        <DialogContent className="sm:max-w-[380px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ShieldCheck className="h-5 w-5 text-teal-600" />
              Validation Vendeur
            </DialogTitle>
            <DialogDescription>
              Saisissez votre code PIN pour valider ce paiement.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label>Vendeur</Label>
              <Select value={selectedSeller} onValueChange={setSelectedSeller}>
                <SelectTrigger>
                  <SelectValue placeholder="Choisir un vendeur" />
                </SelectTrigger>
                <SelectContent>
                  {sellers.map(s => (
                    <SelectItem key={s.id} value={s.id}>{s.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <Label>Code PIN</Label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  type="password"
                  placeholder="****"
                  className="pl-10 text-center text-2xl tracking-[1em]"
                  maxLength={6}
                  value={pin}
                  onChange={(e) => setPin(e.target.value)}
                  autoFocus
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => { setShowPinDialog(false); setPin("") }} disabled={verifyingPin}>
              Annuler
            </Button>
            <Button
              className="bg-teal-600 hover:bg-teal-700"
              onClick={validatePinAndUpdate}
              disabled={!selectedSeller || pin.length < 4 || verifyingPin}
            >
              {verifyingPin ? 'Validation...' : (
                <><Check className="mr-2 h-4 w-4" />Confirmer</>  
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={editClient} onOpenChange={(open) => !open && setEditClient(false)}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>Modifier les informations du client</DialogTitle>
            <DialogDescription>
              Mettez à jour les informations du client.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label>Nom Complet *</Label>
              <Input
                value={clientForm.name}
                onChange={(e) => setClientForm({ ...clientForm, name: e.target.value })}
                placeholder="Nom du client"
              />
            </div>
            <div className="grid gap-2">
              <Label>Téléphone *</Label>
              <Input
                value={clientForm.phone}
                onChange={(e) => setClientForm({ ...clientForm, phone: e.target.value })}
                placeholder="Téléphone"
              />
            </div>
            <div className="grid gap-2">
              <Label>Email</Label>
              <Input
                type="email"
                value={clientForm.email}
                onChange={(e) => setClientForm({ ...clientForm, email: e.target.value })}
                placeholder="Email"
              />
            </div>
            <div className="grid gap-2">
              <Label>CIN</Label>
              <Input
                value={clientForm.cin}
                onChange={(e) => setClientForm({ ...clientForm, cin: e.target.value })}
                placeholder="Numéro CIN"
              />
            </div>
            <div className="grid gap-2">
              <Label>Adresse</Label>
              <Input
                value={clientForm.address}
                onChange={(e) => setClientForm({ ...clientForm, address: e.target.value })}
                placeholder="Adresse"
              />
            </div>
            <div className="grid gap-2">
              <Label>Notes</Label>
              <textarea
                className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                value={clientForm.notes}
                onChange={(e) => setClientForm({ ...clientForm, notes: e.target.value })}
                placeholder="Notes..."
                rows={3}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditClient(false)} disabled={savingClient}>
              Annuler
            </Button>
            <Button
              className="bg-teal-600 hover:bg-teal-700"
              onClick={handleSaveClient}
              disabled={savingClient || !clientForm.name || !clientForm.phone}
            >
              {savingClient ? 'Enregistrement...' : 'Enregistrer'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <PrescriptionDialog 
        clients={[{ id: client.id, name: client.name }]} 
        prescription={editPrescription} 
        trigger={<span />} 
        open={!!editPrescription} 
        onOpenChange={(open) => !open && setEditPrescription(null)} 
      />

      <Dialog open={newAppointment} onOpenChange={(open) => !open && setNewAppointment(false)}>
        <DialogContent className="sm:max-w-[450px]">
          <DialogHeader>
            <DialogTitle>Nouveau rendez-vous</DialogTitle>
            <DialogDescription>
              Programmer un rendez-vous pour {client.name}
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label>Date *</Label>
                <Input
                  type="date"
                  value={appointmentForm.date}
                  onChange={(e) => setAppointmentForm({ ...appointmentForm, date: e.target.value })}
                />
              </div>
              <div className="grid gap-2">
                <Label>Heure *</Label>
                <Input
                  type="time"
                  value={appointmentForm.time}
                  onChange={(e) => setAppointmentForm({ ...appointmentForm, time: e.target.value })}
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label>Type</Label>
                <Select value={appointmentForm.type} onValueChange={(v) => setAppointmentForm({ ...appointmentForm, type: v })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="CONSULTATION">Consultation</SelectItem>
                    <SelectItem value="CONTROL">Contrôle</SelectItem>
                    <SelectItem value="DELIVERY">Livraison</SelectItem>
                    <SelectItem value="REPAIR">Réparation</SelectItem>
                    <SelectItem value="OTHER">Autre</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid gap-2">
                <Label>Durée</Label>
                <Select value={appointmentForm.duration} onValueChange={(v) => setAppointmentForm({ ...appointmentForm, duration: v })}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="15">15 min</SelectItem>
                    <SelectItem value="30">30 min</SelectItem>
                    <SelectItem value="45">45 min</SelectItem>
                    <SelectItem value="60">1 heure</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid gap-2">
              <Label>Notes</Label>
              <textarea
                className="flex min-h-[60px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                value={appointmentForm.notes}
                onChange={(e) => setAppointmentForm({ ...appointmentForm, notes: e.target.value })}
                placeholder="Notes optionnelles..."
                rows={2}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setNewAppointment(false)} disabled={savingAppointment}>
              Annuler
            </Button>
            <Button
              className="bg-teal-600 hover:bg-teal-700"
              onClick={handleSaveAppointment}
              disabled={savingAppointment || !appointmentForm.date || !appointmentForm.time}
            >
              {savingAppointment ? 'Création...' : 'Créer'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
