"use client"

import { useState, useEffect, useRef } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Search, ShoppingCart, Trash2, Printer, CreditCard, Banknote, CheckCircle, ShieldCheck, Lock, Check } from "lucide-react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import { formatCurrency } from "@/lib/utils"

type Client = {
  id: string
  name: string
  totalPurchases: number
  invoiceCount: number
}

type Product = {
  id: string
  sku: string
  name: string
  salePrice: number
  category: string
  quantity: number
  isFree: boolean
}

type Seller = {
  id: string
  name: string
}

type POSClientProps = {
  clients: Client[]
  products: Product[]
  tvaRate: number
}

const categories = ["Tous", "Montures", "Verres", "Solaires", "Accessoires", "Lentilles"]

interface CartItem {
  id: string
  sku: string
  name: string
  price: number
  quantity: number
  isFree?: boolean
}

export default function POSClient({ clients: initialClients, products, tvaRate }: POSClientProps) {
  const router = useRouter()
  const [cart, setCart] = useState<CartItem[]>([])
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedCategory, setSelectedCategory] = useState("Tous")
  const [selectedClient, setSelectedClient] = useState("")
  const [clientSearch, setClientSearch] = useState("")
  const [clients, setClients] = useState(initialClients)
  const [paymentMethod, setPaymentMethod] = useState("Espèces")
  const [payFull, setPayFull] = useState(false)
  const [amountPaid, setAmountPaid] = useState("")
  const [discount, setDiscount] = useState("")
  const [loading, setLoading] = useState(false)
  const [success, setSuccess] = useState(false)
  const [sellers, setSellers] = useState<Seller[]>([])
  const [selectedSeller, setSelectedSeller] = useState("")
  const [pin, setPin] = useState("")
  const [showPinDialog, setShowPinDialog] = useState(false)
  const [verifyingPin, setVerifyingPin] = useState(false)
  const [checkoutParams, setCheckoutParams] = useState<{ isPartial: boolean } | null>(null)
  const [showNewClientForm, setShowNewClientForm] = useState(false)
  const [newClient, setNewClient] = useState({ name: '', phone: '' })
  const [creatingClient, setCreatingClient] = useState(false)
  const [clientSelectOpen, setClientSelectOpen] = useState(false)
  const [error, setError] = useState<{ message: string; details?: Array<{ name: string; requested: number; available: number }> } | null>(null)
  const newClientNameRef = useRef<HTMLInputElement>(null)
  const clientSearchRef = useRef<HTMLInputElement>(null)
  const searchParams = useSearchParams()

  useEffect(() => {
    const fetchSellers = async () => {
      try {
        const response = await fetch('/api/sellers')
        if (response.ok) {
          const data = await response.json()
          setSellers(data)
        }
      } catch (error) {
        console.error("Error fetching sellers:", error)
      }
    }
    fetchSellers()
  }, [])
  useEffect(() => {
    // 1. Get free products from DB that are in stock
    const dbFreeItems: CartItem[] = products
      .filter(p => p.isFree && p.quantity > 0)
      .map(p => ({
        id: p.id,
        sku: p.sku,
        name: p.name,
        price: 0,
        quantity: 1,
        isFree: true
      }))

    // 2. Get products from URL
    const productIdsStr = searchParams.get('productIds')
    let urlItems: CartItem[] = []
    
    if (productIdsStr) {
      const ids = productIdsStr.split(',')
      const manualFreeIds = searchParams.get('freeProductIds')?.split(',') || []
      
      const counts: Record<string, { qty: number, free: boolean }> = {}
      ids.forEach(id => {
        if (!counts[id]) {
          counts[id] = { qty: 0, free: manualFreeIds.includes(id) }
        }
        counts[id].qty += 1
      })

      const uniqueIds = Object.keys(counts)
      const selectedProducts = products.filter(p => uniqueIds.includes(p.id))
      
      urlItems = selectedProducts.map(p => ({
        id: p.id,
        sku: p.sku,
        name: p.name,
        price: counts[p.id].free ? 0 : Number(p.salePrice),
        quantity: counts[p.id].qty,
        isFree: counts[p.id].free
      }))
    }

    // 3. Merge them
    const finalCartMap = new Map<string, CartItem>()
    
    // DB free items first
    dbFreeItems.forEach(item => finalCartMap.set(`${item.id}-true`, item))
    
    // URL items (can overwrite quantity or add new non-free items)
    urlItems.forEach(item => {
      const key = `${item.id}-${!!item.isFree}`
      finalCartMap.set(key, item)
    })

    if (finalCartMap.size > 0) {
      setCart(Array.from(finalCartMap.values()))
    }

    const clientId = searchParams.get('clientId')
    if (clientId) setSelectedClient(clientId)
  }, [searchParams, products])


  const dbProducts = products.map(p => ({
    ...p,
    price: Number(p.salePrice)
  }))

  const filteredClients = clients.filter(client => 
    client.name.toLowerCase().includes(clientSearch.toLowerCase())
  )

  const filteredProducts = dbProducts.filter((product) => {
    const matchesSearch = product.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      product.sku.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesCategory = selectedCategory === "Tous" || product.category === selectedCategory
    const inStock = product.quantity > 0
    return matchesSearch && matchesCategory && inStock
  })

  const addToCart = (product: Product) => {
    setCart((prev) => {
      // Check for same product with same "freeness"
      const existing = prev.find((item) => item.id === product.id && !!item.isFree === !!product.isFree)
      if (existing) {
        return prev.map((item) =>
          (item.id === product.id && !!item.isFree === !!product.isFree) ? { ...item, quantity: item.quantity + 1 } : item
        )
      }
      return [...prev, { 
        id: product.id, 
        sku: product.sku, 
        name: product.name, 
        price: product.isFree ? 0 : Number(product.salePrice), 
        quantity: 1, 
        isFree: !!product.isFree 
      }]
    })
  }

  const toggleGratuité = (id: string, currentIsFree: boolean) => {
    setCart((prev) => prev.map((item) => 
      item.id === id ? { ...item, isFree: !currentIsFree } : item
    ))
  }

  const removeFromCart = (id: string) => {
    setCart((prev) => prev.filter((item) => item.id !== id))
  }

  const updateQuantity = (id: string, isFree: boolean, quantity: number) => {
    if (quantity <= 0) {
      removeFromCart(id)
      return
    }
    setCart((prev) =>
      prev.map((item) => (item.id === id && item.isFree === isFree ? { ...item, quantity } : item))
    )
  }

  const subtotal = cart.reduce((sum, item) => sum + (item.isFree ? 0 : item.price) * item.quantity, 0)
  const tax = subtotal * (tvaRate / 100)
  const parsedDiscount = parseFloat(discount) || 0
  const total = Math.max(0, subtotal + tax - parsedDiscount)

  const handleCheckoutClick = (isPartial: boolean) => {
    if (cart.length === 0 || !selectedClient) return
    setCheckoutParams({ isPartial })
    setShowPinDialog(true)
  }

  const validatePinAndCheckout = async () => {
    if (!selectedSeller || !pin) return
    
    setVerifyingPin(true)
    try {
      const response = await fetch('/api/sellers/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sellerId: selectedSeller, pin }),
      })

      if (response.ok) {
        setShowPinDialog(false)
        await handleCheckout(checkoutParams?.isPartial || false)
        setPin("")
      } else {
        const error = await response.json()
        alert(error.error || "PIN invalide")
      }
    } catch (error) {
      console.error("Error verifying PIN:", error)
      alert("Erreur de vérification")
    } finally {
      setVerifyingPin(false)
    }
  }

  const handleCheckout = async (isPartial: boolean = false) => {
    if (cart.length === 0) return

    const parsedAmount = parseFloat(amountPaid)
    const paidAmount = isNaN(parsedAmount) || parsedAmount <= 0 ? total : Math.min(parsedAmount, total)

    setLoading(true)
    setError(null)
    try {
      const response = await fetch('/api/invoices', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          clientId: selectedClient || null,
          items: cart.map(item => ({
            ...item,
            price: item.isFree ? 0 : item.price
          })),
          paymentMethod,
          tvaRate,
          discount: parsedDiscount,
          paidAmount: paidAmount,
          isPartial: paidAmount < total,
          sellerId: selectedSeller,
        }),
      })

      if (response.ok) {
        setSuccess(true)
        router.refresh()
        setTimeout(() => {
          setSuccess(false)
          setCart([])
          setSelectedClient("")
          setAmountPaid("")
          setDiscount("")
          setPayFull(false)
        }, 2000)
      } else {
        const errorData = await response.json()
        setError({
          message: errorData.error || 'Failed to create invoice',
          details: errorData.details
        })
      }
    } catch (error) {
      console.error('Error creating invoice:', error)
      setError({
        message: 'Failed to create invoice. Please try again.'
      })
    } finally {
      setLoading(false)
    }
  }

  if (success) {
    return (
      <div className="flex items-center justify-center h-[calc(100vh-8rem)]">
        <div className="text-center">
          <CheckCircle className="h-16 w-16 text-green-500 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-green-600">Facture créée!</h2>
          <p className="text-muted-foreground mt-2">Total: {formatCurrency(total)}</p>
        </div>
      </div>
    )
  }

  return (
    <div className="flex h-[calc(100vh-8rem)] gap-6">
      <div className="flex-1 flex flex-col gap-4">
        <div className="flex items-center gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="Rechercher un produit..."
              className="pl-10"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>
          <Select value={selectedCategory} onValueChange={setSelectedCategory}>
            <SelectTrigger className="w-[180px]">
              <SelectValue placeholder="Catégorie" />
            </SelectTrigger>
            <SelectContent>
              {categories.map((cat) => (
                <SelectItem key={cat} value={cat}>{cat}</SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 overflow-y-auto content-start p-1" style={{ maxHeight: 'calc(100vh - 16rem)' }}>
          {filteredProducts.map((product) => (
            <div
              key={product.id}
              onClick={() => addToCart(product)}
              className="group relative cursor-pointer"
            >
              <div className="absolute -inset-0.5 bg-gradient-to-r from-teal-500 to-cyan-500 rounded-lg opacity-0 group-hover:opacity-100 transition duration-300 blur"></div>
              <div className="relative bg-white dark:bg-slate-950 rounded-lg p-4 overflow-hidden border border-gray-200 dark:border-slate-800 group-hover:border-teal-500/50 transition-all duration-300 h-full flex flex-col justify-between shadow-sm group-hover:shadow-lg">
                {/* Top Section - Stock Badge & Free Badge */}
                <div className="flex items-start justify-between gap-2 mb-2">
                  <div className="flex-1 min-w-0">
                    <h3 className="font-semibold text-sm text-gray-900 dark:text-white line-clamp-2 group-hover:text-teal-600 dark:group-hover:text-teal-400 transition-colors">
                      {product.name}
                    </h3>
                  </div>
                  {product.isFree && (
                    <Badge className="bg-gradient-to-r from-teal-500 to-cyan-500 text-white text-[10px] px-2 py-0.5 rounded-full whitespace-nowrap flex-shrink-0">
                      GRATUIT
                    </Badge>
                  )}
                </div>

                {/* SKU */}
                <p className="text-xs text-gray-500 dark:text-gray-400 mb-2">{product.sku}</p>

                {/* Price Section */}
                <div className="mb-3">
                  <span className="text-lg font-bold text-teal-600 dark:text-teal-400">
                    {formatCurrency(Number(product.salePrice))}
                  </span>
                </div>

                {/* Stock Indicator */}
                <div className="flex items-center gap-2 mt-auto">
                  <div className="flex-1">
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-xs text-gray-600 dark:text-gray-300 font-medium">Stock</span>
                      <span className="text-xs font-bold text-gray-900 dark:text-white">{product.quantity}</span>
                    </div>
                    <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2 overflow-hidden">
                      <div
                        className={`h-full rounded-full transition-all duration-300 ${
                          product.quantity > 10
                            ? 'bg-gradient-to-r from-green-400 to-green-500'
                            : product.quantity > 5
                            ? 'bg-gradient-to-r from-amber-400 to-amber-500'
                            : 'bg-gradient-to-r from-orange-400 to-red-500'
                        }`}
                        style={{ width: `${Math.min((product.quantity / 50) * 100, 100)}%` }}
                      ></div>
                    </div>
                  </div>
                  {product.quantity <= 5 && (
                    <span className="text-xs font-semibold text-orange-600 dark:text-orange-400">!</span>
                  )}
                </div>

                {/* Hover Effect - Add to Cart Indicator */}
                <div className="absolute inset-0 bg-gradient-to-t from-teal-600/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300 pointer-events-none rounded-lg"></div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <Card className="w-[400px] flex flex-col">
        <CardHeader className="border-b">
          <CardTitle className="flex items-center gap-2">
            <ShoppingCart className="h-5 w-5" />
            Panier
          </CardTitle>
          <div className="relative">
            <div 
              className="flex items-center h-10 px-3 py-2 border rounded-md bg-background text-sm cursor-pointer hover:bg-muted/50"
              onClick={() => {
                setClientSelectOpen(!clientSelectOpen)
                if (!clientSelectOpen) {
                  setTimeout(() => clientSearchRef.current?.focus(), 50)
                }
              }}
            >
              {selectedClient ? (
                <span>{clients.find(c => c.id === selectedClient)?.name || newClient.name || 'Client sélectionné'}</span>
              ) : (
                <span className="text-muted-foreground">Sélectionner un client</span>
              )}
            </div>
            
            {clientSelectOpen && (
              <div className="absolute z-50 top-full left-0 right-0 mt-1 bg-background border rounded-md shadow-lg">
                <div className="p-2">
                  <Input
                    ref={clientSearchRef}
                    placeholder="Rechercher un client..."
                    value={clientSearch}
                    onChange={(e) => setClientSearch(e.target.value)}
                    className="h-8"
                    autoFocus
                  />
                </div>
                <div className="max-h-[200px] overflow-y-auto">
                  {filteredClients.map((client) => (
                    <div
                      key={client.id}
                      className="px-3 py-2 cursor-pointer hover:bg-muted text-sm"
                      onClick={() => {
                        setSelectedClient(client.id)
                        setShowNewClientForm(false)
                        setNewClient({ name: '', phone: '' })
                        setClientSelectOpen(false)
                      }}
                    >
                      {client.name}
                    </div>
                  ))}
                </div>
                {filteredClients.length === 0 && (
                  <div className="p-3 text-center border-t">
                    <p className="text-sm text-muted-foreground mb-2">
                      {clientSearch ? 'Aucun client trouvé' : 'Tapez pour rechercher'}
                    </p>
                    {clientSearch && (
                      <Button 
                        variant="outline" 
                        size="sm" 
                        className="w-full"
                        onClick={() => {
                          setClientSelectOpen(false)
                          setShowNewClientForm(true)
                          setNewClient({ name: clientSearch, phone: '' })
                          setTimeout(() => newClientNameRef.current?.focus(), 100)
                        }}
                      >
                        + Client de passage
                      </Button>
                    )}
                  </div>
                )}
              </div>
            )}
            
            {clientSelectOpen && (
              <div 
                className="fixed inset-0 z-40" 
                onClick={() => setClientSelectOpen(false)}
              />
            )}
          </div>

          {showNewClientForm && (
            <div className="mt-3 p-3 bg-muted/50 rounded-lg border space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">Nouveau client</span>
                <Button 
                  variant="ghost" 
                  size="sm" 
                  className="h-6 text-xs"
                  onClick={() => {
                    setShowNewClientForm(false)
                    setNewClient({ name: '', phone: '' })
                  }}
                >
                  Annuler
                </Button>
              </div>
              <div className="grid grid-cols-2 gap-2">
                <Input
                  ref={newClientNameRef}
                  placeholder="Nom complet *"
                  value={newClient.name}
                  onChange={(e) => setNewClient({ ...newClient, name: e.target.value })}
                  className="h-8 text-sm"
                />
                <Input
                  placeholder="Téléphone *"
                  value={newClient.phone}
                  onChange={(e) => setNewClient({ ...newClient, phone: e.target.value })}
                  className="h-8 text-sm"
                />
              </div>
              <Button 
                size="sm" 
                className="w-full bg-teal-600 hover:bg-teal-700"
                disabled={!newClient.name || !newClient.phone || creatingClient}
                onClick={async () => {
                  setCreatingClient(true)
                  try {
                    const response = await fetch('/api/clients', {
                      method: 'POST',
                      headers: { 'Content-Type': 'application/json' },
                      body: JSON.stringify({
                        name: newClient.name,
                        phone: newClient.phone,
                      }),
                    })
                    const data = await response.json()
                    if (response.ok) {
                      const newClientData = { 
                        id: data.id, 
                        name: newClient.name, 
                        totalPurchases: 0, 
                        invoiceCount: 0 
                      }
                      setClients(prev => [...prev, newClientData])
                      setSelectedClient(data.id)
                      setShowNewClientForm(false)
                      setNewClient({ name: '', phone: '' })
                    } else {
                      alert(data.error || 'Erreur lors de la création du client')
                    }
                  } catch (error) {
                    console.error('Error creating client:', error)
                    alert('Erreur lors de la création du client')
                  } finally {
                    setCreatingClient(false)
                  }
                }}
              >
                {creatingClient ? 'Création...' : 'Créer et sélectionner'}
              </Button>
            </div>
          )}
        </CardHeader>
        
        <CardContent className="flex-1 overflow-y-auto p-4">
          {cart.length === 0 ? (
            <div className="text-center text-muted-foreground py-8">
              <ShoppingCart className="h-12 w-12 mx-auto mb-4 opacity-50" />
              <p>Le panier est vide</p>
              <p className="text-sm">Cliquez sur un produit pour l'ajouter</p>
            </div>
          ) : (
            <div className="space-y-4">
              {cart.map((item) => (
                <div key={`${item.id}-${item.isFree}`} className="space-y-2 border-b pb-3 last:border-0">
                  <div className="flex items-center justify-between gap-2">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <p className="font-medium text-sm truncate">{item.name}</p>
                        {item.isFree && (
                          <Badge variant="outline" className="text-[10px] h-4 bg-teal-50 text-teal-700 border-teal-200">Gratuit</Badge>
                        )}
                      </div>
                      <p className="text-sm text-muted-foreground">
                        {item.isFree ? <span className="line-through text-xs">{formatCurrency(item.price)}</span> : formatCurrency(item.price)}
                        {item.isFree && <span className="ml-1 text-teal-600 font-bold">0 DH</span>}
                      </p>
                    </div>
                    <div className="flex items-center gap-2">
                      <Button
                        variant="outline"
                        size="icon"
                        className="h-7 w-7"
                        onClick={() => updateQuantity(item.id, !!item.isFree, item.quantity - 1)}
                      >
                        -
                      </Button>
                      <span className="w-8 text-center text-sm">{item.quantity}</span>
                      <Button
                        variant="outline"
                        size="icon"
                        className="h-7 w-7"
                        onClick={() => updateQuantity(item.id, !!item.isFree, item.quantity + 1)}
                      >
                        +
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-7 w-7 text-red-500"
                        onClick={() => removeFromCart(item.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <label className="flex items-center gap-2 text-[10px] cursor-pointer text-muted-foreground hover:text-teal-600 transition-colors">
                      <input 
                        type="checkbox" 
                        checked={item.isFree} 
                        onChange={() => toggleGratuité(item.id, !!item.isFree)}
                        className="h-3 w-3 rounded border-gray-300 text-teal-600 focus:ring-teal-500"
                      />
                      Marquer comme gratuit
                    </label>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>

        <div className="border-t p-4 space-y-4">
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span>Sous-total</span>
              <span>{formatCurrency(subtotal)}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span>TVA ({tvaRate}%)</span>
              <span>{formatCurrency(tax)}</span>
            </div>
            <div className="flex justify-between items-center text-sm">
              <span>Remise (DH)</span>
              <Input
                type="number"
                placeholder="0.00"
                value={discount}
                onChange={(e) => {
                  const val = parseFloat(e.target.value) || 0
                  if (val <= subtotal + tax) {
                    setDiscount(e.target.value)
                  }
                }}
                className="h-8 w-24 text-right"
              />
            </div>
            <div className="flex justify-between text-lg font-bold border-t pt-2">
              <span>Total</span>
              <span className="text-teal-600">{formatCurrency(total)}</span>
            </div>
          </div>

          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <Label className="text-sm font-medium">Montant versé</Label>
              <label className="flex items-center gap-2 text-sm cursor-pointer">
                <input
                  type="checkbox"
                  checked={payFull}
                  onChange={(e) => {
                    setPayFull(e.target.checked)
                    if (e.target.checked) {
                      setAmountPaid(total.toString())
                    } else {
                      setAmountPaid("")
                    }
                  }}
                  className="w-4 h-4 rounded border-gray-300 text-teal-600 focus:ring-teal-500"
                />
                Totalité
              </label>
            </div>
            <Input
              type="number"
              inputMode="decimal"
              placeholder="0.00"
              value={amountPaid}
              onChange={(e) => {
                const val = parseFloat(e.target.value)
                if (isNaN(val) || val <= total) {
                  setAmountPaid(e.target.value)
                }
              }}
              onKeyDown={(e) => {
                const target = e.target as HTMLInputElement
                if (!/[0-9.]/.test(e.key) && !['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Tab'].includes(e.key)) {
                  e.preventDefault()
                }
                if (e.key === '.' && target.value.includes('.')) {
                  e.preventDefault()
                }
              }}
              className="text-lg"
              max={total}
            />
            {amountPaid && parseFloat(amountPaid) > 0 && (
              <div className="text-sm space-y-1">
                {parseFloat(amountPaid) >= total ? (
                  <div className="flex justify-between text-green-600">
                    <span>Montant suffisant</span>
                  </div>
                ) : (
                  <div className="flex justify-between text-amber-600">
                    <span>Reste à payer:</span>
                    <span className="font-medium">{formatCurrency(total - parseFloat(amountPaid))}</span>
                  </div>
                )}
              </div>
            )}
          </div>

          <div className="space-y-3">
            <p className="text-sm font-medium">Mode de paiement</p>
            <div className="flex gap-2">
              <Button
                variant={paymentMethod === "Espèces" ? "default" : "outline"}
                className="flex-1"
                onClick={() => setPaymentMethod("Espèces")}
              >
                <Banknote className="h-4 w-4 mr-2" />
                Espèces
              </Button>
              <Button
                variant={paymentMethod === "Carte" ? "default" : "outline"}
                className="flex-1"
                onClick={() => setPaymentMethod("Carte")}
              >
                <CreditCard className="h-4 w-4 mr-2" />
                Carte
              </Button>
            </div>
          </div>

          {error && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-3 space-y-2">
              <p className="text-sm font-medium text-red-800">{error.message}</p>
              {error.details && error.details.length > 0 && (
                <div className="text-xs text-red-700 space-y-1">
                  {error.details.map((item, idx) => (
                    <div key={idx} className="flex justify-between">
                      <span>{item.name}:</span>
                      <span>Demandé: {item.requested}, Disponible: {item.available}</span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          <div className="space-y-2">
            <Button
              className="w-full bg-teal-600 hover:bg-teal-700"
              size="lg"
              disabled={cart.length === 0 || loading || !selectedClient || (amountPaid !== "" && parseFloat(amountPaid) < total && parseFloat(amountPaid) > 0)}
              onClick={() => handleCheckoutClick(false)}
            >
              {loading ? 'Création...' : (
                <>
                  <Printer className="h-4 w-4 mr-2" />
                  Payer ({formatCurrency(total)})
                </>
              )}
            </Button>
            <Button
              variant="outline"
              className="w-full"
              size="lg"
              disabled={cart.length === 0 || loading || !selectedClient || !amountPaid || parseFloat(amountPaid) >= total || parseFloat(amountPaid) <= 0}
              onClick={() => handleCheckoutClick(true)}
            >
              {loading ? 'Création...' : 'Paiement partiel'}
            </Button>
            {!selectedClient && cart.length > 0 && (
              <p className="text-xs text-red-500 text-center">Veuillez sélectionner un client</p>
            )}
          </div>
        </div>
      </Card>

      <Dialog open={showPinDialog} onOpenChange={setShowPinDialog}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ShieldCheck className="h-5 w-5 text-teal-600" />
              Validation Vendeur
            </DialogTitle>
            <DialogDescription>
              Veuillez sélectionner votre nom et saisir votre code PIN pour valider cette vente.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="seller">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 htmlFor="pin">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
                  id="pin"
                  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={validatePinAndCheckout}
              disabled={!selectedSeller || pin.length < 4 || verifyingPin}
            >
              {verifyingPin ? 'Validation...' : (
                <>
                  <Check className="mr-2 h-4 w-4" />
                  Valider la vente
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}