
import React, { useState } from 'react';
import { Helmet } from 'react-helmet';
import { useParams, useNavigate } from 'react-router-dom';
import {
   ArrowLeft, Calendar, User, DollarSign, FileText, Plus,
   Building2, Phone, Mail, Trash2, Edit, Paperclip, Link, Send
} from 'lucide-react';
import { motion } from 'framer-motion';
import Tabs from '@/components/Tabs';
import StatusBadge from '@/components/StatusBadget';
import PrimaryButton from '@/components/PrimaryButton';
import Timeline from '@/components/Timeline';
import DataTable from '@/components/DataTable';
import { mockOpportunities, mockTimeline, mockClients, mockContacts, mockQuotes } from '@/data/mockData';
import { toast } from '@/components/ui/use-toast';
import FormModal from '@/components/FormModal';
import SmartForm from '@/components/SmartForm';
import { z } from 'zod';

const OpportunityDetailPage = () => {
   const { id } = useParams();
   const navigate = useNavigate();
   const [activeTab, setActiveTab] = useState('details');

   const opportunity = mockOpportunities.find(o => o.id === parseInt(id));

   if (!opportunity) return <div className="p-8 text-center">Opportunité introuvable</div>;

   const client = mockClients.find(c => c.id === opportunity.clientId) || {};
   const contact = mockContacts.find(c => c.id === opportunity.contactId) || {};
   const relatedQuotes = mockQuotes.filter(q => q.opportunityId === opportunity.id);

   const tabs = [
      { id: 'details', label: 'Détails' },
      { id: 'contacts', label: 'Contacts associés' },
      { id: 'company', label: 'Entreprise associée' },
      { id: 'quotes', label: 'Pièces commerciales' },
      { id: 'timeline', label: 'Timeline' },
      { id: 'documents', label: 'Documents' }
   ];

   return (
      <>
         <Helmet>
            <title>{opportunity.name} - Opportunité - Bijou ERP</title>
         </Helmet>

         <div className="space-y-6 max-w-7xl mx-auto">
            {/* Navigation */}
            <div className="flex items-center justify-between">
               <nav className="flex items-center gap-2 text-sm text-gray-500">
                  <button onClick={() => navigate('/opportunites')} className="hover:text-gray-900 dark:hover:text-white flex items-center gap-1">
                     <ArrowLeft className="w-4 h-4" />
                     Pipeline
                  </button>
                  <span className="text-gray-300">/</span>
                  <span className="font-medium text-gray-900 dark:text-white">{opportunity.name}</span>
               </nav>
            </div>

            {/* Header */}
            <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6 shadow-sm">
               <div className="flex flex-col md:flex-row md:items-start justify-between gap-6">
                  <div>
                     <div className="flex items-center gap-3 mb-2">
                        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">{opportunity.name}</h1>
                        <StatusBadge status={opportunity.stage} />
                     </div>
                     <div className="flex flex-wrap gap-4 text-sm text-gray-500">
                        <span className="flex items-center gap-1"><Building2 className="w-4 h-4" /> {client.company || opportunity.client}</span>
                        <span className="flex items-center gap-1"><User className="w-4 h-4" /> {contact.firstName} {contact.lastName}</span>
                        <span className="flex items-center gap-1 text-[#941403] font-semibold"><DollarSign className="w-4 h-4" /> {opportunity.amount.toLocaleString()}€</span>
                     </div>
                  </div>
                  <div className="flex flex-wrap gap-2">
                     <button className="p-2 text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-xl" title="Modifier">
                        <Edit className="w-5 h-5" />
                     </button>
                     <button className="p-2 text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-xl" title="Supprimer">
                        <Trash2 className="w-5 h-5" />
                     </button>
                     <PrimaryButton icon={Link} onClick={() => toast({ title: "Associer un devis", description: "Sélectionnez un devis existant" })} className="bg-gray-900 hover:bg-gray-800">
                        Lier Devis
                     </PrimaryButton>
                     <PrimaryButton icon={FileText} onClick={() => navigate('/devis')}>
                        Créer Devis
                     </PrimaryButton>
                  </div>
               </div>

               {/* Progress Bar */}
               <div className="mt-6">
                  <div className="flex justify-between text-xs text-gray-500 mb-2">
                     <span>Probabilité de succès</span>
                     <span>{opportunity.probability}%</span>
                  </div>
                  <div className="h-2 bg-gray-100 dark:bg-gray-800 rounded-full overflow-hidden">
                     <div
                        className="h-full bg-gradient-to-r from-orange-500 to-[#941403] transition-all duration-1000"
                        style={{ width: `${opportunity.probability}%` }}
                     />
                  </div>
               </div>
            </div>

            {/* Content */}
            <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6 shadow-sm min-h-[500px]">
               <Tabs tabs={tabs} active={activeTab} onChange={setActiveTab} />

               <div className="mt-6">
                  {activeTab === 'details' && (
                     <div className="grid grid-cols-1 md:grid-cols-2 gap-8 animate-in fade-in slide-in-from-bottom-2">
                        <div className="space-y-4">
                           <h3 className="text-sm font-semibold text-gray-900 dark:text-white uppercase tracking-wider">Général</h3>
                           <dl className="space-y-3 text-sm">
                              <div className="grid grid-cols-3"><dt className="text-gray-500">Propriétaire</dt><dd className="col-span-2 font-medium">{opportunity.owner}</dd></div>
                              <div className="grid grid-cols-3"><dt className="text-gray-500">Priorité</dt><dd className="col-span-2"><StatusBadge status={opportunity.priority || 'normal'} /></dd></div>
                              <div className="grid grid-cols-3"><dt className="text-gray-500">Date clôture</dt><dd className="col-span-2 font-medium">{new Date(opportunity.closeDate).toLocaleDateString()}</dd></div>
                              <div className="grid grid-cols-3"><dt className="text-gray-500">Créé le</dt><dd className="col-span-2">{new Date(opportunity.createdAt).toLocaleDateString()}</dd></div>
                           </dl>
                        </div>
                        <div className="space-y-4">
                           <h3 className="text-sm font-semibold text-gray-900 dark:text-white uppercase tracking-wider">Description & Besoins</h3>
                           <div className="p-4 bg-gray-50 dark:bg-gray-900 rounded-xl text-sm text-gray-700 dark:text-gray-300 leading-relaxed">
                              {opportunity.description}
                           </div>
                        </div>
                     </div>
                  )}

                  {activeTab === 'contacts' && (
                     <div className="space-y-4 animate-in fade-in">
                        {contact.id ? (
                           <div className="flex items-center justify-between p-4 border border-gray-200 dark:border-gray-800 rounded-xl">
                              <div className="flex items-center gap-4">
                                 <div className="w-10 h-10 rounded-full bg-gray-100 flex items-center justify-center text-gray-600 font-bold">
                                    {contact.firstName[0]}{contact.lastName[0]}
                                 </div>
                                 <div>
                                    <p className="font-medium text-gray-900 dark:text-white">{contact.firstName} {contact.lastName}</p>
                                    <p className="text-xs text-gray-500">{contact.role}</p>
                                 </div>
                              </div>
                              <div className="flex gap-2">
                                 <button className="p-2 hover:bg-gray-100 rounded-full"><Mail className="w-4 h-4 text-gray-500" /></button>
                                 <button className="p-2 hover:bg-gray-100 rounded-full"><Phone className="w-4 h-4 text-gray-500" /></button>
                              </div>
                           </div>
                        ) : <div className="text-center py-8 text-gray-500">Aucun contact associé</div>}
                        <button className="w-full py-3 border-2 border-dashed border-gray-200 dark:border-gray-800 rounded-xl text-sm text-gray-500 hover:border-[#941403] hover:text-[#941403] transition-colors">
                           + Ajouter un contact
                        </button>
                     </div>
                  )}

                  {activeTab === 'company' && (
                     <div className="p-6 border border-gray-200 dark:border-gray-800 rounded-xl animate-in fade-in">
                        <div className="flex items-center gap-4 mb-6">
                           <div className="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center"><Building2 className="w-6 h-6 text-gray-600" /></div>
                           <div>
                              <h3 className="text-lg font-bold">{client.company}</h3>
                              <p className="text-sm text-gray-500">{client.industry} • {client.city}</p>
                           </div>
                        </div>
                        <div className="grid grid-cols-2 gap-4 text-sm">
                           <div><label className="text-xs text-gray-500">Email</label><p className="font-medium">{client.email}</p></div>
                           <div><label className="text-xs text-gray-500">Téléphone</label><p className="font-medium">{client.phone}</p></div>
                        </div>
                     </div>
                  )}

                  {activeTab === 'quotes' && (
                     <div className="space-y-4 animate-in fade-in">
                        {relatedQuotes.length > 0 ? (
                           <DataTable
                              columns={[
                                 { key: 'number', label: 'Numéro' },
                                 { key: 'date', label: 'Date' },
                                 { key: 'amountHT', label: 'Montant HT', render: (v) => `${v.toLocaleString()}€` },
                                 { key: 'status', label: 'Statut', render: (v) => <StatusBadge status={v} /> }
                              ]}
                              data={relatedQuotes}
                              actions={(row) => (
                                 <button onClick={() => navigate(`/devis/${row.id}`)} className="p-2 hover:bg-gray-100 rounded"><ArrowLeft className="w-4 h-4 rotate-180" /></button>
                              )}
                           />
                        ) : (
                           <div className="text-center py-12">
                              <FileText className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                              <p className="text-gray-500">Aucune pièce commerciale associée</p>
                           </div>
                        )}
                     </div>
                  )}

                  {activeTab === 'timeline' && <Timeline events={mockTimeline.slice(0, 8)} />}

                  {activeTab === 'documents' && (
                     <div className="text-center py-12 border-2 border-dashed border-gray-200 rounded-xl animate-in fade-in">
                        <Paperclip className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                        <p className="text-gray-500 mb-4">Aucun document pour l'instant</p>
                        <PrimaryButton>Téléverser un fichier</PrimaryButton>
                     </div>
                  )}
               </div>
            </div>
         </div>
      </>
   );
};

export default OpportunityDetailPage;
