import React, { useState, useMemo, useEffect } from "react";
import { Helmet } from "react-helmet";
import { useNavigate } from "react-router-dom";
import { toast } from "@/components/ui/use-toast";
import { cn } from "@/lib/utils";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { getfactureSelected } from "@/store/features/factures/selectors";
import { Facture } from "@/types/factureType";
import { getAllClients } from "@/store/features/client/selectors";
import { Client } from "@/types/clientType";
import { Article } from "@/types/articleType";
import { selectClient } from "@/store/features/client/slice";
import { ModalAvoir } from "@/components/modal/ModalAvoir";
import ModalStatus from "@/components/modal/ModalStatus";
import { getFacture, updateFacture, validerFacture } from "@/store/features/factures/thunk";
import { selectfacture } from "@/store/features/factures/slice";
import { ModalLoading } from "@/components/modal/ModalLoading";
import { ModalArticle } from "@/components/modal/ModalArticle";
import PDFPreviewPanel from "@/components/panels/PDFPreviewPanel";
import { useDisplayMode } from "@/context/DisplayModeContext";
import FactureContent, { LigneForm, Note } from "@/components/page/facture/FactureContent";
import FactureHeader from "@/components/page/facture/FactureHeader";
import { UserInterface } from "@/types/userInterface";
import { getuserConnected } from "@/store/features/user/selectors";
import { CheckCircle, Lock } from "lucide-react";
import FormModal from "@/components/ui/FormModal";
import { ValiderFacture } from "@/components/page/facture/ValiderFacture";

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

