import React from "react";
import { useNavigate } from "react-router-dom";
import {
   ArrowLeft,
   FileText,
   FileSignature,
   Eye,
   EyeOff,
   Loader2,
   Save,
   Settings,
} from "lucide-react";
import { cn, formatDateFRCourt, formatForDateInput } from "@/lib/utils";
import { Input } from "@/components/ui/FormModal";
import { DevisListItem } from "@/types/devisType";
import { Client } from "@/types/clientType";
import { UniversignType } from "@/types/sageTypes";
import StatusBadge from "@/components/ui/StatusBadge";
import ClientAutocomplete from "@/components/molecules/ClientAutocomplete";
import PrimaryButton_v2 from "@/components/PrimaryButton_v2";
import { ActionButton } from "@/components/ribbons/ActionButton";
import { UserInterface } from "@/types/userInterface";

interface DevisHeaderProps {
   // Données
   devis: DevisListItem;
   client: Client;
   devisSigned: UniversignType | null;

   userConnected: UserInterface
   
   // États d'édition
   isEditing: boolean;
   isSaving: boolean;
   canSave: boolean;
   
   // Champs éditables
   editClient: Client | null;
   editDateEmission: string;
   editDateLivraison: string;
   editReference: string;
   
   // États UI
   isPdfPreviewVisible: boolean;
   
   // Handlers d'édition
   onSetEditClient: (client: Client | null) => void;
   onSetEditDateEmission: (date: string) => void;
   onSetEditDateLivraison: (date: string) => void;
   onSetEditReference: (ref: string) => void;
   
   // Handlers d'actions
   onStartEdit: () => void;
   onCancelEdit: () => void;
   onSaveEdit: () => void;
   onTogglePdfPreview: () => void;
   onOpenStatusModal: () => void;
   onOpenSignatureModal: () => void;
   onOpenTransformModal: () => void;
   onNavigateToClient: (clientCode: string) => void;
}

const DevisHeader: React.FC<DevisHeaderProps> = ({
   devis,
   client,
   devisSigned,
   isEditing,
   isSaving,
   canSave,
   editClient,
   editDateEmission,
   editDateLivraison,
   editReference,
   isPdfPreviewVisible,
   userConnected,
   onSetEditClient,
   onSetEditDateEmission,
   onSetEditDateLivraison,
   onSetEditReference,
   onStartEdit,
   onCancelEdit,
   onSaveEdit,
   onTogglePdfPreview,
   onOpenStatusModal,
   onOpenSignatureModal,
   onOpenTransformModal,
   onNavigateToClient,
}) => {
   const navigate = useNavigate();
   const isSigned = devisSigned?.local_status === "SIGNE";

   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
                        devis={devis}
                        devisSigned={devisSigned}
                        isEditing={isEditing}
                        onBack={() => navigate("/home/devis")}
                     />

                     <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={devis.client_intitule}
                        onSetEditClient={onSetEditClient}
                        onNavigateToClient={() => onNavigateToClient(devis.client_code)}
                     />

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

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

               {/* Right Section - Actions */}
               <HeaderActions
                  isEditing={isEditing}
                  isSaving={isSaving}
                  canSave={canSave}
                  isSigned={isSigned}
                  devisStatut={devis.statut}
                  isPdfPreviewVisible={isPdfPreviewVisible}
                  onStartEdit={onStartEdit}
                  onCancelEdit={onCancelEdit}
                  onSaveEdit={onSaveEdit}
                  onTogglePdfPreview={onTogglePdfPreview}
                  onOpenStatusModal={onOpenStatusModal}
                  onOpenSignatureModal={onOpenSignatureModal}
                  onOpenTransformModal={onOpenTransformModal}
               />
            </div>
         </div>
      </div>
   );
};

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

interface HeaderTitleProps {
   devis: DevisListItem;
   devisSigned: UniversignType | null;
   isEditing: boolean;
   onBack: () => void;
}

