import React, { useState, useMemo, useEffect } from "react";
import { Helmet } from "react-helmet";
import { useNavigate } from "react-router-dom";
import {
   FileText,
   ShoppingCart,
} from "lucide-react";
import { toast } from "@/components/ui/use-toast";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
   getDevisSelected,
} from "@/store/features/devis/selectors";
import { DevisListItem } from "@/types/devisType";
import {
   changerStatutDevis,
   devisToCommande,
   devisToFacture,
   getDevisById,
   updateDevis,
} from "@/store/features/devis/thunk";
import { getCommande } from "@/store/features/commande/thunk";
import FormModal from "@/components/ui/FormModal";
import { usePDFPreview } from "@/components/modal/ModalPDFPreview";
import { ModalLoading } from "@/components/modal/ModalLoading";
import { cn } from "@/lib/utils";
import { getFacture } from "@/store/features/factures/thunk";
import ModalSendSignatureRequest from "@/components/modal/ModalSendSignatureRequest";
import { sageService } from "@/service/sageService";
import { getAllClients } from "@/store/features/client/selectors";
import { Client } from "@/types/clientType";
import { Article } from "@/types/articleType";
import SignatureWorkflow from "@/components/indicators/SignatureWorkflow";
import { Commande } from "@/types/commandeTypes";
import { selectClient } from "@/store/features/client/slice";
import { selectcommande } from "@/store/features/commande/slice";
import { selectfacture } from "@/store/features/factures/slice";
import { selectDevis } from "@/store/features/devis/slice";
import { Facture } from "@/types/factureType";
import { ModalStatus } from "@/components/modal/ModalStatus";
import StickyTotals from "@/components/document-entry/StickyTotals";
import { ModalArticle } from "@/components/modal/ModalArticle";
import PDFPreviewPanel from "@/components/panels/PDFPreviewPanel";
import { useDisplayMode } from "@/context/DisplayModeContext";
import { getUniversigns } from "@/store/features/universign/thunk";
import { UniversignType } from "@/types/sageTypes";
import { getAlluniversign } from "@/store/features/universign/selectors";
import DevisContent from "@/components/page/devis/DevisContent";
import { TransformOption } from "@/components/page/devis/TransformOption";
import DevisHeader from "@/components/page/devis/DevisHeader";
import { getuserConnected } from "@/store/features/user/selectors";
import { UserInterface } from "@/types/userInterface";

// Interface mise à jour avec id et isManual
export interface LigneForm {
   id: string;
   article_code: string;
   quantite: number;
   prix_unitaire_ht: number;
   total_taxes: number;
   taux_taxe1: number;
   montant_ligne_ht: number;
   remise_pourcentage: number;
   designation: string;
   articles: Article | null;
   isManual: boolean;
}

export interface Note {
   publique: string;
   prive: string;
}

