
import React, { useState } from 'react';
import { Helmet } from 'react-helmet';
import { useParams, useNavigate } from 'react-router-dom';
import {
  ArrowLeft, Mail, Phone, MapPin, Tag, FileText, Clock,
  Ticket, Plus, Edit, Trash2, Lightbulb, Building2, Wallet
} 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 { toast } from '@/components/ui/use-toast';
import { mockClients, mockTimeline, mockOpportunities } from '@/data/mockData';
import ProspectFormModal from '@/components/forms/ProspectFormModal';
import { cn } from '@/lib/utils';

const ProspectDetailPage = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('info');
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);

  // Simulate fetching prospect from mockClients (assuming filtered by ID)
  const prospect = mockClients.find(c => c.id === parseInt(id));

  if (!prospect) {
    return (
      <div className="flex flex-col items-center justify-center min-h-[400px]">
        <h2 className="text-xl font-bold text-gray-900 dark:text-white">Prospect non trouvé</h2>
        <button onClick={() => navigate('/prospects')} className="mt-4 text-[#007E45] hover:underline">Retour à la liste</button>
      </div>
    );
  }

  const tabs = [
    { id: 'info', label: 'Informations' },
    { id: 'timeline', label: 'Historique' },
    { id: 'opportunities', label: 'Opportunités' },
    { id: 'documents', label: 'Documents' },
  ];

  // Filter timeline and opportunities for this mock prospect
  // In a real app, this would be an API call filtering by prospect_id
  const prospectTimeline = mockTimeline.slice(0, 5);
  const prospectOpportunities = mockOpportunities.slice(0, 2).map(o => ({ ...o, client: prospect.company }));

  return (
    <>
      <Helmet>
        <title>{prospect.name} - Prospects - Bijou ERP</title>
        <meta name="description" content={`Fiche prospect ${prospect.name}`} />
      </Helmet>

      <div className="space-y-6">
        {/* Breadcrumbs & Back */}
        <div className="flex items-center justify-between">
          <nav className="flex items-center gap-2 text-sm text-gray-500">
            <button onClick={() => navigate('/home/prospects')} className="hover:text-gray-900 dark:hover:text-white flex items-center gap-1">
              <ArrowLeft className="w-4 h-4" />
              Prospects
            </button>
            <span className="text-gray-300">/</span>
            <span className="font-medium text-gray-900 dark:text-white">{prospect.name}</span>
          </nav>
        </div>

        {/* Header Card */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          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 className="flex items-start gap-5">
              <div className="w-20 h-20 rounded-2xl bg-gradient-to-br from-[#007E45] to-green-700 text-white flex items-center justify-center text-3xl font-bold shadow-lg shadow-red-900/20">
                {prospect.name.charAt(0)}
              </div>
              <div>
                <h1 className="text-2xl font-bold text-gray-900 dark:text-white">{prospect.name}</h1>
                <div className="flex items-center gap-2 mt-1 text-gray-500">
                  <Building2 className="w-4 h-4" />
                  <span>{prospect.company}</span>
                </div>
                <div className="flex items-center gap-3 mt-4">
                  <div className={cn(
                    "px-3 py-1 rounded-full text-xs font-medium border",
                    prospect.status === 'active' ? "bg-green-50 text-green-700 border-green-200" : "bg-blue-50 text-blue-700 border-blue-200"
                  )}>
                    {prospect.status === 'active' ? 'Converti' : 'Nouveau Prospect'}
                  </div>
                  <span className="flex items-center gap-1 text-xs text-gray-500">
                    <Clock className="w-3 h-3" /> Dernière activité: {prospect.lastActivity}
                  </span>
                </div>
              </div>
            </div>

            <div className="flex flex-wrap gap-2">
              <button
                onClick={() => setIsEditModalOpen(true)}
                className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
              >
                <Edit className="w-4 h-4" />
                Modifier
              </button>
              <PrimaryButton
                icon={Lightbulb}
                onClick={() => toast({ title: "Opportunité créée", description: "Nouvelle opportunité ajoutée au pipeline" })}
              >
                Créer opportunité
              </PrimaryButton>
              <button className="p-2 text-green-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-xl transition-colors">
                <Trash2 className="w-5 h-5" />
              </button>
            </div>
          </div>

          {/* Quick Info Bar */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mt-8 pt-6 border-t border-gray-100 dark:border-gray-800">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-gray-50 dark:bg-gray-900 rounded-lg">
                <Mail className="w-4 h-4 text-gray-400" />
              </div>
              <div className="truncate">
                <p className="text-xs text-gray-500">Email</p>
                <p className="text-sm font-medium text-gray-900 dark:text-white truncate" title={prospect.email}>{prospect.email}</p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <div className="p-2 bg-gray-50 dark:bg-gray-900 rounded-lg">
                <Phone className="w-4 h-4 text-gray-400" />
              </div>
              <div>
                <p className="text-xs text-gray-500">Téléphone</p>
                <p className="text-sm font-medium text-gray-900 dark:text-white">{prospect.phone}</p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <div className="p-2 bg-gray-50 dark:bg-gray-900 rounded-lg">
                <Tag className="w-4 h-4 text-gray-400" />
              </div>
              <div>
                <p className="text-xs text-gray-500">Secteur</p>
                <p className="text-sm font-medium text-gray-900 dark:text-white">{prospect.industry}</p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <div className="p-2 bg-gray-50 dark:bg-gray-900 rounded-lg">
                <MapPin className="w-4 h-4 text-gray-400" />
              </div>
              <div>
                <p className="text-xs text-gray-500">Ville</p>
                <p className="text-sm font-medium text-gray-900 dark:text-white">{prospect.city}</p>
              </div>
            </div>
          </div>
        </motion.div>

        {/* Tabs 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-8">
            {activeTab === 'info' && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-12 animate-in fade-in slide-in-from-bottom-4 duration-500">
                <div className="space-y-6">
                  <h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                    <Building2 className="w-4 h-4 text-[#007E45]" />
                    Informations Société
                  </h3>
                  <dl className="space-y-4">
                    <div className="grid grid-cols-3 gap-4">
                      <dt className="text-sm text-gray-500">Raison sociale</dt>
                      <dd className="text-sm font-medium text-gray-900 dark:text-white col-span-2">{prospect.company}</dd>
                    </div>
                    <div className="grid grid-cols-3 gap-4">
                      <dt className="text-sm text-gray-500">Secteur</dt>
                      <dd className="text-sm font-medium text-gray-900 dark:text-white col-span-2">{prospect.industry}</dd>
                    </div>
                    <div className="grid grid-cols-3 gap-4">
                      <dt className="text-sm text-gray-500">Site Web</dt>
                      <dd className="text-sm font-medium text-[#007E45] col-span-2 cursor-pointer hover:underline">www.example.com</dd>
                    </div>
                  </dl>
                </div>

                <div className="space-y-6">
                  <h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                    <Wallet className="w-4 h-4 text-[#007E45]" />
                    Potentiel & Budget
                  </h3>
                  <dl className="space-y-4">
                    <div className="grid grid-cols-3 gap-4">
                      <dt className="text-sm text-gray-500">Intérêt</dt>
                      <dd className="col-span-2"><span className="px-2 py-1 bg-orange-100 text-orange-700 rounded text-xs font-bold">Moyen</span></dd>
                    </div>
                    <div className="grid grid-cols-3 gap-4">
                      <dt className="text-sm text-gray-500">Budget Est.</dt>
                      <dd className="text-sm font-medium text-gray-900 dark:text-white col-span-2">15 000 € - 25 000 €</dd>
                    </div>
                    <div className="grid grid-cols-3 gap-4">
                      <dt className="text-sm text-gray-500">Échéance</dt>
                      <dd className="text-sm font-medium text-gray-900 dark:text-white col-span-2">Q4 2025</dd>
                    </div>
                  </dl>
                </div>
              </div>
            )}

            {activeTab === 'timeline' && (
              <Timeline events={prospectTimeline} />
            )}

            {activeTab === 'opportunities' && (
              <div className="space-y-4 animate-in fade-in slide-in-from-bottom-4">
                {prospectOpportunities.length > 0 ? prospectOpportunities.map(opp => (
                  <div key={opp.id} className="flex items-center justify-between p-4 border border-gray-100 dark:border-gray-800 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-900 transition-colors">
                    <div className="flex items-center gap-4">
                      <div className="p-2 bg-amber-50 text-amber-600 rounded-lg">
                        <Lightbulb className="w-5 h-5" />
                      </div>
                      <div>
                        <h4 className="font-medium text-gray-900 dark:text-white">{opp.name}</h4>
                        <p className="text-xs text-gray-500">{opp.amount} € • {opp.probability}% de chance</p>
                      </div>
                    </div>
                    <StatusBadge status={opp.stage} />
                  </div>
                )) : (
                  <div className="text-center py-12">
                    <Lightbulb className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                    <p className="text-gray-500">Aucune opportunité détectée</p>
                    <button className="mt-2 text-sm text-[#007E45] font-medium hover:underline">Créer une opportunité</button>
                  </div>
                )}
              </div>
            )}

            {activeTab === 'documents' && (
              <div className="text-center py-12 animate-in fade-in">
                <FileText className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                <p className="text-gray-500">Aucun document associé</p>
                <p className="text-xs text-gray-400">Glissez-déposez des fichiers pour les attacher à ce prospect</p>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Edit Modal */}
      <ProspectFormModal
        isOpen={isEditModalOpen}
        onClose={() => setIsEditModalOpen(false)}
        initialData={{
          type: 'entreprise',
          name: prospect.name,
          companyName: prospect.company,
          email: prospect.email,
          phone: prospect.phone.replace(/\s/g, ''),
          address1: '123 Rue Example',
          zipCode: '75000',
          city: prospect.city,
          country: 'France',
          contactName: prospect.name.split(' ')[1] || '',
          contactFirstName: prospect.name.split(' ')[0] || '',
        }}
      />
    </>
  );
};

export default ProspectDetailPage;
