'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Separator } from '@/components/ui/separator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Textarea } from '@/components/ui/textarea'
import { 
  ShoppingCart, 
  Search, 
  Plus, 
  Minus, 
  Trash2, 
  FileText,
  X,
  CheckCircle,
  AlertCircle,
  Upload,
  Calendar,
  Truck,
  Eye,
  Package,
  Download
} from 'lucide-react'
import { toast } from '@/hooks/use-toast'

// Types
interface Fournisseur {
  id: string
  nom: string
  email?: string
  telephone?: string
}

interface Produit {
  id: string
  reference: string
  designation: string
  categorie: string
  prixAchatHT: number
  tva: number
  marque?: string
}

interface Fichier {
  id: string
  nom: string
  type: string
  url: string
  taille: number
  mimeType: string
  createdAt: string
}

interface LigneFactureAchat {
  produitId: string
  produit?: Produit
  quantite: number
  prixUnitaireHT: number
  tauxTVA: number
  montantHT: number
  montantTVA: number
  montantTTC: number
}

interface FactureAchat {
  id: string
  numero: string
  date: string
  dateReception?: string
  statut: 'BROUILLON' | 'VALIDE'
  montantHT: number
  montantTVA: number
  montantTTC: number
  notes?: string
  fournisseur?: Fournisseur
  lignes?: LigneFactureAchat[]
  fichiers?: Fichier[]
}

// Helper functions
const calculateTTCFromHT = (ht: number, tvaRate: number) => {
  return ht * (1 + tvaRate / 100)
}