const InvoiceDetailPage = () => {
   const navigate = useNavigate();
   const dispatch = useAppDispatch();
   const clients = useAppSelector(getAllClients) as Client[];
   const facture = useAppSelector(getfactureSelected) as Facture;

   // États UI
   const [openStatus, setOpenStatus] = useState(false);
   const [isCreateAvoir, setIsCreateAvoir] = useState(false);
   const [isArticleModalOpen, setIsArticleModalOpen] = useState(false);
   const [isValid, setIsValid] = useState(false)
   const [currentLineId, setCurrentLineId] = useState<string | null>(null);
   const userConnected = useAppSelector(getuserConnected) as UserInterface

   // É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 [editDateFacture, setEditDateFacture] = 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 [description, setDescription] = useState<string | null>(null);
   const [activeLineId, setActiveLineId] = useState<string | null>(null);

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

   const editNotLignes: LigneForm[] = facture?.lignes?.map((line, index) => ({
      id: `${index}`,
      article_code: line.article_code,
      quantite: line.quantite,
      prix_unitaire_ht: line.prix_unitaire_ht ?? 0,
      total_taxes: line.total_taxes ?? 0,
      taux_taxe1: line.taux_taxe1 ?? 0,
      montant_ligne_ht: line.montant_ligne_ht ?? 0,
      designation: line.designation ?? "",
      remise_pourcentage: line.remise_pourcentage ?? 0,
      articles: null,
      isManual: false,
   })) || [];

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

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

         const lignesInitiales: LigneForm[] =
            facture.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,
                  },
               ]
         );
      }
   }, [facture, isEditing, clients]);

   if (!facture)
      return <div className="p-8 text-center">Facture introuvable</div>;

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

   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 = facture.valeur_frais;
      return taxesParLignes + valeur_frais * (facture.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 + facture.valeur_frais;
      return totalHtNet;
   };

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

   // 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
   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_facture: editDateFacture,
            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(
            updateFacture({ numero: facture.numero, data: payloadUpdate })
         ).unwrap();

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

         const itemUpdated = (await dispatch(
            getFacture(facture.numero)
         ).unwrap()) as Facture;
         dispatch(selectfacture(itemUpdated));
         setIsEditing(false);
      } catch (err: any) {
         setError(err.message || "Erreur lors de la mise à jour");
         toast({
            title: "Erreur",
            description: "Impossible de mettre à jour la facture.",
            className: "bg-red-500 text-white border-red-600",
         });
      } finally {
         setIsSaving(false);
      }
   };


   const handleValiderFacture = async () => {
      try {
         setIsSaving(true);
         setError(null);
         await dispatch(validerFacture(facture.numero)).unwrap();

         toast({
            title: "Facture validé !",
            description: `La facture ${facture.numero} a été bien validé avec succès.`,
            className: "bg-green-500 text-white border-green-600",
         });

         const itemUpdated = (await dispatch(
            getFacture(facture.numero)
         ).unwrap()) as Facture;
         dispatch(selectfacture(itemUpdated));
         setIsEditing(false);
         setIsValid(false)
      } catch (err: any) {
         setError(err.message || "Erreur lors de la validation du facture");
         toast({
            title: "Erreur",
            description: "Impossible de mettre à jour la facture.",
            className: "bg-red-500 text-white border-red-600",
         });
      } finally {
         setIsSaving(false);
      }
   };

   const handleCreateAvoir = () => {
      setIsCreateAvoir(true);
   };

   return (
       <>
         <Helmet>
            <title>{facture.numero} - Facture</title>
         </Helmet>

         {/* Structure principale avec h-screen */}
         <div className="flex flex-col h-[80vh] overflow-hidden">
            {/* TOP HEADER - Reste fixe */}
            <div className="flex-none">
               <FactureHeader
                  // ... tous les props
                  userConnected={userConnected}
                  facture={facture}
                  client={client}
                  isEditing={isEditing}
                  isSaving={isSaving}
                  canSave={canSave}
                  editClient={editClient}
                  editDateFacture={editDateFacture}
                  editDateLivraison={editDateLivraison}
                  editReference={editReference}
                  isPdfPreviewVisible={isPdfPreviewVisible}
                  setIsValid={setIsValid}
                  onSetEditClient={setEditClient}
                  onSetEditDateFacture={setEditDateFacture}
                  onSetEditDateLivraison={setEditDateLivraison}
                  onSetEditReference={setEditReference}
                  onStartEdit={handleStartEdit}
                  onCancelEdit={handleCancelEdit}
                  onSaveEdit={handleSaveEdit}
                  onTogglePdfPreview={togglePdfPreview}
                  onOpenStatusModal={() => setOpenStatus(true)}
                  onOpenCreateAvoir={handleCreateAvoir}
                  onNavigateToClient={(clientCode) => {
                     const clientSelected = clients.find(
                        (item: Client) => item.numero === clientCode
                     );
                     if (clientSelected) {
                        dispatch(selectClient(clientSelected));
                        navigate(`/home/clients/${clientCode}`);
                     }
                  }}
               />
            </div>
            
            {/* LOCKED BANNER */}
            {facture.valide === 1 && (
                  <div className="bg-blue-50 dark:bg-blue-900/20 border-b border-blue-100 dark:border-blue-800 px-4 py-3 text-center">
                     <p className="text-sm text-blue-800 dark:text-blue-200 font-medium flex items-center justify-center gap-2">
                        <Lock className="w-4 h-4" />
                        Cette facture est validée et n'est plus modifiable.
                     </p>
                  </div>
            )} 
            {/* Zone de contenu avec scroll */}
            <div className="flex flex-1 overflow-hidden">
               {/* Left/Center Panel - Form/Table */}
               <div
                  className={cn(
                     "flex 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"
                  )}
               >
                  {/* Content avec scroll */}
                  <FactureContent
                     facture={facture}
                     editLignes={editLignes}
                     note={note}
                     isEditing={isEditing}
                     isPdfPreviewVisible={isPdfPreviewVisible}
                     activeLineId={activeLineId}
                     description={description}
                     error={error}
                     editTotalHT={editTotalHT}
                     editTotalTVA={editTotalTVA}
                     editTotalTTC={editTotalTTC}
                     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"
                        documentType="facture"
                        document={facture}
                        notes={note}
                        data={isEditing ? editLignes : editNotLignes}
                        total_ht={isEditing ? editTotalHT : facture.total_ht_calcule}
                        total_taxes_calcule={
                           isEditing ? editTotalTVA : facture.total_taxes_calcule
                        }
                        total_ttc_calcule={
                           isEditing ? editTotalTTC : facture.total_ttc_calcule
                        }
                        onClose={togglePdfPreview}
                        isEdit={isEditing}
                     />
                  </div>
               )}
            </div>
         </div>

         {/* Modals */}
         <ModalStatus
            open={openStatus}
            onClose={() => setOpenStatus(false)}
            type_doc={60}
         />

         <ModalAvoir
            open={isCreateAvoir}
            onClose={() => setIsCreateAvoir(false)}
            title="Créer un avoir"
            editing={null}
         />

         <ModalArticle
            open={isArticleModalOpen}
            onClose={() => {
               setIsArticleModalOpen(false);
            }}
         />

         <FormModal
            isOpen={isValid}
            onClose={() => setIsValid(false)}
            title="Validé la facture"
         >
            <div className="p-6 space-y-4">
               <ValiderFacture
                  icon={CheckCircle}
                  title="Validé la facture"
                  description="Valide la facture afin de permettre son règlement et la création éventuelle d’un avoir."
                  colorClass="bg-blue-500"
                  onClick={handleValiderFacture}
               />
            </div>
         </FormModal>

         {isSaving && <ModalLoading />}
      </>
      
   );
};

export default InvoiceDetailPage;