const HeaderTitle: React.FC<HeaderTitleProps> = ({
   devis,
   devisSigned,
   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">
               {devis.numero}
            </h1>
            <StatusBadge
               status={devisSigned?.local_status === "SIGNE" ? 6 : devis.statut}
               type_doc={0}
            />
            {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 {
   editDateEmission: string;
   onSetEditDateEmission: (date: string) => void;
   userConnected: UserInterface
}

const EditingDateFields: React.FC<EditingDateFieldsProps> = ({
   editDateEmission,
   onSetEditDateEmission,
   userConnected
}) => (
   <div className="flex gap-4 shrink-0">
      <div className="w-auto">
         <Input
            type="date"
            value={formatForDateInput(editDateEmission)}
            onChange={(e) => onSetEditDateEmission(e.target.value)}
            className="h-10 text-xs"
         />
      </div>
      <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>
      <Input
         type="date"
         value={formatForDateInput(editDateLivraison)}
         onChange={(e) => onSetEditDateLivraison(e.target.value)}
         className="h-10 text-xs w-[140px]"
      />
   </div>
);

interface ReadOnlyRow2Props {
   devis: DevisListItem;
   userConnected: UserInterface;
   devisSigned: UniversignType | null;
}

const ReadOnlyRow2: React.FC<ReadOnlyRow2Props> = ({ devis, userConnected, devisSigned }) => (
   <div className="flex flex-row gap-8 items-center">
      <div className="flex flex-col">
         <span className="text-xs font-medium text-gray-500">Date</span>
         <span className="text-sm text-gray-900 dark:text-white">
            {formatDateFRCourt(devis.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>
      {devisSigned?.signers && devisSigned.signers.length > 0 && (
         <div className="flex flex-col">
            <span className="text-xs font-medium text-gray-500">Signataire</span>
            <span className="text-sm text-gray-900 dark:text-white">
               {devisSigned.signers[0].name}
            </span>
         </div>
      )}
   </div>
);

interface HeaderActionsProps {
   isEditing: boolean;
   isSaving: boolean;
   canSave: boolean;
   isSigned: boolean;
   devisStatut: number;
   isPdfPreviewVisible: boolean;
   onStartEdit: () => void;
   onCancelEdit: () => void;
   onSaveEdit: () => void;
   onTogglePdfPreview: () => void;
   onOpenStatusModal: () => void;
   onOpenSignatureModal: () => void;
   onOpenTransformModal: () => void;
}

const HeaderActions: React.FC<HeaderActionsProps> = ({
   isEditing,
   isSaving,
   canSave,
   isSigned,
   devisStatut,
   isPdfPreviewVisible,
   onStartEdit,
   onCancelEdit,
   onSaveEdit,
   onTogglePdfPreview,
   onOpenStatusModal,
   onOpenSignatureModal,
   onOpenTransformModal,
}) => (
   <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-[#2A6F4F] 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
            isSigned={isSigned}
            devisStatut={devisStatut}
            onStartEdit={onStartEdit}
            onOpenStatusModal={onOpenStatusModal}
            onOpenSignatureModal={onOpenSignatureModal}
            onOpenTransformModal={onOpenTransformModal}
         />
      )}
   </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 {
   isSigned: boolean;
   devisStatut: number;
   onStartEdit: () => void;
   onOpenStatusModal: () => void;
   onOpenSignatureModal: () => void;
   onOpenTransformModal: () => void;
}

const ReadOnlyActions: React.FC<ReadOnlyActionsProps> = ({
   isSigned,
   devisStatut,
   onStartEdit,
   onOpenStatusModal,
   onOpenSignatureModal,
   onOpenTransformModal,
}) => (
   <>
      {(devisStatut === 0 || devisStatut === 1) && (
         <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>
      )}
      <PrimaryButton_v2
         icon={FileSignature}
         disabled={isSigned}
         onClick={onOpenSignatureModal}
         className="bg-white text-[#2A6F4F] border border-[#2A6F4F] hover:bg-green-50"
      >
         <span className="hidden lg:inline">
            Envoyer pour signature électronique
         </span>
      </PrimaryButton_v2>
      {
         devisStatut === 2 && (
            <ActionButton
               onClick={onOpenTransformModal}
               icon={FileText}
               label="Transformer"
               className="bg-[#2A6F4F] text-white hover:bg-[#235c41]"
            />
         )
      }
      <button
         onClick={onStartEdit}
         disabled={isSigned}
         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",
            isSigned && "opacity-60 cursor-not-allowed"
         )}
      >
         Modifier
      </button>
   </>
);

export default DevisHeader;