import React, { useEffect, useMemo, useState } from 'react';
import { Helmet } from 'react-helmet';
import { useNavigate } from 'react-router-dom';
import {
  ArrowLeft, FileText, Building2,  MapPin,
  CreditCard, Edit, MoreVertical,
  Package, Truck,
  Plus,
  Trash2,
  File,
  Paperclip,
  Upload,
  HardDrive,
  Bell
} from 'lucide-react';
import { motion } from 'framer-motion';
import Tabs from '@/components/Tabs';
import Timeline from '@/components/Timeline';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { getClientSelected } from '@/store/features/client/selectors';
import { Client, ClientRequest, Contacts } from '@/types/clientType';
import PrimaryButton_v2 from '@/components/PrimaryButton_v2';
import { devisStatus, getAllDevis, getDevisSelected } from '@/store/features/devis/selectors';
import { DevisListItem } from '@/types/devisType';
import { getDevisList, selectDevisAsync } from '@/store/features/devis/thunk';
import { commandeStatus, getAllcommandes } from '@/store/features/commande/selectors';
import { Commande } from '@/types/commandeTypes';
import { getCommandes } from '@/store/features/commande/thunk';
import { ModalQuote } from '@/components/modal/ModalQuote';
import StatusBadgetLettre from '@/components/StatusBadgetLettre';
import { toast } from '@/components/ui/use-toast';
import ToggleSwitch from '@/components/ui/ToggleSwitch';
import ModalContact from '@/components/modal/ModalContact';
import { formatDateFRCourt } from '@/lib/utils';
import { UniversignType } from '@/types/sageTypes';
import { getAlluniversign } from '@/store/features/universign/selectors';
import ClientDetailsGrid from '@/components/page/client/ClientDetailsGrid';
import ClientContactsList from '@/components/page/client/ClientContactsList';
import { updateClient, updateStatus } from '@/store/features/client/thunk';
import { selectClient } from '@/store/features/client/slice';
import { ModalLoading } from '@/components/modal/ModalLoading';
import PDFPreview, { DocumentData } from '@/components/modal/PDFPreview';
import { usePDFPreview } from '@/components/ui/PDFActionButtons';
import { CompanyInfo } from '@/data/mockData';
import { downloadSignedDocument } from '@/store/features/universign/thunk';
import ClientInfoVerifier from '@/components/page/client/ClientInfoVerifier';


