import React from "react";
import { useNavigate } from "react-router-dom";
import {
   ArrowLeft,
   Undo2,
   Eye,
   EyeOff,
   Loader2,
   Save,
   Settings,
   Download,
   AlertTriangle,
   Lock,
} from "lucide-react";
import { cn, formatDateFRCourt, formatForDateInput } from "@/lib/utils";
import { Input } from "@/components/ui/FormModal";
import { Facture } from "@/types/factureType";
import { Client } from "@/types/clientType";
import StatusBadge from "@/components/ui/StatusBadge";
import ClientAutocomplete from "@/components/molecules/ClientAutocomplete";
import PrimaryButton_v2 from "@/components/PrimaryButton_v2";
import { UserInterface } from "@/types/userInterface";
import { ActionButton } from "@/components/ribbons/ActionButton";

interface FactureHeaderProps {
   // Données
   facture: Facture;
   client: Client | null;
   userConnected: UserInterface;

   // États d'édition
   isEditing: boolean;
   isSaving: boolean;
   canSave: boolean;

   // Champs éditables
   editClient: Client | null;
   editDateFacture: string;
   editDateLivraison: string;
   editReference: string;

   // États UI
   isPdfPreviewVisible: boolean;
  
   setIsValid: React.Dispatch<React.SetStateAction<boolean>>;

   // Handlers d'édition
   onSetEditClient: (client: Client | null) => void;
   onSetEditDateFacture: (date: string) => void;
   onSetEditDateLivraison: (date: string) => void;
   onSetEditReference: (ref: string) => void;

   // Handlers d'actions
   onStartEdit: () => void;
   onCancelEdit: () => void;
   onSaveEdit: () => void;
   onTogglePdfPreview: () => void;
   onOpenStatusModal: () => void;
   onOpenCreateAvoir: () => void;
   onNavigateToClient: (clientCode: string) => void;
   onDownloadPdf?: () => void;
}

const FactureHeader: React.FC<FactureHeaderProps> = ({
   facture,
   client,
   userConnected,
   isEditing,
   isSaving,
   canSave,
   setIsValid,
   editClient,
   editDateFacture,
   editDateLivraison,
   editReference,
   isPdfPreviewVisible,
   onSetEditClient,
   onSetEditDateFacture,
   onSetEditDateLivraison,
   onSetEditReference,
   onStartEdit,
   onCancelEdit,
   onSaveEdit,
   onTogglePdfPreview,
   onOpenStatusModal,
   onOpenCreateAvoir,
   onNavigateToClient,
   onDownloadPdf,
}) => {
   const navigate = useNavigate();
   const isPaid = facture.statut === 2;
   const isLocked = facture.valide === 0;

   return (
      <div
         className={cn(
            "bg-white dark:bg-gray-950 border-b border-gray-200 dark:border-gray-800 z-30 shadow-[0_1px_3px_rgba(0,0,0,0.05)] transition-all duration-300 shrink-0 py-2"
         )}
      >
         <div className="max-w-[1920px] mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex flex-col gap-4 justify-between items-start lg:flex-row lg:items-center">
               {/* Main Info Area */}
               <div className="flex flex-col flex-1 gap-3 w-full min-w-0 lg:w-auto">
                  {/* Row 1 */}
                  <div className="flex flex-wrap gap-4 items-center">
                     {/* Back button + Title */}
                     <HeaderTitle
                        facture={facture}
                        isEditing={isEditing}
                        onBack={() => navigate("/home/factures")}
                     />

                     <div className="hidden mx-2 w-px h-8 bg-gray-200 dark:bg-gray-800 sm:block" />

                     {/* Client Field */}
                     <ClientField
                        isEditing={isEditing}
                        editClient={editClient}
                        clientIntitule={facture.client_intitule}
                        onSetEditClient={onSetEditClient}
                        onNavigateToClient={() => onNavigateToClient(facture.client_code)}
                     />

                     {/* Date Fields (editing mode) */}
                     {isEditing && (
                        <EditingDateFields
                           editDateFacture={editDateFacture}
                           onSetEditDateFacture={onSetEditDateFacture}
                           userConnected={userConnected}
                        />
                     )}
                  </div>

                  {/* Row 2 */}
                  {isEditing ? (
                     <EditingRow2
                        editReference={editReference}
                        editDateLivraison={editDateLivraison}
                        onSetEditReference={onSetEditReference}
                        onSetEditDateLivraison={onSetEditDateLivraison}
                     />
                  ) : (
                     <ReadOnlyRow2
                        facture={facture}
                        userConnected={userConnected}
                     />
                  )}
               </div>

               {/* Right Section - Actions */}
               <HeaderActions
                  isEditing={isEditing}
                  isSaving={isSaving}
                  canSave={canSave}
                  isPaid={isPaid}
                  isLocked={isLocked}
                  factureStatut={facture.statut}
                  isPdfPreviewVisible={isPdfPreviewVisible}
                  onStartEdit={onStartEdit}
                  onCancelEdit={onCancelEdit}
                  onSaveEdit={onSaveEdit}
                  setIsValid={setIsValid}
                  onTogglePdfPreview={onTogglePdfPreview}
                  onOpenStatusModal={onOpenStatusModal}
                  onOpenCreateAvoir={onOpenCreateAvoir}
                  onDownloadPdf={onDownloadPdf}
               />
            </div>
         </div>
      </div>
   );
};

