import React from "react";
import {
   Building2,
   User,
   MapPin,
   Phone,
   Mail,
   Globe,
   FileText,
   CreditCard,
} from "lucide-react";
import { Client } from "@/types/clientType";

// ============================================
// TYPES
// ============================================

interface ClientDetailsGridProps {
   client: Client;
}

interface SectionCardProps {
   icon: React.ElementType;
   title: string;
   children: React.ReactNode;
}

interface InfoRowProps {
   label: string;
   value?: string | number | null;
}

// ============================================
// HELPERS
// ============================================

const getTypeTiersLabel = (type: number): string => {
   switch (type) {
      case 0:
         return "Client";
      case 1:
         return "Fournisseur";
      case 2:
         return "Client & Fournisseur";
      case 3:
         return "Autre";
      default:
         return "Non défini";
   }
};

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

const SectionCard: React.FC<SectionCardProps> = ({ icon: Icon, title, children }) => (
   <div className="bg-white dark:bg-gray-950 rounded-xl border border-gray-200 dark:border-gray-800 overflow-hidden">
      <div className="px-4 py-3 border-b border-gray-100 dark:border-gray-800 flex items-center gap-2">
         <Icon className="w-4 h-4 text-[#007E45]" />
         <h3 className="font-semibold text-gray-900 dark:text-white text-sm">{title}</h3>
      </div>
      <div className="p-4">{children}</div>
   </div>
);

const InfoRow: React.FC<InfoRowProps> = ({ label, value }) => {
   if (!value && value !== 0) return null;
   
   return (
      <div className="flex justify-between items-start gap-4">
         <span className="text-sm text-gray-500 flex-shrink-0">{label}</span>
         <span className="text-sm text-gray-900 dark:text-white text-right font-medium">
            {value}
         </span>
      </div>
   );
};

const ContactLink: React.FC<{
   icon: React.ElementType;
   href: string;
   label: string;
   suffix?: string;
   isExternal?: boolean;
}> = ({ icon: Icon, href, label, suffix, isExternal = false }) => (
   <div className="flex items-center gap-3">
      <Icon className="w-4 h-4 text-gray-400 flex-shrink-0" />
      <a
         href={href}
         target={isExternal ? "_blank" : undefined}
         rel={isExternal ? "noopener noreferrer" : undefined}
         className="text-blue-600 hover:underline break-all"
      >
         {label}
      </a>
      {suffix && <span className="text-xs text-gray-500">{suffix}</span>}
   </div>
);

const StatusBadge: React.FC<{ label: string; color: "blue" | "purple" | "red" }> = ({
   label,
   color,
}) => {
   const colorClasses = {
      blue: "bg-blue-100 text-blue-700",
      purple: "bg-purple-100 text-purple-700",
      red: "bg-red-100 text-red-700",
   };

   return (
      <span className={`px-2 py-1 ${colorClasses[color]} rounded-full text-xs font-medium`}>
         {label}
      </span>
   );
};

// ============================================
// SECTIONS
// ============================================

const InformationsPrincipales: React.FC<{ client: Client }> = ({ client }) => (
   <SectionCard icon={Building2} title="Informations principales">
      <div className="space-y-4">
         <InfoRow label="Compte Tiers" value={client.numero} />
         <InfoRow label="Raison sociale" value={client.intitule} />
         <InfoRow label="Type de tiers" value={getTypeTiersLabel(client.type_tiers || 0)} />
         <InfoRow label="Qualité" value={client.qualite} />
         <InfoRow label="Classement" value={client.classement} />

         {/* Statuts */}
         <div className="flex flex-wrap gap-2 pt-2">
            {client.est_prospect && <StatusBadge label="Prospect" color="blue" />}
            {(client.type_tiers === 1 || client.type_tiers === 2) && (
               <StatusBadge label="Fournisseur" color="purple" />
            )}
            {!client.est_actif && <StatusBadge label="Inactif" color="red" />}
         </div>
      </div>
   </SectionCard>
);

const ContactSection: React.FC<{ client: Client }> = ({ client }) => (
   <SectionCard icon={User} title="Contact">
      <div className="space-y-4">
         {client.contact && <InfoRow label="Contact principal" value={client.contact} />}

         <div className="space-y-3 pt-2">
            {client.telephone && (
               <div className="flex items-center gap-3">
                  <Phone className="w-4 h-4 text-gray-400 flex-shrink-0" />
                  <a
                     href={`tel:${client.telephone}`}
                     className="text-gray-900 dark:text-white hover:text-blue-600"
                  >
                     {client.telephone}
                  </a>
                  <span className="text-xs text-gray-500">Fixe</span>
               </div>
            )}
            {client.telecopie && (
               <div className="flex items-center gap-3">
                  <FileText className="w-4 h-4 text-gray-400 flex-shrink-0" />
                  <span className="text-gray-900 dark:text-white">{client.telecopie}</span>
                  <span className="text-xs text-gray-500">Fax</span>
               </div>
            )}
            {client.email && (
               <ContactLink
                  icon={Mail}
                  href={`mailto:${client.email}`}
                  label={client.email}
               />
            )}
            {client.site_web && (
               <ContactLink
                  icon={Globe}
                  href={client.site_web.startsWith("http") ? client.site_web : `https://${client.site_web}`}
                  label={client.site_web}
                  isExternal
               />
            )}
            {client.facebook && (
               <ContactLink
                  icon={Globe}
                  href={client.facebook.startsWith("http") ? client.facebook : `https://${client.facebook}`}
                  label="Facebook"
                  isExternal
               />
            )}
            {client.linkedin && (
               <ContactLink
                  icon={Globe}
                  href={client.linkedin.startsWith("http") ? client.linkedin : `https://${client.linkedin}`}
                  label="LinkedIn"
                  isExternal
               />
            )}
         </div>
      </div>
   </SectionCard>
);

