'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  Phone,
  Mail,
  MapPin,
  Building2,
  Calendar,
  FileText,
  Package,
  Edit,
  Power,
  PowerOff,
} from 'lucide-react'

interface Supplier {
  id: string
  nom: string
  contact: string | null
  email: string | null
  telephone: string | null
  adresse: string | null
  ville: string | null
  codePostal: string | null
  notes: string | null
  actif: boolean
  createdAt: string
  updatedAt: string
}

interface Product {
  id: string
  reference: string
  designation: string
  categorie: string
  stock: number
  prixVenteTTC: number
}

interface Invoice {
  id: string
  numero: string
  date: string
  montantHT: number
  montantTVA: number
  montantTTC: number
  statut: string
}

interface SupplierDetailProps {
  supplier: Supplier
  onClose: () => void
  onUpdate: () => void
  onEdit: () => void
}

export function SupplierDetail({ supplier, onClose, onUpdate, onEdit }: SupplierDetailProps) {
  const [products, setProducts] = useState<Product[]>([])
  const [invoices, setInvoices] = useState<Invoice[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetchSupplierData()
  }, [supplier.id])

  const fetchSupplierData = async () => {
    setLoading(true)
    try {
      // Fetch products from this supplier
      const productsResponse = await fetch(`/api/produits?fournisseurId=${supplier.id}`)
      if (productsResponse.ok) {
        const productsData = await productsResponse.json()
        setProducts(Array.isArray(productsData) ? productsData : [])
      }

      // Fetch invoices from this supplier
      const invoicesResponse = await fetch(`/api/fournisseurs/${supplier.id}/factures`)
      if (invoicesResponse.ok) {
        const invoicesData = await invoicesResponse.json()
        setInvoices(Array.isArray(invoicesData) ? invoicesData : [])
      }
    } catch (error) {
      console.error('Error fetching supplier data:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleToggleStatus = async () => {
    try {
      const response = await fetch(`/api/fournisseurs/${supplier.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...supplier,
          actif: !supplier.actif,
        }),
      })

      if (response.ok) {
        onUpdate()
      }
    } catch (error) {
      console.error('Error toggling supplier status:', error)
    }
  }

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

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('fr-FR', {
      style: 'currency',
      currency: 'EUR',
    }).format(amount)
  }

  const totalPurchaseAmount = invoices.reduce((sum, inv) => sum + inv.montantTTC, 0)

  return (
    <div className="space-y-6">
      {/* Actions */}
      <div className="flex gap-2">
        <Button onClick={onEdit} variant="outline" className="gap-2">
          <Edit className="h-4 w-4" />
          Modifier
        </Button>
        <Button
          onClick={handleToggleStatus}
          variant={supplier.actif ? "destructive" : "default"}
          className="gap-2"
        >
          {supplier.actif ? (
            <>
              <PowerOff className="h-4 w-4" />
              Désactiver
            </>
          ) : (
            <>
              <Power className="h-4 w-4" />
              Activer
            </>
          )}
        </Button>
      </div>

      {/* Supplier Information */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Building2 className="h-5 w-5" />
            Informations du fournisseur
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-xl font-bold">{supplier.nom}</h3>
              {supplier.contact && (
                <p className="text-sm text-gray-500">Contact: {supplier.contact}</p>
              )}
            </div>
            <Badge
              variant={supplier.actif ? 'default' : 'secondary'}
              className={
                supplier.actif
                  ? 'bg-green-100 text-green-800 hover:bg-green-200'
                  : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
              }
            >
              {supplier.actif ? 'Actif' : 'Inactif'}
            </Badge>
          </div>

          <Separator />

          <div className="space-y-3">
            {supplier.telephone && (
              <div className="flex items-center gap-3">
                <Phone className="h-4 w-4 text-gray-500" />
                <span>{supplier.telephone}</span>
              </div>
            )}
            {supplier.email && (
              <div className="flex items-center gap-3">
                <Mail className="h-4 w-4 text-gray-500" />
                <span>{supplier.email}</span>
              </div>
            )}
            {(supplier.adresse || supplier.ville || supplier.codePostal) && (
              <div className="flex items-start gap-3">
                <MapPin className="h-4 w-4 text-gray-500 mt-0.5" />
                <div className="space-y-1">
                  {supplier.adresse && <div>{supplier.adresse}</div>}
                  <div>
                    {supplier.codePostal && `${supplier.codePostal} `}
                    {supplier.ville}
                  </div>
                </div>
              </div>
            )}
            <div className="flex items-center gap-3">
              <Calendar className="h-4 w-4 text-gray-500" />
              <span className="text-sm text-gray-500">
                Créé le {formatDate(supplier.createdAt)}
              </span>
            </div>
          </div>

          {supplier.notes && (
            <>
              <Separator />
              <div>
                <h4 className="font-medium mb-2">Notes</h4>
                <p className="text-sm text-gray-600 whitespace-pre-wrap">{supplier.notes}</p>
              </div>
            </>
          )}
        </CardContent>
      </Card>

      {/* Statistics */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Produits</p>
                <p className="text-2xl font-bold">{products.length}</p>
              </div>
              <Package className="h-8 w-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Factures</p>
                <p className="text-2xl font-bold">{invoices.length}</p>
              </div>
              <FileText className="h-8 w-8 text-orange-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">Total Achats</p>
                <p className="text-2xl font-bold text-green-600">{formatCurrency(totalPurchaseAmount)}</p>
              </div>
              <Building2 className="h-8 w-8 text-green-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Products List */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Package className="h-5 w-5" />
            Produits fournis ({products.length})
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 text-center text-gray-500">Chargement...</div>
          ) : products.length === 0 ? (
            <div className="p-8 text-center text-gray-500">
              Aucun produit associé à ce fournisseur
            </div>
          ) : (
            <ScrollArea className="h-[300px]">
              <div className="divide-y">
                {products.map((product) => (
                  <div key={product.id} className="p-4 hover:bg-gray-50 flex items-center justify-between">
                    <div>
                      <div className="font-medium">{product.designation}</div>
                      <div className="text-sm text-gray-500">
                        {product.reference} • {product.categorie}
                      </div>
                    </div>
                    <div className="text-right">
                      <div className="font-medium">{formatCurrency(product.prixVenteTTC)}</div>
                      <div className="text-sm text-gray-500">Stock: {product.stock}</div>
                    </div>
                  </div>
                ))}
              </div>
            </ScrollArea>
          )}
        </CardContent>
      </Card>

      {/* Purchase History */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <FileText className="h-5 w-5" />
            Historique des achats ({invoices.length})
          </CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {loading ? (
            <div className="p-8 text-center text-gray-500">Chargement...</div>
          ) : invoices.length === 0 ? (
            <div className="p-8 text-center text-gray-500">
              Aucune facture d'achat associée à ce fournisseur
            </div>
          ) : (
            <ScrollArea className="h-[300px]">
              <div className="divide-y">
                {invoices.map((invoice) => (
                  <div key={invoice.id} className="p-4 hover:bg-gray-50">
                    <div className="flex items-center justify-between mb-2">
                      <div className="font-medium">{invoice.numero}</div>
                      <Badge
                        variant={invoice.statut === 'VALIDE' ? 'default' : 'secondary'}
                        className={
                          invoice.statut === 'VALIDE'
                            ? 'bg-green-100 text-green-800 hover:bg-green-200'
                            : 'bg-yellow-100 text-yellow-800 hover:bg-yellow-200'
                        }
                      >
                        {invoice.statut === 'VALIDE' ? 'Validé' : 'Brouillon'}
                      </Badge>
                    </div>
                    <div className="flex items-center justify-between text-sm">
                      <div className="text-gray-500">{formatDate(invoice.date)}</div>
                      <div className="font-medium">{formatCurrency(invoice.montantTTC)}</div>
                    </div>
                  </div>
                ))}
              </div>
            </ScrollArea>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