// ============================================
// SOUS-COMPOSANTS
// ============================================

interface HeaderTitleProps {
   facture: Facture;
   isEditing: boolean;
   onBack: () => void;
}

const HeaderTitle: React.FC<HeaderTitleProps> = ({
   facture,
   isEditing,
   onBack,
}) => (
   <div className="flex gap-3 items-center mr-2 shrink-0">
      <button
         onClick={onBack}
         disabled={isEditing}
         className="p-1.5 -ml-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors text-gray-500 disabled:opacity-50"
      >
         <ArrowLeft className="w-5 h-5" />
      </button>
      <div className="flex flex-col">
         <div className="flex gap-2 items-center">
            <h1 className="text-xl font-bold tracking-tight text-gray-900 dark:text-white">
               {facture.numero}
            </h1>
            <StatusBadge status={facture.valide === 1 ? 5 : facture.statut} type_doc={60} />
            {isEditing && (
               <span className="px-2 py-1 text-xs font-medium text-amber-800 bg-amber-100 rounded-full">
                  Mode édition
               </span>
            )}
         </div>
      </div>
   </div>
);

interface ClientFieldProps {
   isEditing: boolean;
   editClient: Client | null;
   clientIntitule: string;
   onSetEditClient: (client: Client | null) => void;
   onNavigateToClient: () => void;
}

const ClientField: React.FC<ClientFieldProps> = ({
   isEditing,
   editClient,
   clientIntitule,
   onSetEditClient,
   onNavigateToClient,
}) => (
   <div className="flex-1 min-w-[250px] max-w-[400px]">
      {isEditing ? (
         <div className="relative z-20">
            <ClientAutocomplete
               value={editClient}
               onChange={onSetEditClient}
               required
            />
         </div>
      ) : (
         <div
            className="flex flex-col p-2 -m-2 rounded-lg transition-colors cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-900"
            onClick={onNavigateToClient}
         >
            <span className="text-xs font-medium text-gray-500">Client</span>
            <span className="font-semibold text-gray-900 truncate dark:text-white">
               {clientIntitule || "—"}
            </span>
         </div>
      )}
   </div>
);

interface EditingDateFieldsProps {
   editDateFacture: string;
   onSetEditDateFacture: (date: string) => void;
   userConnected?: UserInterface;
}

const EditingDateFields: React.FC<EditingDateFieldsProps> = ({
   editDateFacture,
   onSetEditDateFacture,
   userConnected,
}) => (
   <div className="flex gap-4 shrink-0">
      <div className="w-auto">
         <Input
            type="date"
            value={formatForDateInput(editDateFacture)}
            onChange={(e) => onSetEditDateFacture(e.target.value)}
            className="h-10 text-xs"
         />
      </div>
      {userConnected && (
         <div className="w-[140px]">
            <div
               className={cn(
                  "flex flex-row gap-2 items-center px-1 py-1 w-full text-sm bg-gray-50 rounded-xl border shadow-sm opacity-80 cursor-not-allowed dark:bg-gray-900",
                  "border-gray-200 dark:border-gray-800"
               )}
            >
               <div
                  className="w-6 h-6 rounded-full bg-[#007E45] text-white flex items-center justify-center text-[10px] font-semibold"
                  style={{ width: "3vh", height: "3vh" }}
               >
                  {userConnected
                     ? `${userConnected.prenom?.[0] || ""}${userConnected.nom?.[0] || ""}`
                     : "JD"}
               </div>
               <span className="text-sm text-gray-900 dark:text-white">
                  {userConnected ? `${userConnected.prenom}` : "_"}
               </span>
            </div>
         </div>
      )}
   </div>
);

