
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, Package, ShoppingCart, CheckCircle, Euro } from 'lucide-react';
import { mockPurchaseOrders, calculateKPIs } from '@/data/mockData';
import { cn } from '@/lib/utils';
import KPIBar from '@/components/KPIBar';

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

  const kpis = useMemo(() => {
    const stats = calculateKPIs(mockPurchaseOrders, period, { dateField: 'date', amountField: 'amountHT' });
    const validated = stats.items.filter(o => o.status !== 'draft');
    
    return [
      { title: 'Montant Engagé', value: `${stats.totalAmount.toLocaleString()}€`, change: '+5%', trend: 'up', icon: Euro },
      { title: 'Nombre de BC', value: stats.filteredCount, change: '+2', trend: 'up', icon: ShoppingCart },
      { title: 'BC Validés', value: validated.length, change: '+3', trend: 'up', icon: CheckCircle },
      { title: 'Livraisons en Attente', value: stats.items.filter(o => o.status === 'sent').length, change: '', trend: 'neutral', icon: Package },
    ];
  }, [period]);

  const getStatusColor = (status) => {
    switch (status) {
      case 'received': return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
      case 'sent': return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400';
      case 'draft': return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300';
      case 'invoiced': return 'bg-purple-100 text-purple-800 dark:bg-purple-900/30 dark:text-purple-400';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getStatusLabel = (status) => {
    switch (status) {
      case 'received': return 'Reçu';
      case 'sent': return 'Envoyé';
      case 'draft': return 'Brouillon';
      case 'invoiced': return 'Facturé';
      default: return status;
    }
  };

  const filteredOrders = mockPurchaseOrders.filter(
    order => 
      order.number.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.supplier.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <>
      <Helmet>
        <title>Commandes 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">
              <Package className="w-6 h-6 text-[#941403]" />
              Commandes Fournisseurs
            </h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              Gérez vos approvisionnements et commandes d'achat.
            </p>
          </div>
        </div>

        {/* Filters */}
        <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 commande..."
              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>
          <button className="flex items-center gap-2 px-4 py-2 bg-gray-50 dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm font-medium hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors">
            <Filter className="w-4 h-4" />
            Filtres
          </button>
        </div>

        {/* Table */}
        <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</th>
                  <th className="px-6 py-4 font-medium text-gray-500 dark:text-gray-400">Livraison Prévue</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">
                {filteredOrders.map((order) => (
                  <motion.tr
                    key={order.id}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    whileHover={{ backgroundColor: "rgba(0,0,0,0.02)" }}
                    onClick={() => navigate(`/bons-commande/${order.id}`)}
                    className="cursor-pointer group"
                  >
                    <td className="px-6 py-4 font-medium text-gray-900 dark:text-white">
                      {order.number}
                    </td>
                    <td className="px-6 py-4 text-gray-600 dark:text-gray-400">
                      {order.supplier}
                    </td>
                    <td className="px-6 py-4 text-gray-600 dark:text-gray-400">
                      {order.date}
                    </td>
                    <td className="px-6 py-4 text-gray-600 dark:text-gray-400">
                      {order.deliveryDate}
                    </td>
                    <td className="px-6 py-4 text-right font-medium text-gray-900 dark:text-white">
                      {order.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(order.status))}>
                        {getStatusLabel(order.status)}
                      </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 PurchaseOrdersPage;
