import React, { useState, useMemo } from 'react';
import { Helmet } from 'react-helmet';
import { useNavigate } from 'react-router-dom';
import { Plus, Search, Filter, Target, TrendingUp, XCircle, Euro } from 'lucide-react';
import KanbanBoard from '@/components/KanbanBoard';
import PrimaryButton from '@/components/PrimaryButton';
import KPIBar from '@/components/KPIBar';
import { mockOpportunities, calculateKPIs } from '@/data/mockData';
import { toast } from '@/components/ui/use-toast';

const OpportunitiesPipelinePage = () => {
  const navigate = useNavigate();
  const [opportunities, setOpportunities] = useState(mockOpportunities);
  const [searchTerm, setSearchTerm] = useState('');
  const [period, setPeriod] = useState('month');

  const kpis = useMemo(() => {
    const stats = calculateKPIs(opportunities, period, { dateField: 'createdAt', amountField: 'amount' });
    const won = stats.items.filter(o => o.stage === 'won');
    const lost = stats.items.filter(o => o.stage === 'lost');

    // Total pipeline value for ALL opportunities (not just filtered period for context)
    const totalPipeline = opportunities.reduce((sum, o) => sum + o.amount, 0);

    return [
      { title: 'Total Pipeline', value: `${totalPipeline.toLocaleString()}€`, change: '', trend: 'neutral', icon: Euro },
      { title: 'Opps Créées', value: stats.filteredCount, change: '+5', trend: 'up', icon: Target },
      { title: 'Gagnées', value: won.length, change: '+2', trend: 'up', icon: TrendingUp },
      { title: 'Montant Gagné', value: `${won.reduce((acc, o) => acc + o.amount, 0).toLocaleString()}€`, change: '+8%', trend: 'up', icon: Euro },
      { title: 'Perdues', value: lost.length, change: '', trend: 'neutral', icon: XCircle },
    ];
  }, [period, opportunities]);

  const columns = [
    { id: 'new', title: 'Nouveau' },
    { id: 'qualification', title: 'Qualification' },
    { id: 'discovery', title: 'Découverte/RDV' },
    { id: 'proposal', title: 'Proposition' },
    { id: 'negotiation', title: 'Négociation' },
    { id: 'won', title: 'Gagné' },
    { id: 'lost', title: 'Perdu' },
  ];

  const handleDragEnd = (result) => {
    if (!result.destination) return;

    const { source, destination, draggableId } = result;

    if (source.droppableId === destination.droppableId) return;

    const updatedOpportunities = opportunities.map(opp => {
      if (opp.id.toString() === draggableId) {
        return { ...opp, stage: destination.droppableId };
      }
      return opp;
    });

    setOpportunities(updatedOpportunities);
    toast({
      title: "Opportunité mise à jour",
      description: "Le statut de l'opportunité a été modifié.",
    });
  };

  const handleCardAction = (action, item) => {
    if (action === 'quote') {
      navigate('/devis', { state: { opportunityId: item.id } });
      toast({ title: "Nouveau devis", description: `Création d'un devis pour ${item.name}` });
    } else if (action === 'task') {
      toast({ title: "Nouvelle tâche", description: "Ajouter une tâche de rappel" });
    } else {
      toast({ title: "Note ajoutée", description: "Note rapide ajoutée" });
    }
  };

  const filteredOpportunities = opportunities.filter(opp =>
    opp.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    opp.client.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <>
      <Helmet>
        <title>Pipeline Opportunités - Bijou ERP</title>
      </Helmet>

      <div className="h-[calc(100vh-6rem)] flex flex-col 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 flex-shrink-0">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Pipeline des ventes</h1>
            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
              {filteredOpportunities.length} opportunités actives • {filteredOpportunities.reduce((sum, o) => sum + o.amount, 0).toLocaleString()}€
            </p>
          </div>
          <div className="flex gap-3">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder="Rechercher..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-9 pr-4 py-2 bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-[#007E45]"
              />
            </div>
            <button className="p-2 bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-900 text-gray-600 dark:text-gray-400">
              <Filter className="w-5 h-5" />
            </button>
            <PrimaryButton icon={Plus} onClick={() => toast({ title: "Non implémenté", description: "Utilisez le bouton Nouveau Prospect pour l'instant" })}>
              Nouvelle opportunité
            </PrimaryButton>
          </div>
        </div>

        {/* Kanban */}
        <div className="flex-1 overflow-hidden min-h-0">
          <KanbanBoard
            columns={columns}
            items={filteredOpportunities}
            onDragEnd={handleDragEnd}
            onItemClick={(item) => navigate(`/opportunites/${item.id}`)}
            onActionItem={handleCardAction}
          />
        </div>
      </div>
    </>
  );
};

export default OpportunitiesPipelinePage;