interface EditingRow2Props {
   editReference: string;
   editDateLivraison: string;
   onSetEditReference: (ref: string) => void;
   onSetEditDateLivraison: (date: string) => void;
}

const EditingRow2: React.FC<EditingRow2Props> = ({
   editReference,
   editDateLivraison,
   onSetEditReference,
   onSetEditDateLivraison,
}) => (
   <div className="flex flex-wrap gap-4 items-center pt-1 animate-in fade-in slide-in-from-top-1">
      <div className="w-[250px]">
         <Input
            value={editReference}
            onChange={(e) => onSetEditReference(e.target.value)}
            placeholder="REF-EXT-123 ..."
            className="h-9 text-xs"
         />
      </div>
      <div className="flex items-center gap-2">
         <AlertTriangle className="w-4 h-4 text-red-500" />
         <Input
            type="date"
            value={formatForDateInput(editDateLivraison)}
            onChange={(e) => onSetEditDateLivraison(e.target.value)}
            className="h-10 text-xs w-[140px]"
         />
      </div>
   </div>
);

interface ReadOnlyRow2Props {
   facture: Facture;
   userConnected: UserInterface;
}

const ReadOnlyRow2: React.FC<ReadOnlyRow2Props> = ({
   facture,
   userConnected,
}) => {
   return (
      <div className="flex flex-row gap-8 items-center">
         <div className="flex flex-col">
            <span className="text-xs font-medium text-gray-500">
               Date d'émission
            </span>
            <span className="text-sm text-gray-900 dark:text-white">
               {formatDateFRCourt(facture.date)}
            </span>
         </div>
         <div className="flex flex-col">
            <span className="text-xs font-medium text-gray-500">Commercial</span>
            <span className="text-sm text-gray-900 dark:text-white">
               {userConnected
                  ? `${userConnected.prenom} ${userConnected.nom}`
                  : "_"}
            </span>
         </div>
         {facture.date_livraison && (
            <div className="flex flex-col">
               <span className="text-xs font-medium text-red-500 flex items-center gap-1">
                  <AlertTriangle className="w-3 h-3" />
                  Date d'échéance
               </span>
               <span className="text-sm font-semibold text-red-600">
                  {formatDateFRCourt(facture.date_livraison)}
               </span>
            </div>
         )}
         {facture.reference && (
            <div className="flex flex-col">
               <span className="text-xs font-medium text-gray-500">Référence</span>
               <span className="text-sm text-gray-900 dark:text-white">
                  {facture.reference}
               </span>
            </div>
         )}
      </div>
   );
}

interface HeaderActionsProps {
   isEditing: boolean;
   isSaving: boolean;
   canSave: boolean;
   isPaid: boolean;
   isLocked: boolean;
   factureStatut: number;
   isPdfPreviewVisible: boolean;
   setIsValid: React.Dispatch<React.SetStateAction<boolean>>;
   onStartEdit: () => void;
   onCancelEdit: () => void;
   onSaveEdit: () => void;
   onTogglePdfPreview: () => void;
   onOpenStatusModal: () => void;
   onOpenCreateAvoir: () => void;
   onDownloadPdf?: () => void;
}