export default function PurchaseModule() {
  // State
  const [suppliers, setSuppliers] = useState<Fournisseur[]>([])
  const [products, setProducts] = useState<Produit[]>([])
  const [purchaseInvoices, setPurchaseInvoices] = useState<FactureAchat[]>([])
  const [selectedInvoice, setSelectedInvoice] = useState<FactureAchat | null>(null)
  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [showDetailDialog, setShowDetailDialog] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [statusFilter, setStatusFilter] = useState<'ALL' | 'BROUILLON' | 'VALIDE'>('ALL')
  const [activeTab, setActiveTab] = useState<'list' | 'create'>('list')
  
  // Form state
  const [formData, setFormData] = useState({
    fournisseurId: '',
    date: new Date().toISOString().split('T')[0],
    notes: ''
  })
  const [lines, setLines] = useState<LigneFactureAchat[]>([])
  const [selectedProduct, setSelectedProduct] = useState<string>('')
  const [newLine, setNewLine] = useState({
    quantite: 1,
    prixUnitaireHT: 0,
    tauxTVA: 20
  })
  const [uploadedFile, setUploadedFile] = useState<File | null>(null)

  // Calculate totals
  const totals = lines.reduce((acc, line) => ({
    ht: acc.ht + line.montantHT,
    tva: acc.tva + line.montantTVA,
    ttc: acc.ttc + line.montantTTC
  }), { ht: 0, tva: 0, ttc: 0 })

  // Load functions
  const loadSuppliers = async () => {
    try {
      const response = await fetch('/api/fournisseurs')
      if (response.ok) {
        const data = await response.json()
        setSuppliers(data.filter((s: Fournisseur) => s.nom))
      }
    } catch (error) {
      console.error('Error loading suppliers:', error)
    }
  }

  const loadProducts = async () => {
    try {
      const response = await fetch('/api/produits?actif=true')
      if (response.ok) {
        const data = await response.json()
        setProducts(data)
      }
    } catch (error) {
      console.error('Error loading products:', error)
    }
  }

  const loadInvoices = async () => {
    try {
      const response = await fetch('/api/achats/factures')
      if (response.ok) {
        const data = await response.json()
        setPurchaseInvoices(data)
      }
    } catch (error) {
      console.error('Error loading invoices:', error)
    }
  }

  // Initial load
  useEffect(() => {
    loadSuppliers()
    loadProducts()
    loadInvoices()
  }, [])

  // Search and filter invoices
  const filteredInvoices = purchaseInvoices.filter(invoice => {
    const matchesSearch = 
      invoice.numero.toLowerCase().includes(searchQuery.toLowerCase()) ||
      invoice.fournisseur?.nom.toLowerCase().includes(searchQuery.toLowerCase())
    
    const matchesStatus = statusFilter === 'ALL' || invoice.statut === statusFilter
    
    return matchesSearch && matchesStatus
  })

  // Add line to invoice
  const addLine = () => {
    if (!selectedProduct) {
      toast({
        title: 'Produit requis',
        description: 'Veuillez sélectionner un produit',
        variant: 'destructive'
      })
      return
    }

    if (newLine.quantite <= 0 || newLine.prixUnitaireHT <= 0) {
      toast({
        title: 'Valeurs invalides',
        description: 'Veuillez entrer des quantités et prix valides',
        variant: 'destructive'
      })
      return
    }

    const product = products.find(p => p.id === selectedProduct)
    if (!product) return

    const montantHT = newLine.quantite * newLine.prixUnitaireHT
    const montantTVA = montantHT * (newLine.tauxTVA / 100)
    const montantTTC = montantHT + montantTVA

    const line: LigneFactureAchat = {
      produitId: selectedProduct,
      produit: product,
      quantite: newLine.quantite,
      prixUnitaireHT: newLine.prixUnitaireHT,
      tauxTVA: newLine.tauxTVA,
      montantHT,
      montantTVA,
      montantTTC
    }

    setLines([...lines, line])
    setSelectedProduct('')
    setNewLine({ quantite: 1, prixUnitaireHT: 0, tauxTVA: 20 })
  }

  // Remove line
  const removeLine = (index: number) => {
    setLines(lines.filter((_, i) => i !== index))
  }

  // Update line quantity
  const updateLineQuantity = (index: number, newQuantity: number) => {
    if (newQuantity < 1) return

    setLines(lines.map((line, i) => {
      if (i === index) {
        const montantHT = newQuantity * line.prixUnitaireHT
        const montantTVA = montantHT * (line.tauxTVA / 100)
        return {
          ...line,
          quantite: newQuantity,
          montantHT,
          montantTVA,
          montantTTC: montantHT + montantTVA
        }
      }
      return line
    }))
  }

  // Reset form
  const resetForm = () => {
    setFormData({ fournisseurId: '', date: new Date().toISOString().split('T')[0], notes: '' })
    setLines([])
    setSelectedProduct('')
    setNewLine({ quantite: 1, prixUnitaireHT: 0, tauxTVA: 20 })
    setUploadedFile(null)
  }

  // Create purchase invoice
  const createInvoice = async () => {
    if (!formData.fournisseurId) {
      toast({
        title: 'Fournisseur requis',
        description: 'Veuillez sélectionner un fournisseur',
        variant: 'destructive'
      })
      return
    }

    if (lines.length === 0) {
      toast({
        title: 'Lignes requises',
        description: 'Veuillez ajouter au moins une ligne à la facture',
        variant: 'destructive'
      })
      return
    }

    try {
      const response = await fetch('/api/achats/factures', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          fournisseurId: formData.fournisseurId,
          date: formData.date,
          lignes: lines.map(l => ({
            produitId: l.produitId,
            quantite: l.quantite,
            prixUnitaireHT: l.prixUnitaireHT,
            tauxTVA: l.tauxTVA,
            montantHT: l.montantHT,
            montantTVA: l.montantTVA,
            montantTTC: l.montantTTC
          })),
          montantHT: totals.ht,
          montantTVA: totals.tva,
          montantTTC: totals.ttc,
          notes: formData.notes
        })
      })

      if (response.ok) {
        const invoice = await response.json()

        // Upload file if selected
        if (uploadedFile) {
          await uploadFile(invoice.id)
        }

        toast({
          title: 'Facture créée',
          description: `Facture ${invoice.numero} créée avec succès`
        })
        resetForm()
        setShowCreateDialog(false)
        loadInvoices()
        setActiveTab('list')
      }
    } catch (error) {
      console.error('Error creating invoice:', error)
      toast({
        title: 'Erreur',
        description: 'Impossible de créer la facture',
        variant: 'destructive'
      })
    }
  }

  // Upload file
  const uploadFile = async (invoiceId: string) => {
    if (!uploadedFile) return

    const formData = new FormData()
    formData.append('file', uploadedFile)
    formData.append('factureAchatId', invoiceId)
    formData.append('type', 'FACTURE_ACHAT')
    formData.append('nom', uploadedFile.name)

    try {
      const response = await fetch('/api/achats/upload-facture', {
        method: 'POST',
        body: formData
      })

      if (!response.ok) {
        console.error('Error uploading file')
      }
    } catch (error) {
      console.error('Error uploading file:', error)
    }
  }

  // Validate invoice (receive stock)
  const validateInvoice = async (invoiceId: string) => {
    try {
      const response = await fetch(`/api/achats/factures/${invoiceId}/valider`, {
        method: 'POST'
      })

      if (response.ok) {
        toast({
          title: 'Facture validée',
          description: 'Le stock a été mis à jour'
        })
        loadInvoices()
      }
    } catch (error) {
      console.error('Error validating invoice:', error)
      toast({
        title: 'Erreur',
        description: 'Impossible de valider la facture',
        variant: 'destructive'
      })
    }
  }

  // Delete invoice (only if BROUILLON)
  const deleteInvoice = async (invoiceId: string) => {
    try {
      const response = await fetch(`/api/achats/factures/${invoiceId}`, {
        method: 'DELETE'
      })

      if (response.ok) {
        toast({
          title: 'Facture supprimée',
          description: 'La facture a été supprimée'
        })
        loadInvoices()
      }
    } catch (error) {
      console.error('Error deleting invoice:', error)
      toast({
        title: 'Erreur',
        description: 'Impossible de supprimer la facture',
        variant: 'destructive'
      })
    }
  }

  // View invoice detail
  const viewInvoiceDetail = async (invoiceId: string) => {
    try {
      const response = await fetch(`/api/achats/factures/${invoiceId}`)
      if (response.ok) {
        const invoice = await response.json()
        setSelectedInvoice(invoice)
        setShowDetailDialog(true)
      }
    } catch (error) {
      console.error('Error loading invoice detail:', error)
    }
  }

  // Get status badge
  const getStatusBadge = (statut: string) => {
    const variants: Record<string, { color: string; label: string }> = {
      'BROUILLON': { color: 'bg-yellow-500', label: 'Brouillon' },
      'VALIDE': { color: 'bg-green-500', label: 'Validé' }
    }
    const status = variants[statut] || variants['BROUILLON']
    return <Badge className={status.color}>{status.label}</Badge>
  }

  // Generate invoice number
  const generateInvoiceNumber = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const count = purchaseInvoices.filter(i => {
      const d = new Date(i.date)
      return d.getFullYear() === year && d.getMonth() + 1 === now.getMonth() + 1
    }).length + 1
    return `A${year}${month}${String(count).padStart(4, '0')}`
  }

  return (
    <div className="space-y-6">
      <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as 'list' | 'create')}>
        <div className="flex items-center justify-between">
          <TabsList className="grid w-full max-w-md grid-cols-2">
            <TabsTrigger value="list">Factures d'achat</TabsTrigger>
            <TabsTrigger value="create">Nouvelle facture</TabsTrigger>
          </TabsList>
        </div>

        {/* Invoices List Tab */}
        <TabsContent value="list" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <FileText className="h-5 w-5" />
                Factures d'achat
              </CardTitle>
              <CardDescription>
                Gestion des factures fournisseurs et réception de stock
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Filters */}
              <div className="flex gap-4 items-center">
                <div className="flex-1">
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                    <Input
                      placeholder="Rechercher par n° facture ou fournisseur..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      className="pl-10"
                    />
                  </div>
                </div>
                <Select value={statusFilter} onValueChange={(v: any) => setStatusFilter(v)}>
                  <SelectTrigger className="w-48">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ALL">Tous les statuts</SelectItem>
                    <SelectItem value="BROUILLON">Brouillon</SelectItem>
                    <SelectItem value="VALIDE">Validé</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* Invoices Table */}
              <div className="border rounded-lg">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>N° Facture</TableHead>
                      <TableHead>Date</TableHead>
                      <TableHead>Fournisseur</TableHead>
                      <TableHead>Statut</TableHead>
                      <TableHead>Date réception</TableHead>
                      <TableHead className="text-right">Montant TTC</TableHead>
                      <TableHead className="text-center">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredInvoices.map((invoice) => (
                      <TableRow key={invoice.id}>
                        <TableCell className="font-medium">
                          <div className="flex items-center gap-2">
                            {invoice.numero}
                            {invoice.fichiers && invoice.fichiers.length > 0 && (
                              <Badge variant="secondary" className="text-xs">
                                <FileText className="h-3 w-3 mr-1" />
                                {invoice.fichiers.length}
                              </Badge>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          {new Date(invoice.date).toLocaleDateString('fr-FR')}
                        </TableCell>
                        <TableCell>{invoice.fournisseur?.nom || '-'}</TableCell>
                        <TableCell>{getStatusBadge(invoice.statut)}</TableCell>
                        <TableCell>
                          {invoice.dateReception 
                            ? new Date(invoice.dateReception).toLocaleDateString('fr-FR')
                            : '-'
                          }
                        </TableCell>
                        <TableCell className="text-right font-bold">
                          {invoice.montantTTC.toFixed(2)} €
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center justify-center gap-1">
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => viewInvoiceDetail(invoice.id)}
                            >
                              <Eye className="h-4 w-4" />
                            </Button>
                            {invoice.statut === 'BROUILLON' && (
                              <>
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  onClick={() => validateInvoice(invoice.id)}
                                  className="text-green-600 hover:text-green-700"
                                >
                                  <CheckCircle className="h-4 w-4" />
                                </Button>
                                <Button
                                  variant="ghost"
                                  size="icon"
                                  onClick={() => deleteInvoice(invoice.id)}
                                  className="text-red-600 hover:text-red-700"
                                >
                                  <Trash2 className="h-4 w-4" />
                                </Button>
                              </>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                    {filteredInvoices.length === 0 && (
                      <TableRow>
                        <TableCell colSpan={7} className="text-center py-8 text-gray-500">
                          {searchQuery || statusFilter !== 'ALL' 
                            ? 'Aucune facture trouvée' 
                            : 'Aucune facture d\'achat enregistrée'}
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Create Invoice Tab */}
        <TabsContent value="create" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Left: Invoice Form */}
            <div className="space-y-4">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <FileText className="h-5 w-5" />
                    Informations de la facture
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="space-y-2">
                    <Label>Fournisseur *</Label>
                    <Select
                      value={formData.fournisseurId}
                      onValueChange={(value) => setFormData({ ...formData, fournisseurId: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Sélectionner un fournisseur" />
                      </SelectTrigger>
                      <SelectContent>
                        {suppliers.map((supplier) => (
                          <SelectItem key={supplier.id} value={supplier.id}>
                            {supplier.nom}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label>Date de la facture *</Label>
                    <Input
                      type="date"
                      value={formData.date}
                      onChange={(e) => setFormData({ ...formData, date: e.target.value })}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label>Notes</Label>
                    <Textarea
                      placeholder="Notes ou commentaires..."
                      value={formData.notes}
                      onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
                      rows={3}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label>Facture fournisseur (PDF)</Label>
                    <div className="flex gap-2">
                      <Input
                        type="file"
                        accept=".pdf"
                        onChange={(e) => setUploadedFile(e.target.files?.[0] || null)}
                        className="flex-1"
                      />
                      {uploadedFile && (
                        <Badge variant="secondary">
                          <FileText className="h-3 w-3 mr-1" />
                          {uploadedFile.name}
                        </Badge>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>

              {/* Add Products */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Package className="h-5 w-5" />
                    Ajouter des produits
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="space-y-2">
                    <Label>Produit *</Label>
                    <Select value={selectedProduct} onValueChange={setSelectedProduct}>
                      <SelectTrigger>
                        <SelectValue placeholder="Sélectionner un produit" />
                      </SelectTrigger>
                      <SelectContent>
                        {products.map((product) => (
                          <SelectItem key={product.id} value={product.id}>
                            {product.reference} - {product.designation}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label>Quantité *</Label>
                      <Input
                        type="number"
                        min="1"
                        value={newLine.quantite}
                        onChange={(e) => setNewLine({ ...newLine, quantite: Number(e.target.value) })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label>Prix unitaire HT (€) *</Label>
                      <Input
                        type="number"
                        min="0"
                        step="0.01"
                        value={newLine.prixUnitaireHT || ''}
                        onChange={(e) => {
                          const product = products.find(p => p.id === selectedProduct)
                          setNewLine({ 
                            ...newLine, 
                            prixUnitaireHT: Number(e.target.value),
                            tauxTVA: product?.tva || 20
                          })
                        }}
                        placeholder={products.find(p => p.id === selectedProduct)?.prixAchatHT.toString() || '0.00'}
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label>Taux TVA (%)</Label>
                    <Select
                      value={newLine.tauxTVA.toString()}
                      onValueChange={(v) => setNewLine({ ...newLine, tauxTVA: Number(v) })}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="20">20%</SelectItem>
                        <SelectItem value="10">10%</SelectItem>
                        <SelectItem value="5.5">5.5%</SelectItem>
                        <SelectItem value="0">0%</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <Button onClick={addLine} className="w-full">
                    <Plus className="h-4 w-4 mr-2" />
                    Ajouter à la facture
                  </Button>
                </CardContent>
              </Card>
            </div>

            {/* Right: Lines and Totals */}
            <div className="space-y-4">
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <ShoppingCart className="h-5 w-5" />
                      Lignes de facture ({lines.length})
                    </div>
                    {lines.length > 0 && (
                      <Button variant="ghost" size="sm" onClick={resetForm}>
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    )}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  {lines.length === 0 ? (
                    <div className="text-center py-8 text-gray-500">
                      Aucune ligne ajoutée
                    </div>
                  ) : (
                    <>
                      <div className="max-h-[400px] overflow-y-auto">
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>Produit</TableHead>
                              <TableHead className="text-center">Qté</TableHead>
                              <TableHead className="text-right">Prix HT</TableHead>
                              <TableHead className="text-right">Total TTC</TableHead>
                              <TableHead></TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {lines.map((line, index) => (
                              <TableRow key={index}>
                                <TableCell>
                                  <div>
                                    <p className="font-medium text-sm">{line.produit?.designation}</p>
                                    <p className="text-xs text-gray-500">{line.produit?.reference}</p>
                                  </div>
                                </TableCell>
                                <TableCell>
                                  <div className="flex items-center justify-center gap-1">
                                    <Button
                                      variant="outline"
                                      size="icon"
                                      className="h-6 w-6"
                                      onClick={() => updateLineQuantity(index, line.quantite - 1)}
                                    >
                                      <Minus className="h-3 w-3" />
                                    </Button>
                                    <span className="w-8 text-center text-sm">{line.quantite}</span>
                                    <Button
                                      variant="outline"
                                      size="icon"
                                      className="h-6 w-6"
                                      onClick={() => updateLineQuantity(index, line.quantite + 1)}
                                    >
                                      <Plus className="h-3 w-3" />
                                    </Button>
                                  </div>
                                </TableCell>
                                <TableCell className="text-right text-sm">
                                  {line.prixUnitaireHT.toFixed(2)} €
                                </TableCell>
                                <TableCell className="text-right font-medium">
                                  {line.montantTTC.toFixed(2)} €
                                </TableCell>
                                <TableCell>
                                  <Button
                                    variant="ghost"
                                    size="icon"
                                    onClick={() => removeLine(index)}
                                  >
                                    <Trash2 className="h-4 w-4 text-red-500" />
                                  </Button>
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>

                      <Separator className="my-4" />

                      {/* Totals */}
                      <div className="space-y-2">
                        <div className="flex justify-between text-sm">
                          <span>Total HT:</span>
                          <span>{totals.ht.toFixed(2)} €</span>
                        </div>
                        <div className="flex justify-between text-sm">
                          <span>TVA:</span>
                          <span>{totals.tva.toFixed(2)} €</span>
                        </div>
                        <Separator />
                        <div className="flex justify-between text-lg font-bold">
                          <span>Total TTC:</span>
                          <span className="text-primary">{totals.ttc.toFixed(2)} €</span>
                        </div>
                      </div>
                    </>
                  )}
                </CardContent>
              </Card>

              {/* Actions */}
              {lines.length > 0 && (
                <Card>
                  <CardContent className="pt-6">
                    <div className="space-y-3">
                      <div className="flex items-center gap-2 text-sm text-gray-600">
                        <AlertCircle className="h-4 w-4" />
                        <span>N° de facture prévu: {generateInvoiceNumber()}</span>
                      </div>
                      <Button
                        onClick={createInvoice}
                        className="w-full"
                        size="lg"
                      >
                        <CheckCircle className="h-5 w-5 mr-2" />
                        Créer la facture (Brouillon)
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>
          </div>
        </TabsContent>
      </Tabs>

      {/* Invoice Detail Dialog */}
      <Dialog open={showDetailDialog} onOpenChange={setShowDetailDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <FileText className="h-5 w-5" />
              Facture d'achat {selectedInvoice?.numero}
            </DialogTitle>
            <DialogDescription>
              Détails de la facture fournisseur
            </DialogDescription>
          </DialogHeader>
          
          {selectedInvoice && (
            <div className="space-y-6">
              {/* Header */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-gray-500">Fournisseur</p>
                  <p className="font-semibold">{selectedInvoice.fournisseur?.nom || '-'}</p>
                  {selectedInvoice.fournisseur?.telephone && (
                    <p className="text-sm text-gray-600">{selectedInvoice.fournisseur.telephone}</p>
                  )}
                </div>
                <div className="text-right">
                  <p className="text-sm text-gray-500">Statut</p>
                  <div className="flex justify-end mt-1">{getStatusBadge(selectedInvoice.statut)}</div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-gray-500">Date de la facture</p>
                  <p className="font-medium">{new Date(selectedInvoice.date).toLocaleDateString('fr-FR')}</p>
                </div>
                <div className="text-right">
                  <p className="text-sm text-gray-500">Date de réception</p>
                  <p className="font-medium">
                    {selectedInvoice.dateReception 
                      ? new Date(selectedInvoice.dateReception).toLocaleDateString('fr-FR')
                      : 'Non reçu'
                    }
                  </p>
                </div>
              </div>

              {selectedInvoice.notes && (
                <div className="bg-gray-50 p-4 rounded">
                  <p className="text-sm text-gray-500 mb-1">Notes</p>
                  <p className="text-sm">{selectedInvoice.notes}</p>
                </div>
              )}

              {/* Attached Files */}
              {selectedInvoice.fichiers && selectedInvoice.fichiers.length > 0 && (
                <div className="bg-blue-50 p-4 rounded">
                  <p className="text-sm text-gray-700 font-medium mb-2 flex items-center gap-2">
                    <FileText className="h-4 w-4" />
                    Documents joints ({selectedInvoice.fichiers.length})
                  </p>
                  <div className="space-y-2">
                    {selectedInvoice.fichiers.map((fichier) => (
                      <div
                        key={fichier.id}
                        className="flex items-center justify-between bg-white p-3 rounded border hover:border-blue-300 transition-colors"
                      >
                        <div className="flex items-center gap-3">
                          <FileText className="h-5 w-5 text-blue-600" />
                          <div>
                            <p className="font-medium text-sm">{fichier.nom}</p>
                            <p className="text-xs text-gray-500">
                              {(fichier.taille / 1024).toFixed(2)} KB • {new Date(fichier.createdAt).toLocaleDateString('fr-FR')}
                            </p>
                          </div>
                        </div>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => window.open(fichier.url, '_blank')}
                          className="flex items-center gap-2"
                        >
                          <Download className="h-4 w-4" />
                          Télécharger
                        </Button>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              <Separator />

              {/* Lines */}
              <div>
                <h3 className="font-semibold mb-3">Lignes de facture</h3>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Produit</TableHead>
                      <TableHead className="text-center">Qté</TableHead>
                      <TableHead className="text-right">Prix HT</TableHead>
                      <TableHead className="text-right">TVA</TableHead>
                      <TableHead className="text-right">Total TTC</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {selectedInvoice.lignes?.map((line, index) => (
                      <TableRow key={index}>
                        <TableCell>
                          <div>
                            <p className="font-medium text-sm">{line.produit?.designation}</p>
                            <p className="text-xs text-gray-500">{line.produit?.reference}</p>
                          </div>
                        </TableCell>
                        <TableCell className="text-center">{line.quantite}</TableCell>
                        <TableCell className="text-right">{line.prixUnitaireHT.toFixed(2)} €</TableCell>
                        <TableCell className="text-right">{line.tauxTVA}%</TableCell>
                        <TableCell className="text-right font-medium">{line.montantTTC.toFixed(2)} €</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              <Separator />

              {/* Totals */}
              <div className="space-y-2">
                <div className="flex justify-between">
                  <span>Total HT:</span>
                  <span>{selectedInvoice.montantHT.toFixed(2)} €</span>
                </div>
                <div className="flex justify-between">
                  <span>TVA:</span>
                  <span>{selectedInvoice.montantTVA.toFixed(2)} €</span>
                </div>
                <Separator />
                <div className="flex justify-between text-lg font-bold">
                  <span>Total TTC:</span>
                  <span className="text-primary">{selectedInvoice.montantTTC.toFixed(2)} €</span>
                </div>
              </div>

              {/* Actions */}
              {selectedInvoice.statut === 'BROUILLON' && (
                <div className="flex gap-2">
                  <Button
                    onClick={() => {
                      validateInvoice(selectedInvoice.id)
                      setShowDetailDialog(false)
                    }}
                    className="flex-1"
                  >
                    <CheckCircle className="h-4 w-4 mr-2" />
                    Valider et recevoir le stock
                  </Button>
                  <Button
                    variant="destructive"
                    onClick={() => {
                      deleteInvoice(selectedInvoice.id)
                      setShowDetailDialog(false)
                    }}
                  >
                    <Trash2 className="h-4 w-4 mr-2" />
                    Supprimer
                  </Button>
                </div>
              )}

              <Button onClick={() => setShowDetailDialog(false)} variant="outline" className="w-full">
                Fermer
              </Button>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
