
import React, { useState, useMemo } from 'react';
import { Helmet } from 'react-helmet';
import { Plus, Filter, Search, MoreHorizontal, Phone, Mail, UserPlus, TrendingUp, Award, Users } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import PrimaryButton from '@/components/PrimaryButton';
import KPIBar from '@/components/KPIBar';
import { mockClients, calculateKPIs } from '@/data/mockData.js';
import { cn } from '@/lib/utils.js';

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

  // Using clients with specific status as proxy for prospects
  const allProspects = mockClients.filter(c => c.status === 'prospect' || c.status === 'inactive' || c.status === 'lead');

  const kpis = useMemo(() => {
    const stats = calculateKPIs(allProspects, period, { dateField: 'createdAt', amountField: 'id' }); // Mock dateField
    const converted = stats.items.filter(p => p.status === 'active');
    const leads = stats.items.filter(p => p.status === 'lead' || p.status === 'prospect');

    return [
      { title: 'Nouveaux Prospects', value: stats.filteredCount, change: '+12%', trend: 'up', icon: UserPlus },
      { title: 'En Qualification', value: leads.length, change: '+5', trend: 'up', icon: Users },
      { title: 'Taux Conversion', value: '15%', change: '+2%', trend: 'up', icon: TrendingUp },
      { title: 'Gagnés', value: converted.length, change: '', trend: 'neutral', icon: Award },
    ];
  }, [period, allProspects]);

  const filteredProspects = allProspects.filter(
    p => p.company.toLowerCase().includes(searchTerm.toLowerCase()) ||
      p.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const handleRowClick = (prospect) => {
    navigate(`/home/prospects/${prospect.id}`);
  };

  return (
    <>
      <Helmet>
        <title>Prospects - Bijou ERP</title>
        <meta name="description" content="Gestion de vos prospects" />
      </Helmet>

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

        {/* Header */}
        <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">Prospects</h1>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
              Gérez votre pipeline de prospection et convertissez vos leads.
            </p>
          </div>
          <div className="flex gap-3">
            <PrimaryButton icon={Plus} onClick={() => navigate('/home/prospects/create')}>
              Nouveau prospect
            </PrimaryButton>
          </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 un prospect..."
              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-[#338660]/20 focus:border-[#338660]"
            />
          </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>

        {/* List */}
        <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-xl shadow-sm overflow-hidden">
          <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">Société / Nom</th>
                <th className="px-6 py-4 font-medium text-gray-500">Contact</th>
                <th className="px-6 py-4 font-medium text-gray-500">Ville</th>
                <th className="px-6 py-4 font-medium text-gray-500">Statut</th>
                <th className="px-6 py-4 text-right font-medium text-gray-500">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
              {filteredProspects.map((prospect) => (
                <tr
                  key={prospect.id}
                  onClick={() => handleRowClick(prospect)}
                  className="group hover:bg-gray-50 dark:hover:bg-gray-900/50 transition-colors cursor-pointer"
                >
                  <td className="px-6 py-4">
                    <div className="font-medium text-gray-900 dark:text-white hover:text-[#338660] transition-colors">
                      {prospect.company}
                    </div>
                    <div className="text-xs text-gray-500">{prospect.industry}</div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 rounded-full bg-gray-100 flex items-center justify-center text-xs font-medium text-gray-600">
                        {prospect.name.charAt(0)}
                      </div>
                      <div>
                        <div className="text-gray-900 dark:text-white">{prospect.name}</div>
                        <div className="text-xs text-gray-500">{prospect.email}</div>
                      </div>
                    </div>
                  </td>
                  <td className="px-6 py-4 text-gray-600 dark:text-gray-400">
                    {prospect.city}
                  </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",
                      prospect.status === 'active' ? "bg-green-100 text-green-800" : "bg-blue-100 text-blue-800"
                    )}>
                      {prospect.status === 'active' ? 'Converti' : 'Nouveau'}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-right">
                    <div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button className="p-1.5 hover:bg-gray-200 dark:hover:bg-gray-800 rounded-lg text-gray-500">
                        <Phone className="w-4 h-4" />
                      </button>
                      <button className="p-1.5 hover:bg-gray-200 dark:hover:bg-gray-800 rounded-lg text-gray-500">
                        <Mail className="w-4 h-4" />
                      </button>
                      <button
                        className="p-1.5 hover:bg-gray-200 dark:hover:bg-gray-800 rounded-lg text-gray-500"
                      >
                        <MoreHorizontal className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
};

export default ProspectsPage;