const HeaderActions: React.FC<HeaderActionsProps> = ({
   isEditing,
   isSaving,
   canSave,
   isPaid,
   isLocked,
   factureStatut,
   isPdfPreviewVisible,
   setIsValid,
   onStartEdit,
   onCancelEdit,
   onSaveEdit,
   onTogglePdfPreview,
   onOpenStatusModal,
   onOpenCreateAvoir,
   onDownloadPdf,
}) => (
   <div className="flex gap-3 items-center self-start mt-2 ml-auto shrink-0 lg:self-center lg:mt-0">
      {/* Toggle PDF Preview */}
      <div className="flex items-center p-1 mr-2 bg-gray-100 rounded-lg dark:bg-gray-800">
         <button
            onClick={onTogglePdfPreview}
            className={cn(
               "p-1.5 rounded-md transition-all",
               isPdfPreviewVisible
                  ? "bg-white dark:bg-gray-700 text-[#007E45] shadow-sm"
                  : "text-gray-500 hover:text-gray-900 hover:bg-white"
            )}
            title="Aperçu PDF"
         >
            {isPdfPreviewVisible ? (
               <Eye className="w-4 h-4" />
            ) : (
               <EyeOff className="w-4 h-4" />
            )}
         </button>
      </div>

      {isEditing ? (
         <EditingActions
            isSaving={isSaving}
            canSave={canSave}
            onCancelEdit={onCancelEdit}
            onSaveEdit={onSaveEdit}
         />
      ) : (
         <ReadOnlyActions
            isPaid={isPaid}
            isLocked={isLocked}
            setIsValid={setIsValid}
            factureStatut={factureStatut}
            onStartEdit={onStartEdit}
            onOpenStatusModal={onOpenStatusModal}
            onOpenCreateAvoir={onOpenCreateAvoir}
            onDownloadPdf={onDownloadPdf}
         />
      )}
   </div>
);

interface EditingActionsProps {
   isSaving: boolean;
   canSave: boolean;
   onCancelEdit: () => void;
   onSaveEdit: () => void;
}

const EditingActions: React.FC<EditingActionsProps> = ({
   isSaving,
   canSave,
   onCancelEdit,
   onSaveEdit,
}) => (
   <div className="flex gap-2 items-center">
      <button
         onClick={onCancelEdit}
         disabled={isSaving}
         className="px-4 py-2 text-sm font-medium text-gray-600 transition-colors hover:text-gray-900 disabled:opacity-50"
      >
         Annuler
      </button>
      <button
         onClick={onSaveEdit}
         disabled={!canSave || isSaving}
         className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-[#007E45] hover:bg-[#006837] rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed shadow-sm"
      >
         {isSaving ? (
            <Loader2 className="w-4 h-4 animate-spin" />
         ) : (
            <Save className="w-4 h-4" />
         )}
         Enregistrer
      </button>
   </div>
);

interface ReadOnlyActionsProps {
   isPaid: boolean;
   isLocked: boolean;
   setIsValid: React.Dispatch<React.SetStateAction<boolean>>;
   factureStatut: number;
   onStartEdit: () => void;
   onOpenStatusModal: () => void;
   onOpenCreateAvoir: () => void;
   onDownloadPdf?: () => void;
}

const ReadOnlyActions: React.FC<ReadOnlyActionsProps> = ({
   isPaid,
   isLocked,
   factureStatut,
   setIsValid,
   onStartEdit,
   onOpenStatusModal,
   onOpenCreateAvoir,
   onDownloadPdf,
}) => (
   <>
      {onDownloadPdf && (
         <button
            onClick={onDownloadPdf}
            className="p-2 text-gray-600 hover:text-gray-900 transition-colors"
            title="Télécharger PDF"
         >
            <Download className="w-5 h-5" />
         </button>
      )}

      {isPaid ? (
         <PrimaryButton_v2
            icon={Undo2}
            onClick={onOpenCreateAvoir}
            className="bg-green-50 text-green-700 border border-green-100 hover:bg-green-100"
         >
            <span className="hidden lg:inline">Créer Avoir</span>
         </PrimaryButton_v2>
      ) : (
        <div className="flex flex-wrap items-center gap-2">
             <button
                onClick={onOpenStatusModal}
                className="flex gap-2 items-center px-3 py-2 text-sm font-medium text-gray-700 bg-white rounded-xl border border-gray-200 transition-colors hover:bg-gray-50"
                title="Changer le statut"
            >
                <Settings className="w-4 h-4 text-gray-500" />
                <span className="hidden lg:inline">Changer le statut</span>
            </button>
            {isLocked && (
               <ActionButton
                  onClick={() => setIsValid(true) }
                  icon={Lock}
                  label="Valider"
                  className="bg-blue-600 text-white hover:bg-blue-700"
               />
            )}
        </div>
      )}

      <button
         onClick={onStartEdit}
         className={cn(
            "px-4 py-2 text-sm font-medium text-gray-700 hover:text-gray-900 border border-gray-300 rounded-xl hover:bg-gray-50 transition-colors bg-white shadow-sm"
         )}
      >
         Modifier
      </button>
   </>
);

export default FactureHeader;