
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, CheckSquare, Truck, Box } from 'lucide-react';
import { mockReceptionNotes, calculateKPIs } from '@/data/mockData';
import { cn } from '@/lib/utils';
import KPIBar from '@/components/KPIBar';

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

  const kpis = useMemo(() => {
    // We can assume each reception note has a value (sum of items) for KPI purposes
    // mockReceptionNotes in mockData might not have amount field directly, so we rely on item count or fake amount
    const notesWithAmounts = mockReceptionNotes.map(n => ({...n, amount: 1000})); // Mock amount
    const stats = calculateKPIs(notesWithAmounts, period, { dateField: 'date', amountField: 'amount' });
    
    return [
      { title: 'Bons Réception', value: stats.filteredCount, change: '+4', trend: 'up', icon: CheckSquare },
      { title: 'Validés', value: stats.items.filter(n => n.status === 'validated').length, change: '+4', trend: 'up', icon: CheckSquare },
      { title: 'En Attente', value: stats.items.filter(n => n.status !== 'validated').length, change: '', trend: 'neutral', icon: Truck },
    ];
  }, [period]);

  const filteredNotes = mockReceptionNotes.filter(
    note => 
      note.number.toLowerCase().includes(searchTerm.toLowerCase()) ||
      note.supplier.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <>
      <Helmet>
        <title>Bons de Réception - 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">
              <CheckSquare className="w-6 h-6 text-[#941403]" />
              Bons de Réception
            </h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              Historique des réceptions de marchandises.
            </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 un bon..."
              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>

        <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">Commande Liée</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 Réception</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">
                {filteredNotes.map((note) => (
                  <motion.tr
                    key={note.id}
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    whileHover={{ backgroundColor: "rgba(0,0,0,0.02)" }}
                    onClick={() => navigate(`/bons-reception/${note.id}`)}
                    className="cursor-pointer group"
                  >
                    <td className="px-6 py-4 font-medium text-gray-900 dark:text-white">
                      {note.number}
                    </td>
                    <td className="px-6 py-4 text-[#941403] font-medium">
                      {note.purchaseOrder}
                    </td>
                    <td className="px-6 py-4 text-gray-600 dark:text-gray-400">
                      {note.supplier}
                    </td>
                    <td className="px-6 py-4 text-gray-600 dark:text-gray-400">
                      {note.date}
                    </td>
                    <td className="px-6 py-4">
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400">
                        Validé
                      </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 ReceptionNotesPage;
