'use client'

import { useState, useEffect } from 'react'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
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 {
  Search,
  Plus,
  Eye,
  Pencil,
  Phone,
  Mail,
  MapPin,
  Building2,
  Power,
  PowerOff,
  Trash2,
} from 'lucide-react'
import { SupplierForm } from './SupplierForm'
import { SupplierDetail } from './SupplierDetail'
import { toast } from 'sonner'

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
  _count?: {
    produits: number
    facturesAchat: number
  }
}

export function SupplierList() {
  const [suppliers, setSuppliers] = useState<Supplier[]>([])
  const [filteredSuppliers, setFilteredSuppliers] = useState<Supplier[]>([])
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all')
  const [loading, setLoading] = useState(true)
  const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(null)
  const [editingSupplier, setEditingSupplier] = useState<Supplier | null>(null)
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)
  const [isDetailDialogOpen, setIsDetailDialogOpen] = useState(false)

  useEffect(() => {
    fetchSuppliers()
  }, [])

  useEffect(() => {
    filterSuppliers()
  }, [searchTerm, statusFilter, suppliers])

  const filterSuppliers = () => {
    let filtered = [...suppliers]

    // Filter by search term
    if (searchTerm) {
      const term = searchTerm.toLowerCase()
      filtered = filtered.filter(supplier =>
        supplier.nom.toLowerCase().includes(term) ||
        (supplier.contact && supplier.contact.toLowerCase().includes(term)) ||
        (supplier.email && supplier.email.toLowerCase().includes(term)) ||
        (supplier.telephone && supplier.telephone.includes(term)) ||
        (supplier.ville && supplier.ville.toLowerCase().includes(term)) ||
        (supplier.codePostal && supplier.codePostal.includes(term))
      )
    }

    // Filter by status
    if (statusFilter === 'active') {
      filtered = filtered.filter(s => s.actif)
    } else if (statusFilter === 'inactive') {
      filtered = filtered.filter(s => !s.actif)
    }

    setFilteredSuppliers(filtered)
  }

  const fetchSuppliers = async () => {
    try {
      const response = await fetch('/api/fournisseurs')
      if (response.ok) {
        const data = await response.json()
        setSuppliers(data)
        setFilteredSuppliers(data)
      }
    } catch (error) {
      console.error('Error fetching suppliers:', error)
      toast.error('Erreur lors du chargement des fournisseurs')
    } finally {
      setLoading(false)
    }
  }

  const handleSupplierSaved = async () => {
    setIsAddDialogOpen(false)
    setEditingSupplier(null)
    await fetchSuppliers()
    toast.success(editingSupplier ? 'Fournisseur mis à jour' : 'Fournisseur créé')
  }

  const handleViewSupplier = (supplier: Supplier) => {
    setSelectedSupplier(supplier)
    setIsDetailDialogOpen(true)
  }

  const handleEditSupplier = (supplier: Supplier) => {
    setEditingSupplier(supplier)
    setIsAddDialogOpen(true)
  }

  const handleToggleStatus = async (supplier: Supplier) => {
    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) {
        await fetchSuppliers()
        toast.success(supplier.actif ? 'Fournisseur désactivé' : 'Fournisseur activé')
      } else {
        const error = await response.json()
        toast.error(error.error || 'Erreur lors de la mise à jour')
      }
    } catch (error) {
      console.error('Error toggling supplier status:', error)
      toast.error('Erreur lors de la mise à jour du statut')
    }
  }

  const handleDeleteSupplier = async (supplier: Supplier) => {
    if (!confirm(`Êtes-vous sûr de vouloir supprimer le fournisseur "${supplier.nom}" ?`)) {
      return
    }

    try {
      const response = await fetch(`/api/fournisseurs/${supplier.id}`, {
        method: 'DELETE',
      })

      if (response.ok) {
        await fetchSuppliers()
        toast.success('Fournisseur supprimé')
      } else {
        const error = await response.json()
        toast.error(error.error || 'Erreur lors de la suppression')
      }
    } catch (error) {
      console.error('Error deleting supplier:', error)
      toast.error('Erreur lors de la suppression')
    }
  }

  const activeCount = suppliers.filter(s => s.actif).length
  const inactiveCount = suppliers.length - activeCount

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">Gestion des Fournisseurs</h2>
          <p className="text-sm text-gray-500">
            {suppliers.length} fournisseur{suppliers.length !== 1 ? 's' : ''} enregistré{suppliers.length !== 1 ? 's' : ''}
          </p>
        </div>
        <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
          <DialogTrigger asChild>
            <Button className="gap-2">
              <Plus className="h-4 w-4" />
              Nouveau Fournisseur
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>
                {editingSupplier ? 'Modifier le Fournisseur' : 'Nouveau Fournisseur'}
              </DialogTitle>
              <DialogDescription>
                {editingSupplier
                  ? 'Modifiez les informations du fournisseur'
                  : 'Remplissez les informations pour créer un nouveau fournisseur'}
              </DialogDescription>
            </DialogHeader>
            <SupplierForm
              supplier={editingSupplier}
              onSave={handleSupplierSaved}
              onCancel={() => {
                setIsAddDialogOpen(false)
                setEditingSupplier(null)
              }}
            />
          </DialogContent>
        </Dialog>
      </div>

      {/* Statistics Cards */}
      <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">Total</p>
                <p className="text-2xl font-bold">{suppliers.length}</p>
              </div>
              <Building2 className="h-8 w-8 text-gray-400" />
            </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">Actifs</p>
                <p className="text-2xl font-bold text-green-600">{activeCount}</p>
              </div>
              <Power className="h-8 w-8 text-green-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">Inactifs</p>
                <p className="text-2xl font-bold text-gray-400">{inactiveCount}</p>
              </div>
              <PowerOff className="h-8 w-8 text-gray-400" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Search and Filter */}
      <Card>
        <CardContent className="pt-6">
          <div className="space-y-4">
            <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 nom, contact, email, téléphone, ville..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
            <div className="flex gap-2">
              <Button
                variant={statusFilter === 'all' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setStatusFilter('all')}
              >
                Tous ({suppliers.length})
              </Button>
              <Button
                variant={statusFilter === 'active' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setStatusFilter('active')}
              >
                Actifs ({activeCount})
              </Button>
              <Button
                variant={statusFilter === 'inactive' ? 'default' : 'outline'}
                size="sm"
                onClick={() => setStatusFilter('inactive')}
              >
                Inactifs ({inactiveCount})
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Suppliers Table */}
      <Card>
        <CardContent className="p-0">
          <ScrollArea className="h-[600px]">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Fournisseur</TableHead>
                  <TableHead>Contact</TableHead>
                  <TableHead>Adresse</TableHead>
                  <TableHead>Produits</TableHead>
                  <TableHead>Statut</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center py-8">
                      Chargement...
                    </TableCell>
                  </TableRow>
                ) : filteredSuppliers.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="text-center py-8">
                      <div className="flex flex-col items-center gap-2">
                        <Building2 className="h-12 w-12 text-gray-400" />
                        <p className="text-gray-500">
                          {searchTerm || statusFilter !== 'all'
                            ? 'Aucun fournisseur trouvé'
                            : 'Aucun fournisseur enregistré'}
                        </p>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredSuppliers.map((supplier) => (
                    <TableRow key={supplier.id} className="hover:bg-gray-50">
                      <TableCell>
                        <div>
                          <div className="font-medium">{supplier.nom}</div>
                          {supplier.contact && (
                            <div className="text-sm text-gray-500">{supplier.contact}</div>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="space-y-1">
                          {supplier.email && (
                            <div className="flex items-center gap-2 text-sm">
                              <Mail className="h-3 w-3 text-gray-400" />
                              <span className="truncate max-w-[150px]">{supplier.email}</span>
                            </div>
                          )}
                          {supplier.telephone && (
                            <div className="flex items-center gap-2 text-sm">
                              <Phone className="h-3 w-3 text-gray-400" />
                              <span>{supplier.telephone}</span>
                            </div>
                          )}
                        </div>
                      </TableCell>
                      <TableCell>
                        {supplier.adresse || supplier.ville || supplier.codePostal ? (
                          <div className="space-y-1">
                            {supplier.adresse && (
                              <div className="text-sm text-gray-600 truncate max-w-[150px]">
                                {supplier.adresse}
                              </div>
                            )}
                            <div className="flex items-center gap-1 text-sm text-gray-500">
                              <MapPin className="h-3 w-3" />
                              <span>
                                {supplier.codePostal && `${supplier.codePostal} `}
                                {supplier.ville}
                              </span>
                            </div>
                          </div>
                        ) : (
                          <span className="text-gray-400 text-sm">Non renseignée</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <Badge variant="secondary">
                          {supplier._count?.produits || 0}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <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>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleViewSupplier(supplier)}
                          >
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleEditSupplier(supplier)}
                          >
                            <Pencil className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleToggleStatus(supplier)}
                            title={supplier.actif ? 'Désactiver' : 'Activer'}
                          >
                            {supplier.actif ? (
                              <PowerOff className="h-4 w-4" />
                            ) : (
                              <Power className="h-4 w-4" />
                            )}
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDeleteSupplier(supplier)}
                            className="text-red-600 hover:text-red-700"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </ScrollArea>
        </CardContent>
      </Card>

      {/* Supplier Detail Dialog */}
      <Dialog open={isDetailDialogOpen} onOpenChange={setIsDetailDialogOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Détail du Fournisseur</DialogTitle>
            <DialogDescription>
              Informations complètes et historique des achats
            </DialogDescription>
          </DialogHeader>
          {selectedSupplier && (
            <SupplierDetail
              supplier={selectedSupplier}
              onClose={() => setIsDetailDialogOpen(false)}
              onUpdate={fetchSuppliers}
              onEdit={() => {
                setEditingSupplier(selectedSupplier)
                setIsDetailDialogOpen(false)
                setIsAddDialogOpen(true)
              }}
            />
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