// Générer un ID unique
const generateLineId = () =>
   `line_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

const QuoteDetailPage = () => {
   const navigate = useNavigate();
   const dispatch = useAppDispatch();
   const clients = useAppSelector(getAllClients) as Client[];
   const universign = useAppSelector(getAlluniversign) as UniversignType[];
   const devis = useAppSelector(getDevisSelected) as DevisListItem;
   const userConnected = useAppSelector(getuserConnected) as UserInterface

   // États pour transformation
   const [isTransformOpen, setIsTransformOpen] = useState(false);
   const [loadingTransform, setLoadingTransform] = useState(false);

   // États UI
   const {
      openPreview,
      closePreview,
      isOpen,
      pdfUrl,
      fileName,
      PDFPreviewModal,
   } = usePDFPreview();
   const [openStatusDevis, setOpenStatusDevis] = useState(false);
   const [isSendSignatureModalOpen, setIsSendSignatureModalOpen] =
      useState(false);

   // États pour le modal article
   const [isArticleModalOpen, setIsArticleModalOpen] = useState(false);
   const [currentLineId, setCurrentLineId] = useState<string | null>(null);

   // États pour l'édition inline
   const [isEditing, setIsEditing] = useState(false);
   const [isSaving, setIsSaving] = useState(false);
   const [error, setError] = useState<string | null>(null);

   // États des champs éditables
   const [editDateEmission, setEditDateEmission] = useState("");
   const [editDateLivraison, setEditDateLivraison] = useState("");
   const [editReference, setEditReference] = useState("");
   const [editClient, setEditClient] = useState<Client | null>(null);
   const [editLignes, setEditLignes] = useState<LigneForm[]>([]);

   const { isPdfPreviewVisible, togglePdfPreview } = useDisplayMode();

   
   const editNotLignes: LigneForm[] = devis.lignes.map((line, index) => ({
      id: `${index}`, // ou line.article_code si unique
      article_code: line.article_code,
      quantite: line.quantite,
      prix_unitaire_ht: line.prix_unitaire_ht ?? 0,
      total_taxes: line.total_taxes,
      taux_taxe1: line.taux_taxe1,
      montant_ligne_ht: line.montant_ligne_ht ?? 0,
      designation: line.designation ?? "",
      remise_pourcentage: line.remise_pourcentage ?? 0,
      articles: null, // à remplir si tu veux relier un Article complet
      isManual: false, // par défaut false
   }));

   // Initialiser les valeurs d'édition
   useEffect(() => {
      if (devis && isEditing) {
         setEditDateEmission(devis.date || "");
         setEditDateLivraison(devis.date_livraison || "");
         setEditReference(devis.reference || "");

         const clientFound = clients.find((c) => c.numero === devis.client_code);
         setEditClient(
            clientFound ||
            ({
               numero: devis.client_code,
               intitule: devis.client_intitule,
               compte_collectif: "",
               adresse: "",
               code_postal: "",
               ville: "",
               email: "",
               telephone: "",
            } as Client)
         );

         const lignesInitiales: LigneForm[] =
            devis.lignes?.map((ligne) => ({
               id: generateLineId(),
               article_code: ligne.article_code,
               quantite: ligne.quantite,
               prix_unitaire_ht: ligne.prix_unitaire_ht ?? 0,
               designation: ligne.designation ?? "",
               remise_pourcentage: ligne.remise_valeur1 ?? 0,
               total_taxes: ligne.total_taxes ?? 0,
               taux_taxe1: ligne.taux_taxe1 ?? 0,
               montant_ligne_ht: ligne.montant_ligne_ht ?? 0,
               articles: ligne.article_code
                  ? ({
                     reference: ligne.article_code,
                     designation: ligne.designation ?? "",
                     prix_vente: ligne.prix_unitaire_ht ?? 0,
                     stock_reel: 0,
                  } as Article)
                  : null,
               isManual: !ligne.article_code,
            })) ?? [];

         setEditLignes(
            lignesInitiales.length > 0
               ? lignesInitiales
               : [
                  {
                     id: generateLineId(),
                     article_code: "",
                     quantite: 1,
                     prix_unitaire_ht: 0,
                     total_taxes: 0,
                     taux_taxe1: 0,
                     montant_ligne_ht: 0,
                     remise_pourcentage: 0,
                     designation: "",
                     articles: null,
                     isManual: false,
                  },
               ]
         );
      }
   }, [devis, isEditing, clients]);

   if (!devis) return <div>Devis introuvable</div>;

   const client = clients.find(
      (item: Client) => item.numero === devis.client_code
   ) as Client;

   const devisSigned = useMemo(() => {
      if (!universign || !devis?.numero) return null;

      const idx = universign.findIndex(
         (item) => item.sage_document_id === devis.numero
      );
      return idx !== -1 ? universign[idx] : null;
   }, [universign, devis?.numero]);

   useEffect(() => {
      const updateStatut = async () => {
         if (devisSigned?.local_status === "SIGNE") {
            const payload = {
               numero: devis.numero,
               status: 2,
            };

            try {
               if (devis.statut === 1)
                  await dispatch(changerStatutDevis(payload)).unwrap();
            } catch (error) {
               console.error("Erreur lors du changement de statut:", error);
            }
         }
      };

      updateStatut();
   }, [devisSigned?.local_status, devis.numero, dispatch]);

   const calculerTotalLigne = (ligne: LigneForm) => {
      const prix = ligne.prix_unitaire_ht || ligne.articles?.prix_vente || 0;
      const remise = ligne.remise_pourcentage ?? 0;
      const prixRemise = prix * (1 - remise / 100);
      return prixRemise * ligne.quantite;
   };

   const calculerTotalTva = () => {
      const taxesParLignes = editLignes.reduce((total, ligne) => {
         const totalHtLigne = calculerTotalLigne(ligne);
         const tva = totalHtLigne * (ligne.taux_taxe1 / 100);
         return total + tva;
      }, 0);

      const valeur_frais = devis.valeur_frais;
      return taxesParLignes + valeur_frais * (devis.taxes1 ?? 0.2);
   };

   const calculerTotalHT = () => {
      const total_ligne = editLignes.map((ligne) => calculerTotalLigne(ligne));
      const totalHTLigne = total_ligne.reduce((acc, ligne) => acc + ligne, 0);
      const totalHtNet = totalHTLigne + devis.valeur_frais;
      return totalHtNet;
   };

   const editTotalHT = calculerTotalHT();
   const editTotalTVA = calculerTotalTva();
   const editTotalTTC = editTotalHT + editTotalTVA;

   const [description, setDescription] = useState<string | null>(null);
   const [activeLineId, setActiveLineId] = useState<string | null>(null);

   const [note, setNote] = useState<Note>({
      publique: "Offre valable 30 jours",
      prive: "",
   });

   // Toggle mode Article/Libre
   const toggleLineMode = (lineId: string) => {
      setEditLignes((prev) =>
         prev.map((ligne) => {
            if (ligne.id === lineId) {
               const newIsManual = !ligne.isManual;
               return {
                  ...ligne,
                  isManual: newIsManual,
                  article_code: newIsManual ? "" : ligne.article_code,
                  articles: newIsManual ? null : ligne.articles,
                  designation: "",
                  prix_unitaire_ht: newIsManual ? 0 : ligne.prix_unitaire_ht,
               };
            }
            return ligne;
         })
      );
   };

   // Gestion des lignes
   const ajouterLigne = () => {
      setEditLignes([
         ...editLignes,
         {
            id: generateLineId(),
            article_code: "",
            quantite: 1,
            prix_unitaire_ht: 0,
            total_taxes: 0,
            taux_taxe1: 0,
            montant_ligne_ht: 0,
            remise_pourcentage: 0,
            designation: "",
            articles: null,
            isManual: false,
         },
      ]);
   };

   const supprimerLigne = (lineId: string) => {
      if (editLignes.length > 1) {
         setEditLignes(editLignes.filter((l) => l.id !== lineId));
      }
   };

   const updateLigne = (lineId: string, field: keyof LigneForm, value: any) => {
      setEditLignes((prev) =>
         prev.map((ligne) => {
            if (ligne.id !== lineId) return ligne;

            if (field === "articles" && value) {
               const article = value as Article;
               return {
                  ...ligne,
                  articles: article,
                  article_code: article.reference,
                  designation: article.designation,
                  prix_unitaire_ht: article.prix_vente,
               };
            } else if (field === "articles" && !value) {
               return {
                  ...ligne,
                  articles: null,
                  article_code: "",
                  designation: "",
                  prix_unitaire_ht: 0,
               };
            } else {
               return { ...ligne, [field]: value };
            }
         })
      );
   };

   // Validation - accepte aussi les lignes manuelles avec désignation
   const canSave = useMemo(() => {
      if (!editClient) return false;
      const lignesValides = editLignes.filter(
         (l) => l.article_code || (l.isManual && l.designation)
      );
      return lignesValides.length > 0;
   }, [editClient, editLignes]);

   // Gestion de l'édition
   const handleStartEdit = () => setIsEditing(true);
   const handleCancelEdit = () => {
      setIsEditing(false);
      setError(null);
   };

   const handleSaveEdit = async () => {
      if (!editClient) {
         setError("Veuillez sélectionner un client");
         return;
      }

      const lignesValides = editLignes.filter(
         (l) => l.article_code || (l.isManual && l.designation)
      );
      if (lignesValides.length === 0) {
         setError("Veuillez ajouter au moins un article ou une ligne");
         return;
      }

      try {
         setIsSaving(true);
         setError(null);

         const payloadUpdate = {
            client_id: editClient.numero,
            date_devis: editDateEmission,
            date_livraison: editDateLivraison,
            reference: editReference,
            lignes: lignesValides.map((l) => ({
               article_code: l.article_code || "DIVERS",
               quantite: l.quantite,
               remise_pourcentage: l.remise_pourcentage,
            })),
         };

         await dispatch(
            updateDevis({ numero: devis.numero, data: payloadUpdate })
         ).unwrap();

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

         const devisUpdated = (await dispatch(
            getDevisById(devis.numero)
         ).unwrap()) as any;
         dispatch(selectDevis(devisUpdated.data as DevisListItem));
         setIsEditing(false);
      } catch (err: any) {
         setError(err.message || "Erreur lors de la mise à jour");
         toast({
            title: "Erreur",
            description: "Impossible de mettre à jour le devis.",
            className: "bg-red-500 text-white border-red-600",
         });
      } finally {
         setIsSaving(false);
      }
   };

   // Handlers transformation
   const handleTransform = async () => {
      setIsTransformOpen(false);
      try {
         setLoadingTransform(true);
         const response = await dispatch(devisToCommande(devis!.numero)).unwrap();
         const res = (await dispatch(
            getCommande(response.document_cible)
         ).unwrap()) as Commande;
         dispatch(selectcommande(res));
         setLoadingTransform(false);
         toast({
            title: "Commande créée !",
            description: `Le devis ${devis.numero} a été transformé en commande.`,
            className: "bg-green-500 text-white border-green-600",
         });
         setTimeout(() => navigate(`/home/commandes/${res.numero}`), 1000);
      } catch (err: any) {
         setLoadingTransform(false);
         toast({
            title: "Transformation échouée !",
            description: `Le devis ${devis.numero} ne peut pas être transformé en commande.`,
            className: "bg-red-500 text-white border-red-600",
         });
      }
   };

   const handleTransformToFacture = async () => {
      setIsTransformOpen(false);
      try {
         setLoadingTransform(true);
         const response = await dispatch(devisToFacture(devis!.numero)).unwrap();
         const res = (await dispatch(
            getFacture(response.document_cible)
         ).unwrap()) as Facture;
         dispatch(selectfacture(res));
         setLoadingTransform(false);
         toast({
            title: "Facture créée !",
            description: `Le devis ${devis.numero} a été transformé en facture.`,
            className: "bg-green-500 text-white border-green-600",
         });
         setTimeout(() => navigate(`/home/factures/${res.numero}`), 1000);
      } catch (err: any) {
         setLoadingTransform(false);
         toast({
            title: "Transformation échouée !",
            description: `Le devis ${devis.numero} ne peut pas être transformé en facture.`,
            className: "bg-red-500 text-white border-red-600",
         });
      }
   };

   const handleSendSignatureRequest = async (data: {
      emailSignataire: string;
      nomSignataire: string;
   }) => {
      try {
         setLoadingTransform(true);
         const a = await sageService.envoyerDevisSignature(
            devis.numero,
            data.emailSignataire,
            data.nomSignataire
         );
         console.log("signed : ", a);
         await dispatch(getUniversigns()).unwrap();

         const payload = {
            numero: devis.numero,
            status: 1,
         };
         await dispatch(changerStatutDevis(payload)).unwrap();
         toast({
            title: "Devis envoyé !",
            description: `Demande de signature envoyée avec succès`,
            className: "bg-green-500 text-white border-green-600",
         });
         setIsSendSignatureModalOpen(false);
      } catch (error) {
         // toast({ title: "Erreur !", description: `Demande de signature refusée`, className: "bg-red-500 text-white border-red-600" });
         await dispatch(getUniversigns()).unwrap();
         const payload = {
            numero: devis.numero,
            status: 1,
         };
         await dispatch(changerStatutDevis(payload)).unwrap();
         toast({
            title: "Devis envoyé !",
            description: `Demande de signature envoyée avec succès`,
            className: "bg-green-500 text-white border-green-600",
         });
         setIsSendSignatureModalOpen(false);
      } finally {
         setLoadingTransform(false);
      }
   };

   return (
      <>
         <Helmet>
            <title>{devis.numero} - Devis</title>
         </Helmet>

          <div className={`flex flex-col  overflow-hidden h-[80vh]`}>
            {/* TOP HEADER */}
            <div className="flex-none">
                <DevisHeader
                  // Données
                  devis={devis}
                  client={client}
                  devisSigned={devisSigned}

                  userConnected={userConnected}
                  
                  // États d'édition
                  isEditing={isEditing}
                  isSaving={isSaving}
                  canSave={canSave}
                  
                  // Champs éditables
                  editClient={editClient}
                  editDateEmission={editDateEmission}
                  editDateLivraison={editDateLivraison}
                  editReference={editReference}
                  
                  // États UI
                  isPdfPreviewVisible={isPdfPreviewVisible}
                  
                  // Handlers d'édition
                  onSetEditClient={setEditClient}
                  onSetEditDateEmission={setEditDateEmission}
                  onSetEditDateLivraison={setEditDateLivraison}
                  onSetEditReference={setEditReference}
                  
                  // Handlers d'actions
                  onStartEdit={handleStartEdit}
                  onCancelEdit={handleCancelEdit}
                  onSaveEdit={handleSaveEdit}
                  onTogglePdfPreview={togglePdfPreview}
                  onOpenStatusModal={() => setOpenStatusDevis(true)}
                  onOpenSignatureModal={() => setIsSendSignatureModalOpen(true)}
                  onOpenTransformModal={() => setIsTransformOpen(true)}
                  onNavigateToClient={(clientCode) => {
                     const clientSelected = clients.find((item: Client) => item.numero === clientCode);
                     if (clientSelected) {
                        dispatch(selectClient(clientSelected));
                        navigate(`/home/clients/${clientCode}`);
                     }
                  }}
               />
            </div>
           

            <div className="flex overflow-hidden">
               {/* Left/Center Panel - Form/Table */}
               <div
                  className={cn(
                     "flex relative flex-col flex-1 min-w-0 transition-all duration-300",
                     isPdfPreviewVisible
                        ? "w-1/2 border-r border-gray-200 dark:border-gray-800"
                        : "w-full"
                  )}
               >
                  {/* Signature Workflow */}
                  {!isEditing && (
                     <div className="w-3xl">
                        <SignatureWorkflow
                           status={
                              devisSigned?.local_status === "SIGNE"
                                 ? "Signé"
                                 : devis.statut === 2
                                    ? "Accepté"
                                    : "Vu"
                           }
                        />
                     </div>
                  )}
                  {/* Content */}
                  <DevisContent
                     // Données
                     devis={devis}
                     editLignes={editLignes}
                     note={note}
                     
                     // États
                     isEditing={isEditing}
                     isPdfPreviewVisible={isPdfPreviewVisible}
                     activeLineId={activeLineId}
                     description={description}
                     error={error}
                     
                     // Totaux
                     editTotalHT={editTotalHT}
                     editTotalTVA={editTotalTVA}
                     editTotalTTC={editTotalTTC}
                     
                     // Handlers
                     onToggleLineMode={toggleLineMode}
                     onUpdateLigne={updateLigne}
                     onAjouterLigne={ajouterLigne}
                     onSupprimerLigne={supprimerLigne}
                     onSetActiveLineId={setActiveLineId}
                     onSetDescription={setDescription}
                     onSetNote={setNote}
                     onOpenArticleModal={(lineId) => {
                        setCurrentLineId(lineId);
                        setIsArticleModalOpen(true);
                     }}
                     
                     calculerTotalLigne={calculerTotalLigne}
                  />
               </div>

               {/* Right Panel - Live PDF Preview */}
               {isPdfPreviewVisible && (
                  <div className="w-[45%] hidden lg:block bg-[#525659] shadow-inner relative z-10 animate-in slide-in-from-right duration-300">
                     {/* <PDFPreviewPanel
                        isOpen={true}
                        variant="inline"
                        devis={devis}
                        notes={note}
                        data={isEditing ? editLignes : editNotLignes}
                        total_ht={isEditing ? editTotalHT : devis.total_ht_calcule}
                        total_taxes_calcule={
                           isEditing ? editTotalTVA : devis.total_taxes_calcule
                        }
                        total_ttc_calcule={
                           isEditing ? editTotalTTC : devis.total_ttc_calcule
                        }
                        onClose={togglePdfPreview}
                        isEdit={isEditing}
                     /> */}
                     <PDFPreviewPanel
                        isOpen={true}
                        onClose={() => {}}
                        documentType="devis"
                        document={devis}
                        data={isEditing ? editLignes : editNotLignes}
                        notes={note}
                        total_ht={isEditing ? editTotalHT : devis.total_ht_calcule}
                        total_taxes_calcule={
                           isEditing ? editTotalTVA : devis.total_taxes_calcule
                        }
                        total_ttc_calcule={
                           isEditing ? editTotalTTC : devis.total_ttc_calcule
                        }
                        variant="inline"
                        isEdit={isEditing}
                     />
                  </div>
               )}
            </div>
         </div>

         {/* Modals */}
         <FormModal
            isOpen={isTransformOpen}
            onClose={() => setIsTransformOpen(false)}
            title="Transformer le devis"
         >
            <div className="p-6 space-y-4">
               <TransformOption
                  icon={ShoppingCart}
                  title="Transformer en Commande"
                  description="Crée un bon de commande client basé sur ce devis."
                  colorClass="bg-blue-500"
                  onClick={handleTransform}
               />
               <TransformOption
                  icon={FileText}
                  title="Transformer en Facture"
                  description="Crée une facture directe sans passer par la commande."
                  colorClass="bg-purple-500"
                  onClick={handleTransformToFacture}
               />
            </div>
         </FormModal>

         <PDFPreviewModal
            isOpen={isOpen}
            onClose={closePreview}
            pdfUrl={pdfUrl}
            fileName={fileName}
         />
         <ModalSendSignatureRequest
            isOpen={isSendSignatureModalOpen}
            onClose={() => setIsSendSignatureModalOpen(false)}
            client={client}
            quote={devis}
            onConfirm={handleSendSignatureRequest}
         />
         <ModalStatus
            open={openStatusDevis}
            onClose={() => setOpenStatusDevis(false)}
            type_doc={0}
         />

         {/* Modal création article */}
         <ModalArticle
            open={isArticleModalOpen}
            onClose={() => {
               setIsArticleModalOpen(false);
            }}
         />

         {(loadingTransform || isSaving) && <ModalLoading />}
      </>
   );
};

export default QuoteDetailPage;