const ClientDetailPage = () => {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);
  const dispatch = useAppDispatch();
  const [activeTab, setActiveTab] = useState('info');

  const client = useAppSelector(getClientSelected) as Client;
  
  const devis = useAppSelector(getAllDevis) as DevisListItem[];
  const universign = useAppSelector(getAlluniversign) as UniversignType[];
  const statusDevis = useAppSelector(devisStatus);
  const commandes = useAppSelector(getAllcommandes) as Commande[];
  const statusCommande = useAppSelector(commandeStatus);

  
  const [isActive, setIsActive] = useState(client?.est_actif ?? true);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const { showPreview, openPreview, closePreview } = usePDFPreview();

  const [isCreateModalContactOpen, setIsCreateModalContactOpen] = useState(false);
  const [editing, setEditing] = useState<Contacts | null>(null);

  useEffect(() => {
    const load = async () => {
      if (statusDevis === "idle") await dispatch(getDevisList()).unwrap();
      if (statusCommande === "idle") await dispatch(getCommandes()).unwrap();
    };
    load();
  }, [statusDevis, statusCommande, dispatch]);

  if (!client) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-gray-500">Client non trouvé</p>
      </div>
    );
  }
  const devisSelected = useAppSelector(getDevisSelected) as DevisListItem;
  const devisClient = devis.filter((item) => item.client_code === client.numero);
  const commandeClient = commandes.filter((item) => item.client_code === client.numero);
  
  const devisSignedClient = universign.filter(
    (item) => item.local_status === "SIGNE" && item.sage_document_id && devisClient.some((d) => d.numero === item.sage_document_id)
  );

  console.log("devisSignedClient : ",devisSignedClient);
  
  

  const timelineEventsDevis = devisClient
    .map(d => ({
      type: 'quote' as const,
      title: 'Devis créé',
      description: `${d.numero} pour ${d.total_ttc.toLocaleString('fr-FR')}€`,
      date: d.date,
      user: d.statut,
      link: `/home/devis/${d.numero}`,
      item: d
    }))
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

  const timelineEventsCommande = commandeClient
    .map(d => ({
      type: 'commande' as const,
      title: 'Commande créée',
      description: `${d.numero} pour ${d.total_ttc.toLocaleString('fr-FR')}€`,
      date: d.date,
      user: d.statut,
      link: `/home/commandes/${d.numero}`,
      item: d
    }))
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

  const timelineEvents = [
    ...timelineEventsDevis,
    ...timelineEventsCommande,
  ].sort(
    (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
  );

  const handleToggleActive = async (newStatus: boolean) => {
    setIsActive(newStatus);
    setIsLoading(true);
    
    try {
   
        const rep = await dispatch(updateStatus({
            numero: client.numero,
            est_actif: newStatus
        })).unwrap() as any;

        const dataResponse = rep.client as Client;
        
        toast({
            title: "Client mis à jour !",
            description: `Le client ${dataResponse.numero} a été mis à jour avec succès.`,
            className: "bg-green-500 text-white border-green-600"
        });

        dispatch(selectClient(dataResponse));
        navigate(`/home/clients/${dataResponse.numero}`);

    } catch (e: any) {
        console.error("Erreur lors de la sauvegarde:", e);
        toast({
            title: "Erreur",
            description: e.message || "Une erreur est survenue.",
            variant: "destructive"
        });
    } finally {
        setIsLoading(false);
    }
  };



  // Fonction pour obtenir le libellé du type de tiers
  const getTypeTiersLabel = (type: number): string => {
    const types: Record<number, string> = {
      0: 'Client',
      1: 'Fournisseur',
      2: 'Client & Fournisseur',
      3: 'Autre'
    };
    return types[type] || 'Non défini';
  };

  const getBadges = () => {
    const badges = [];
    if (client.type_tiers === 1 || client.type_tiers === 2) {
      badges.push({ label: 'Fournisseur', color: 'bg-blue-100 text-blue-700 dark:bg-blue-900/20 dark:text-blue-300' });
    }
    if (!client.est_actif) {
      badges.push({ label: 'Inactif', color: 'bg-red-100 text-red-700 dark:bg-red-900/20 dark:text-red-300' });
    }
    if (client.est_prospect) {
      badges.push({ label: 'Prospect', color: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/20 dark:text-yellow-300' });
    }
    return badges;
  };

  const tabs = [
    { id: 'info', label: 'Informations' },
    { id: 'contacts', label: 'Contacts', count: client.contacts?.length || 0 },
    { id: 'relances', label: 'Relances & Relevés' },
    { id: 'timeline', label: 'Timeline', count: timelineEvents.length || 0 },
    { id: 'documents', label: 'Documents', count: devisSignedClient.length || 0 },
    { id: 'pieces', label: 'Pièces', count:1 },
    // { id: 'tickets', label: 'Tickets' },
  ];

  const handleEdit = () => {
    navigate(`/home/clients/${client.numero}/edit`);
  };

  const handleCreateContact = () => {
      setEditing(null);
      setIsCreateModalContactOpen(true);
    };
  
  const handleEditContact = (row: Contacts) => {
    setEditing(row);
    setIsCreateModalContactOpen(true);
  };

  const openPDF = async (row: DevisListItem) => {
    await dispatch(selectDevisAsync(row)).unwrap();
    openPreview();
  };

  const downloadPDF = async (transactionId: string) => {
    try {
      const blob = await dispatch(downloadSignedDocument(transactionId)).unwrap();
      
      const url = window.URL.createObjectURL(blob);
      
      const link = document.createElement('a');
      link.href = url;
      link.download = `document-${transactionId}.pdf`; 
      
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error('Erreur lors du téléchargement:', error);
    }
  };

  const pdfData = useMemo(() => {
    if (!devisSelected) return null;

    return {
      numero: devisSelected.numero,
      type: 'devis' as const,
      date: devisSelected.date,
      client: {
        code: devisSelected.client_code,
        nom: devisSelected.client_intitule,
        adresse: devisSelected.client_adresse,
        code_postal: devisSelected.client_code_postal,
        ville: devisSelected.client_ville,
        email: devisSelected.client_email,
        telephone: devisSelected.client_telephone,
      },
      reference_externe: devisSelected.reference,
      lignes: (devisSelected.lignes ?? []).map(l => ({
        article: l.article_code,
        designation: l.designation,
        quantite: l.quantite,
        prix_unitaire: l.prix_unitaire_ht ?? 0,
        tva: 20,
        total_ht: l.quantite * (l.prix_unitaire_ht ?? 0),
      })),
      total_ht: devisSelected.total_ht_calcule,
      total_tva: devisSelected.total_taxes_calcule,
      total_ttc: devisSelected.total_ttc_calcule,
    };
  }, [devisSelected]) as DocumentData;

  return (
    <>
      <Helmet>
        <title>{client.intitule} - Clients - Dataven</title>
        <meta name="description" content={`Fiche client ${client.intitule}`} />
      </Helmet>

      <div className="space-y-6">
        <button
          onClick={() => navigate('/home/clients')}
          className="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
        >
          <ArrowLeft className="w-4 h-4" />
          Retour aux clients
        </button>

        {/* Header */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex flex-col gap-4"
        >
          {/* Carte principale du client */}
          <div className="flex flex-row xl:flex-row xl:items-center justify-between gap-4 bg-white dark:bg-gray-950 p-6 rounded-2xl border border-gray-200 dark:border-gray-800 shadow-sm">
            <div className="flex items-start gap-4">
              <div 
                style={{ width: "7vh", height: "7vh" }} 
                className="w-16 h-16 rounded-2xl bg-[#007E45] text-white flex items-center justify-center text-2xl font-bold shadow-lg shadow-red-900/20"
              >
                {client.intitule?.split(' ').map(n => n[0]).join('').slice(0, 2)}
              </div>
              <div className="flex-1">
                <div className="flex items-center gap-3 mb-1">
                  <h1 className="text-2xl font-bold text-gray-900 dark:text-white">{client.intitule}</h1>
                  <StatusBadgetLettre status={isActive ? 'actif' : 'inactif'} />
                  <ToggleSwitch isActive={isActive} onChange={handleToggleActive} />
                </div>
                <div className="flex items-center gap-4 text-sm text-gray-500">
                  <span className="font-mono">#{client.numero}</span>
                  {client.ville && (
                    <span className="flex items-center gap-1">
                      <MapPin className="w-3.5 h-3.5" /> {client.ville}, {client.pays || 'France'}
                    </span>
                  )}
                  {client.forme_juridique && (
                    <span className="flex items-center gap-1">
                      <Building2 className="w-3.5 h-3.5" /> {client.forme_juridique}
                    </span>
                  )}
                </div>
              </div>
            </div>

            <div className="flex flex-wrap gap-2 h-10">
              <PrimaryButton_v2 icon={Edit} onClick={handleEdit}>
                Modifier
              </PrimaryButton_v2>
              <button 
                className="p-2.5 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-400" 
                title="Plus d'actions"
              >
                <MoreVertical className="w-5 h-5" />
              </button>
            </div>
          </div>

          {/* Composant de vérification des informations */}
          <ClientInfoVerifier client={client} />
        </motion.div>

        {/* Quick Actions */}
        <div className="flex gap-2 overflow-x-auto pb-2">
          <button onClick={() => navigate('/home/devis')} className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-xl text-sm font-medium hover:bg-gray-50 dark:hover:bg-gray-900 whitespace-nowrap transition-colors">
            <FileText className="w-4 h-4 text-blue-600" /> Devis
          </button>
          <button onClick={() => navigate('/home/commandes')} className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-xl text-sm font-medium hover:bg-gray-50 dark:hover:bg-gray-900 whitespace-nowrap transition-colors">
            <Package className="w-4 h-4 text-blue-600" /> Commander
          </button>
          <button onClick={() => navigate('/home/bons-livraison')} className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-xl text-sm font-medium hover:bg-gray-50 dark:hover:bg-gray-900 whitespace-nowrap transition-colors">
            <Truck className="w-4 h-4 text-orange-600" /> Livraison
          </button>
          <button onClick={() => navigate('/home/factures')} className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-xl text-sm font-medium hover:bg-gray-50 dark:hover:bg-gray-900 whitespace-nowrap transition-colors">
            <CreditCard className="w-4 h-4 text-purple-600" /> Enregistrer facture
          </button>
        </div>

        <Tabs tabs={tabs} active={activeTab} onChange={setActiveTab} />

        <div className="mt-6">
          {activeTab === 'info' && (
            <ClientDetailsGrid client={client} />
          )}

          {activeTab === 'contacts' && (
            <ClientContactsList
              contacts={client.contacts!}
              onCreateContact={handleCreateContact}
              onEditContact={handleEditContact}
              showDeleteButton={false}          
            />
          )}

          {activeTab === 'relances' && (
            <div className="space-y-6 animate-in fade-in">
              <div className="flex justify-between items-center bg-red-50 dark:bg-red-900/20 p-4 rounded-xl border border-red-100 dark:border-red-800">
                <div>
                  <h3 className="font-bold text-red-800 dark:text-red-200">Factures en retard : 0</h3>
                  <p className="text-sm text-red-600 dark:text-red-300 mt-1">
                    Montant total dû : <span className="font-bold">0 €</span>
                  </p>
                </div>
                <div className="flex gap-2">
                  <button className="px-4 py-2 bg-white text-gray-700 border border-gray-200 rounded-lg text-sm font-medium hover:bg-gray-50 transition-colors">
                    Envoyer Relevé
                  </button>
                  <PrimaryButton_v2 icon={Bell}>
                    Relancer maintenant
                  </PrimaryButton_v2>
                </div>
              </div>

              <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden">
                <table className="w-full text-sm text-left">
                  <thead className="bg-gray-50 dark:bg-gray-900 font-medium text-gray-500">
                    <tr>
                      <th className="px-6 py-3">N° Facture</th>
                      <th className="px-6 py-3">Date</th>
                      <th className="px-6 py-3">Échéance</th>
                      <th className="px-6 py-3">Montant TTC</th>
                      <th className="px-6 py-3">Reste Dû</th>
                      <th className="px-6 py-3">Retard (j)</th>
                      <th className="px-6 py-3">Dernière Relance</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                    <tr>
                      <td colSpan={7} className="px-6 py-12 text-center text-gray-500">
                        Aucune facture en retard. Bon payeur ! 🎉
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {activeTab === 'timeline' && (
            timelineEvents.length > 0 ? (
              <Timeline events={timelineEvents} />
            ) : (
              <div className="text-center py-12">
                <FileText className="w-12 h-12 text-gray-300 mx-auto mb-3" />
                <p className="text-gray-500">Aucun événement dans l'historique</p>
              </div>
            )
          )}

          {activeTab === 'documents' && (
            <div className="space-y-6">
              {/* <div className="bg-white dark:bg-gray-950 border border-dashed border-gray-200 dark:border-gray-800 rounded-2xl p-12 text-center hover:bg-gray-50 dark:hover:bg-gray-900 transition-colors cursor-pointer">
                <File className="w-12 h-12 mx-auto mb-4 text-gray-300" />
                <p className="text-gray-600 dark:text-gray-400 font-medium text-sm">
                  Glissez-déposez vos fichiers ici
                </p>
              </div> */}

              <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl overflow-hidden shadow-sm">
               <table className="w-full">
                  <thead className="bg-gray-50 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800">
                      <tr className="text-left text-xs font-semibold text-gray-500 uppercase">
                        <th className="px-6 py-3">Fichier</th>
                        <th className="px-6 py-3">Type</th>
                        <th className="px-6 py-3">Date</th>
                        <th className="px-6 py-3 text-right">Actions</th>
                      </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                      {devisSignedClient.length > 0 ? (
                        devisSignedClient.map((item) => {
                          
                          const devis = devisClient.find((dev) => dev.numero === item.sage_document_id) as DevisListItem
                          return (
                             <tr key={item.id} className="hover:bg-gray-50 dark:hover:bg-gray-900/50">
                              <td className="px-6 py-4 flex items-center gap-3 text-sm">
                                  <FileText className="w-5 h-5 text-[#007E45]" />
                                  <span className="font-medium text-gray-900 dark:text-white">
                                    DEVIS_{item.sage_document_id}
                                  </span>
                              </td>
                              <td className="px-6 py-4 text-sm text-gray-500">PDF</td>
                              <td className="px-6 py-4 text-sm text-gray-500">
                                  {formatDateFRCourt(item.created_at)}
                              </td>
                              <td className="px-6 py-4 text-right">
                                  <button 
                                    // onClick={async () => openPDF(devis)}
                                    onClick={async () => downloadPDF(item.transaction_id)}
                                    className="text-blue-600 hover:underline text-sm font-medium mr-4"
                                  >
                                    Télécharger
                                  </button>
                                  <button className="text-[#007E45] hover:text-red-700">
                                    <Trash2 className="w-4 h-4" />
                                  </button>
                              </td>
                            </tr>
                          )
                        })
                      ) : (
                        <tr>
                            <td colSpan={4} className="px-6 py-8 text-center text-sm text-gray-500">
                              Aucun document signé pour ce client
                            </td>
                        </tr>
                      )}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {activeTab === 'pieces' && (
            <div className="space-y-6">
                {/* Zone d'upload */}
                <div className="relative">
                  <input
                      type="file"
                      multiple
                      accept=".pdf,.doc,.docx,.xls,.xlsx,.png,.jpg,.jpeg"
                      onChange={(e) => console.log(e.target.files)}
                      className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"
                  />
                  <div className="border-2 border-dashed border-gray-300 dark:border-gray-700 rounded-2xl p-8 text-center hover:border-[#007E45] hover:bg-green-50/50 dark:hover:bg-green-900/10 transition-all duration-300">
                      <div className="flex flex-col items-center gap-4">
                        <div className="p-4 bg-green-100 dark:bg-green-900/30 rounded-full">
                            <Upload className="w-8 h-8 text-[#007E45]" />
                        </div>
                        <div>
                            <p className="text-base font-semibold text-gray-900 dark:text-white">
                              Glissez-déposez vos fichiers ici
                            </p>
                            <p className="text-sm text-gray-500 mt-1">
                              ou <span className="text-[#007E45] font-medium hover:underline">parcourir</span> depuis votre ordinateur
                            </p>
                        </div>
                        <div className="flex flex-wrap justify-center gap-2 mt-2">
                            <span className="px-2 py-1 bg-gray-100 dark:bg-gray-800 rounded text-xs text-gray-500">PDF</span>
                            <span className="px-2 py-1 bg-gray-100 dark:bg-gray-800 rounded text-xs text-gray-500">DOC</span>
                            <span className="px-2 py-1 bg-gray-100 dark:bg-gray-800 rounded text-xs text-gray-500">XLS</span>
                            <span className="px-2 py-1 bg-gray-100 dark:bg-gray-800 rounded text-xs text-gray-500">PNG</span>
                            <span className="px-2 py-1 bg-gray-100 dark:bg-gray-800 rounded text-xs text-gray-500">JPG</span>
                        </div>
                        <p className="text-xs text-gray-400">Taille max: 10 Mo par fichier</p>
                      </div>
                  </div>
                </div>

                {/* Liste des fichiers */}
                <div className="bg-white dark:bg-gray-950 rounded-2xl border border-gray-200 dark:border-gray-800 overflow-hidden">
                  <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-800 flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <Paperclip className="w-5 h-5 text-gray-400" />
                        <h3 className="font-semibold text-gray-900 dark:text-white">Pièces jointes</h3>
                        <span className="px-2 py-0.5 bg-gray-100 dark:bg-gray-800 rounded-full text-xs text-gray-500">
                            0 fichier
                        </span>
                      </div>
                      <button className="text-sm text-[#007E45] font-medium hover:underline flex items-center gap-1">
                        <Plus className="w-4 h-4" />
                        Ajouter
                      </button>
                  </div>
                </div>

                {/* Résumé stockage */}
                <div className="bg-gray-50 dark:bg-gray-900/50 rounded-xl p-4 flex items-center justify-between">
                  <div className="flex items-center gap-3">
                      <HardDrive className="w-5 h-5 text-gray-400" />
                      <div>
                        <p className="text-sm font-medium text-gray-900 dark:text-white">Espace utilisé</p>
                        <p className="text-xs text-gray-500">4.5 Mo sur 50 Mo disponibles</p>
                      </div>
                  </div>
                  <div className="w-32 h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                      <div className="h-full bg-[#007E45] rounded-full" style={{ width: '9%' }} />
                  </div>
                </div>
            </div>
          )}

          <PDFPreview open={showPreview} onClose={closePreview} data={pdfData} entreprise={CompanyInfo} />

        </div>
      </div>

      {isLoading && <ModalLoading />}

      <ModalQuote
        open={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        title={"Créer un devis"}
        client={client}
      />

      <ModalContact
        open={isCreateModalContactOpen}
        onClose={() => setIsCreateModalContactOpen(false)}
        title={editing ? `Mettre à jour le contact ${editing.nom}` : 'Créer un contact'}
        editing={editing}
        entityType='client'
      />
    </>
  );
};

export default ClientDetailPage;