import { useEffect, useState, useMemo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { X, ArrowRight, Save, ShieldAlert, History } from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { changerStatutDevis } from "@/store/features/devis/thunk";
import { changerStatutCommande } from "@/store/features/commande/thunk";
import { DevisListItem } from "@/types/devisType";
import { toast } from "../ui/use-toast";
import { useNavigate } from "react-router-dom";
import { SageDocumentType, StatusRequest } from "@/types/sageTypes";
import { devisStatus, getDevisSelected } from "@/store/features/devis/selectors";
import { commandeStatus, getcommandeSelected } from "@/store/features/commande/selectors";
import { Commande } from "@/types/commandeTypes";
import { factureStatus, getfactureSelected } from "@/store/features/factures/selectors";
import { Facture } from "@/types/factureType";
import { BL } from "@/types/BL_Types";
import { BLStatus, getBLSelected } from "@/store/features/bl/selectors";
import { avoirStatus, getavoirSelected } from "@/store/features/avoir/selectors";
import { Avoir } from "@/types/avoirType";
import StatusBadge from "../ui/StatusBadge";
import { changerStatutBL } from "@/store/features/bl/thunk";
import { changerStatutFacture } from "@/store/features/factures/thunk";
import { cn } from "@/lib/utils";

// ============================================
// CONFIGURATION DES STATUTS PAR TYPE DE DOCUMENT
// ============================================

interface StatusOption {
  value: number;
  label: string;
}

const STATUS_OPTIONS: Record<SageDocumentType, StatusOption[]> = {
  [SageDocumentType.DEVIS]: [
    { value: 0, label: "Saisi" },
    { value: 1, label: "Confirmé" },
    { value: 2, label: "Accepté" },
    { value: 3, label: "Perdu" },
    { value: 4, label: "Archivé" },
  ],
  [SageDocumentType.BON_COMMANDE]: [
    { value: 0, label: "Saisi" },
    { value: 1, label: "Confirmé" },
    { value: 2, label: "A préparer" },
  ],
  [SageDocumentType.PREPARATION]: [
    { value: 0, label: "Saisi" },
    { value: 1, label: "Confirmé" },
  ],
  [SageDocumentType.BON_LIVRAISON]: [
    { value: 0, label: "Saisi" },
    { value: 1, label: "Confirmé" },
    { value: 2, label: "A Facturer" },
  ],
  [SageDocumentType.BON_RETOUR]: [
    { value: 0, label: "Saisi" },
    { value: 1, label: "Confirmé" },
  ],
  [SageDocumentType.BON_AVOIR]: [
    { value: 0, label: "Saisi" },
    { value: 1, label: "Confirmé" },
    { value: 2, label: "A Facturer" },
  ],
  [SageDocumentType.FACTURE]: [
    { value: 0, label: "Saisi" },
    { value: 1, label: "Confirmé" },
    { value: 2, label: "A comptabiliser" },
  ],
};

const DOCUMENT_LABELS: Record<SageDocumentType, string> = {
  [SageDocumentType.DEVIS]: "Devis",
  [SageDocumentType.BON_COMMANDE]: "Bon de commande",
  [SageDocumentType.PREPARATION]: "Préparation",
  [SageDocumentType.BON_LIVRAISON]: "Bon de livraison",
  [SageDocumentType.BON_RETOUR]: "Bon de retour",
  [SageDocumentType.BON_AVOIR]: "Avoir",
  [SageDocumentType.FACTURE]: "Facture",
};

const DOCUMENT_ROUTES: Record<SageDocumentType, string> = {
  [SageDocumentType.DEVIS]: "/home/devis",
  [SageDocumentType.BON_COMMANDE]: "/home/commandes",
  [SageDocumentType.PREPARATION]: "/home/preparations",
  [SageDocumentType.BON_LIVRAISON]: "/home/bons-livraison",
  [SageDocumentType.BON_RETOUR]: "/home/retours",
  [SageDocumentType.BON_AVOIR]: "/home/avoirs",
  [SageDocumentType.FACTURE]: "/home/factures",
};

// ============================================
// TYPE DOCUMENT GÉNÉRIQUE
// ============================================

type DocumentBase = { 
  numero: string; 
  statut: number;
  client_intitule?: string;
  client_code?: string;
};

// ============================================
// COMPOSANT MODAL
// ============================================

export function ModalStatus({
  open,
  onClose,
  type_doc,
  document,
}: {
  open: boolean;
  onClose: () => void;
  type_doc: SageDocumentType;
  document?: DocumentBase | null;
}) {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();

  // Sélecteurs par type de document
  const devisSelected = useAppSelector(getDevisSelected) as DevisListItem | null;
  const commandeSelected = useAppSelector(getcommandeSelected) as Commande | null;
  const factureSelected = useAppSelector(getfactureSelected) as Facture | null;
  const livraisonSelected = useAppSelector(getBLSelected) as BL | null;
  const avoirSelected = useAppSelector(getavoirSelected) as Avoir | null;

  // Status loading par type de document
  const devisLoading = useAppSelector(devisStatus);
  const commandeLoading = useAppSelector(commandeStatus);
  const factureLoading = useAppSelector(factureStatus);
  const livraisonLoading = useAppSelector(BLStatus);
  const avoirLoading = useAppSelector(avoirStatus);

  // Document sélectionné dynamique
  const currentDocument = useMemo((): DocumentBase | null => {
    if (document) return document;
    
    switch (type_doc) {
      case SageDocumentType.DEVIS:
        return devisSelected;
      case SageDocumentType.BON_COMMANDE:
        return commandeSelected;
      case SageDocumentType.FACTURE:
        return factureSelected;
      case SageDocumentType.BON_LIVRAISON:
        return livraisonSelected;
      case SageDocumentType.BON_AVOIR:
        return avoirSelected;
      default:
        return devisSelected;
    }
  }, [document, type_doc, devisSelected, commandeSelected, factureSelected, livraisonSelected, avoirSelected]);

  // Loading dynamique
  const isLoading = useMemo(() => {
    switch (type_doc) {
      case SageDocumentType.DEVIS:
        return devisLoading === "loading";
      case SageDocumentType.BON_COMMANDE:
        return commandeLoading === "loading";
      case SageDocumentType.FACTURE:
        return factureLoading === "loading";
      case SageDocumentType.BON_LIVRAISON:
        return livraisonLoading === "loading";
      case SageDocumentType.BON_AVOIR:
        return avoirLoading === "loading";
      default:
        return devisLoading === "loading";
    }
  }, [type_doc, devisLoading, commandeLoading, factureLoading, livraisonLoading, avoirLoading]);

  const [error, setError] = useState<string | null>(null);
  const [selectedStatus, setSelectedStatus] = useState<number>(0);

  // Options dynamiques selon le type de document
  const statusOptions = STATUS_OPTIONS[type_doc] || STATUS_OPTIONS[SageDocumentType.DEVIS];
  const documentLabel = DOCUMENT_LABELS[type_doc] || "Document";
  const documentRoute = DOCUMENT_ROUTES[type_doc] || "/home/devis";

  useEffect(() => {
    if (!open) return;
    setSelectedStatus(currentDocument?.statut ?? 0);
    setError(null);
  }, [open, currentDocument]);

  // Dispatch dynamique selon le type de document
  const dispatchStatusChange = async (payload: StatusRequest) => {
    switch (type_doc) {
      case SageDocumentType.DEVIS:
        return dispatch(changerStatutDevis(payload)).unwrap();
      case SageDocumentType.BON_COMMANDE:
        return dispatch(changerStatutCommande(payload)).unwrap();
      case SageDocumentType.FACTURE:
        return dispatch(changerStatutFacture(payload)).unwrap();
      case SageDocumentType.BON_LIVRAISON:
        return dispatch(changerStatutBL(payload)).unwrap();
      default:
        return dispatch(changerStatutDevis(payload)).unwrap();
    }
  };

  async function onSave() {
    if (selectedStatus === currentDocument?.statut) {
      onClose();
      return;
    }

    setError(null);
    try {
      const payload: StatusRequest = {
        numero: currentDocument!.numero,
        status: selectedStatus,
      };

      const rep = await dispatchStatusChange(payload);

      toast({
        title: "Statut mis à jour !",
        description: `Le statut du ${documentLabel.toLowerCase()} ${rep.document_id} a été modifié avec succès.`,
        className: "bg-green-500 text-white border-green-600",
      });

      setTimeout(() => {
        onClose();
        navigate(`${documentRoute}/${rep.document_id}`);
      }, 1500);
    } catch (e) {
      setError(`Ce ${documentLabel.toLowerCase()} ne peut pas être modifié dans ce statut`);
    }
  }

  // Trouver le label du statut actuel et sélectionné
  const currentStatusLabel = statusOptions.find(s => s.value === currentDocument?.statut)?.label || "Inconnu";
  const selectedStatusLabel = statusOptions.find(s => s.value === selectedStatus)?.label || "Inconnu";

  const hasChanged = selectedStatus !== currentDocument?.statut;

  return (
    <AnimatePresence>
      {open && currentDocument && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[70]"
          />

          {/* Modal Panel - Slide from right */}
          <motion.div
            initial={{ x: "100%" }}
            animate={{ x: 0 }}
            exit={{ x: "100%" }}
            transition={{ type: "spring", damping: 25, stiffness: 200 }}
            className="fixed inset-y-0 right-0 w-full max-w-md bg-white dark:bg-gray-950 shadow-2xl z-[80] flex flex-col border-l border-gray-200 dark:border-gray-800"
          >
            {/* Header */}
            <div className="flex items-center justify-between px-6 py-5 border-b border-gray-200 dark:border-gray-800">
              <div>
                <h2 className="text-lg font-bold text-gray-900 dark:text-white">Changer le statut</h2>
                <p className="text-sm text-gray-500">Mise à jour du cycle de vie</p>
              </div>
              <button 
                onClick={onClose} 
                className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            {/* Content */}
            <div className="flex-1 overflow-y-auto p-6 space-y-8">
              
              {/* Document Info Card */}
              <div className="bg-gray-50 dark:bg-gray-900/50 rounded-xl p-5 border border-gray-100 dark:border-gray-800 space-y-4">
                <div className="flex items-center gap-3 mb-2">
                  <div className="p-2 bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700">
                    <ShieldAlert className="w-5 h-5 text-gray-400" />
                  </div>
                  <div>
                    <p className="text-xs font-semibold text-gray-500 uppercase tracking-wider">Document</p>
                    <p className="font-bold text-gray-900 dark:text-white">{documentLabel} #{currentDocument.numero}</p>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4 pt-2 border-t border-gray-200 dark:border-gray-700/50">
                  <div>
                    <p className="text-xs text-gray-500 mb-1">Client</p>
                    <p className="text-sm font-medium text-gray-900 dark:text-white truncate" title={currentDocument.client_intitule}>
                      {currentDocument.client_intitule || 'N/A'}
                    </p>
                    {currentDocument.client_code && (
                      <p className="text-xs text-gray-400">{currentDocument.client_code}</p>
                    )}
                  </div>
                  <div>
                    <p className="text-xs text-gray-500 mb-1">Statut actuel</p>
                    <StatusBadge status={currentDocument.statut} type_doc={type_doc} />
                  </div>
                </div>
              </div>

              {/* Status Selection */}
              <div className="space-y-4">
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                  Nouveau statut
                </label>
                <div className="relative">
                  <select
                    value={selectedStatus}
                    onChange={(e) => setSelectedStatus(Number(e.target.value))}
                    className="w-full pl-4 pr-10 py-3 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-xl appearance-none focus:outline-none focus:ring-2 focus:ring-[#007E45] focus:border-transparent text-sm text-gray-900 dark:text-white"
                  >
                    {statusOptions.map((option) => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                  {/* Custom Arrow */}
                  <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none">
                    <svg className="w-4 h-4 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
                    </svg>
                  </div>
                </div>
                
                {/* Visual Preview - Only show if status changed */}
                {hasChanged && (
                  <motion.div 
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="flex items-center justify-between p-4 bg-[#007E45]/5 rounded-xl border border-[#007E45]/20"
                  >
                    <div className="flex flex-col items-center gap-1 flex-1">
                      <span className="text-xs text-gray-500">Avant</span>
                      <StatusBadge status={currentDocument.statut} type_doc={type_doc} />
                    </div>
                    <ArrowRight className="w-5 h-5 text-[#007E45] mx-4" />
                    <div className="flex flex-col items-center gap-1 flex-1">
                      <span className="text-xs text-[#007E45] font-medium">Après</span>
                      <StatusBadge status={selectedStatus} type_doc={type_doc} />
                    </div>
                  </motion.div>
                )}
              </div>

              {/* Error Message */}
              {error && (
                <motion.div 
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl text-sm text-red-700 dark:text-red-400"
                >
                  {error}
                </motion.div>
              )}

              {/* Audit Info Note */}
              <div className="flex gap-3 p-4 bg-blue-50 dark:bg-blue-900/10 rounded-xl text-xs text-blue-700 dark:text-blue-400">
                <History className="w-4 h-4 shrink-0 mt-0.5" />
                <p>
                  Ce changement de statut sera enregistré dans l'historique du document. 
                  Cette action n'entraîne pas automatiquement de mouvement comptable ou de stock.
                </p>
              </div>

            </div>

            {/* Footer */}
            <div className="p-6 border-t border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-900/50 flex items-center justify-end gap-3">
              <button 
                onClick={onClose}
                className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-white dark:hover:bg-gray-800 hover:shadow-sm border border-transparent hover:border-gray-200 dark:hover:border-gray-700 rounded-xl transition-all"
              >
                Annuler
              </button>
              <button
                onClick={onSave}
                disabled={!hasChanged || isLoading}
                className={cn(
                  "inline-flex items-center gap-2 px-5 py-2.5 text-sm font-medium text-white rounded-xl transition-all shadow-lg",
                  "bg-[#007E45] hover:bg-[#006837]",
                  "disabled:opacity-50 disabled:cursor-not-allowed disabled:shadow-none"
                )}
              >
                {isLoading ? (
                  <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                ) : (
                  <Save className="w-4 h-4" />
                )}
                Appliquer le statut
              </button>
            </div>

          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}

export default ModalStatus;