const AdresseSection: React.FC<{ client: Client }> = ({ client }) => (
   <SectionCard icon={MapPin} title="Adresse">
      <div className="space-y-2">
         {client.adresse && (
            <p className="text-gray-900 dark:text-white">{client.adresse}</p>
         )}
         {client.complement && (
            <p className="text-gray-700 dark:text-gray-300">{client.complement}</p>
         )}
         {(client.code_postal || client.ville) && (
            <p className="text-gray-900 dark:text-white">
               {client.code_postal} {client.ville}
            </p>
         )}
         {client.region && (
            <p className="text-gray-700 dark:text-gray-300">{client.region}</p>
         )}
         {client.pays && (
            <p className="text-gray-700 dark:text-gray-300 font-medium">{client.pays}</p>
         )}
      </div>
   </SectionCard>
);

const InformationsLegales: React.FC<{ client: Client }> = ({ client }) => (
   <SectionCard icon={FileText} title="Informations légales">
      <div className="space-y-4">
         <InfoRow label="SIRET" value={client.siret} />
         <InfoRow label="TVA Intracommunautaire" value={client.tva_intra} />
         <InfoRow label="Code NAF" value={client.code_naf} />
         <InfoRow label="Forme juridique" value={client.forme_juridique} />
      </div>
   </SectionCard>
);

const DonneesFinancieres: React.FC<{ client: Client }> = ({ client }) => (
   <SectionCard icon={CreditCard} title="Données financières">
      <div className="space-y-4">
         <InfoRow label="Compte général" value={client.compte_general} />

         <div className="grid grid-cols-2 gap-4">
            {client.categorie_tarif !== null && client.categorie_tarif !== undefined && (
               <InfoRow label="Catégorie tarifaire" value={client.categorie_tarif.toString()} />
            )}
            {client.categorie_compta !== null && client.categorie_compta !== undefined && (
               <InfoRow label="Catégorie comptable" value={client.categorie_compta.toString()} />
            )}
         </div>

         {client.encours_autorise !== undefined && client.encours_autorise !== 0 && (
            <InfoRow
               label="Encours autorisé"
               value={client.encours_autorise.toLocaleString("fr-FR", {
                  style: "currency",
                  currency: "EUR",
                  minimumFractionDigits: 2,
               })}
            />
         )}

         {client.assurance_credit !== undefined && client.assurance_credit !== 0 && (
            <InfoRow
               label="Assurance crédit"
               value={client.assurance_credit.toLocaleString("fr-FR", {
                  style: "currency",
                  currency: "EUR",
                  minimumFractionDigits: 2,
               })}
            />
         )}
      </div>
   </SectionCard>
);

const CommentaireSection: React.FC<{ commentaire: string }> = ({ commentaire }) => (
   <SectionCard icon={FileText} title="Commentaire">
      <p className="text-sm text-gray-700 dark:text-gray-300 whitespace-pre-wrap">
         {commentaire}
      </p>
   </SectionCard>
);

// ============================================
// COMPOSANT PRINCIPAL
// ============================================

const ClientDetailsGrid: React.FC<ClientDetailsGridProps> = ({ client }) => {
   return (
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
         {/* Colonne gauche */}
         <div className="space-y-6">
            <InformationsPrincipales client={client} />
            <ContactSection client={client} />
            <AdresseSection client={client} />
         </div>

         {/* Colonne droite */}
         <div className="space-y-6">
            <InformationsLegales client={client} />
            <DonneesFinancieres client={client} />
            {client.commentaire && <CommentaireSection commentaire={client.commentaire} />}
         </div>
      </div>
   );
};

export default ClientDetailsGrid;

// Export des sous-composants si besoin de les réutiliser ailleurs
export {
   SectionCard,
   InfoRow,
   ContactLink,
   StatusBadge,
   InformationsPrincipales,
   ContactSection,
   AdresseSection,
   InformationsLegales,
   DonneesFinancieres,
   CommentaireSection,
   getTypeTiersLabel,
};