
import React, { useState, useMemo } from 'react';
import { Helmet } from 'react-helmet';
import { useNavigate } from 'react-router-dom';
import { motion } from 'framer-motion';
import { Search, Filter, MoreHorizontal, Receipt, CheckCircle, AlertTriangle, Euro, FileText } from 'lucide-react';
import { mockPurchaseInvoices, calculateKPIs } from '@/data/mockData';
import { cn } from '@/lib/utils';
import KPIBar from '@/components/KPIBar';

const PurchaseInvoicesPage = () => {
  const navigate = useNavigate();
  const [searchTerm, setSearchTerm] = useState('');
  const [period, setPeriod] = useState('month');

  const kpis = useMemo(() => {
    const stats = calculateKPIs(mockPurchaseInvoices, period, { dateField: 'date', amountField: 'amountTTC' });
    const paid = stats.items.filter(i => i.status === 'paid');
    const overdue = stats.items.filter(i => i.status === 'overdue');

    return [
      { title: 'Total Facturé', value: `${stats.totalAmount.toLocaleString()}€`, change: '+2%', trend: 'up', icon: Euro },
      { title: 'Nombre Factures', value: stats.filteredCount, change: '+1', trend: 'up', icon: FileText },
      { title: 'Payées', value: paid.length, change: '+3', trend: 'up', icon: CheckCircle },
      { title: 'En Retard', value: overdue.length, change: overdue.length > 0 ? '+1' : '', trend: overdue.length > 0 ? 'down' : 'neutral', icon: AlertTriangle },
    ];
  }, [period]);

  const getStatusColor = (status) => {
    switch (status) {
      case 'paid': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
      case 'pending': return 'bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400';
      case 'overdue': return 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const filteredInvoices = mockPurchaseInvoices.filter(
    inv => 
      inv.number.toLowerCase().includes(searchTerm.toLowerCase()) ||
      inv.supplier.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <>
      <Helmet>
        <title>Factures Fournisseurs - Bijou ERP</title>
      </Helmet>

      <div className="space-y-6">
        <KPIBar kpis={kpis} period={period} onPeriodChange={setPeriod} />

        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
              <Receipt className="w-6 h-6 text-[#941403]" />
              Factures Fournisseurs
            </h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              Suivi de la facturation et des paiements fournisseurs.
            </p>
          </div>
        </div>

        <div className="flex flex-col sm:flex-row gap-4 p-4 bg-white dark:bg-gray-950 rounded-xl border border-gray-200 dark:border-gray-800 shadow-sm">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Rechercher une facture..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#941403]/20 focus:border-[#941403]"
            />
          </div>
        </div>

        <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-xl shadow-sm overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-left text-sm">
              <thead className="bg-gray-50 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800">
                <tr>
                  <th className="px-6 py-4 font-medium text-gray-500 dark:text-gray-400">Numéro</th>
                  <th className="px-6 py-4 font-medium text-gray-500 dark:text-gray-400">Fournisseur</th>
                  <th className="px-6 py-4 font-medium text-gray-500 dark:text-gray-400">Date Échéance</th>
                  <th className="px-6 py-4 font-medium text-gray-500 dark:text-gray-400 text-right">Montant TTC</th>
                  <th className="px-6 py-4 font-medium text-gray-500 dark:text-gray-400">Statut</th>
                  <th className="px-6 py-4 font-medium text-gray-500 dark:text-gray-400 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
                {filteredInvoices.map((inv) => (
                  <motion.tr
                    key={inv.id}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    whileHover={{ backgroundColor: "rgba(0,0,0,0.02)" }}
                    onClick={() => navigate(`/factures-achat/${inv.id}`)}
                    className="cursor-pointer group"
                  >
                    <td className="px-6 py-4 font-medium text-gray-900 dark:text-white">
                      {inv.number}
                    </td>
                    <td className="px-6 py-4 text-gray-600 dark:text-gray-400">
                      {inv.supplier}
                    </td>
                    <td className="px-6 py-4 text-gray-600 dark:text-gray-400">
                      {inv.dueDate}
                    </td>
                    <td className="px-6 py-4 text-right font-medium text-gray-900 dark:text-white">
                      {inv.amountTTC.toLocaleString('fr-FR', { style: 'currency', currency: 'EUR' })}
                    </td>
                    <td className="px-6 py-4">
                      <span className={cn("inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium", getStatusColor(inv.status))}>
                        {inv.status === 'paid' ? 'Payée' : inv.status === 'pending' ? 'En attente' : 'En retard'}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right">
                      <button className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors text-gray-400 hover:text-gray-600 dark:hover:text-gray-200">
                        <MoreHorizontal className="w-4 h-4" />
                      </button>
                    </td>
                  </motion.tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </>
  );
};

export default PurchaseInvoicesPage;
