"use client";

import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState, useMemo } from "react";
import { ArrowLeft, Loader2, ChevronLeft, ChevronRight } from "lucide-react";
import { usePageTitle } from "@/hooks/usePageTitle";

// Types
type SalarieDetail = {
  matricule: string;
  civilite?: string;
  prenom?: string;
  nom_naissance?: string;
  nom_usage?: string;
  pseudo?: string;
  date_naissance?: string;
  lieu_naissance?: string;
  email?: string;
  telephone?: string;
  adresse?: string;
  nir?: string | number;
  conges_spectacles?: string;
  iban?: string;
  bic?: string;
  transat_connecte?: boolean;
  justificatifs?: string;
  mineur_moins_16?: boolean;
  resident_fr?: boolean;
  rib_pdf?: string | null;
};

type ContratListItem = {
  id: string;
  reference: string;
  profession?: string;
  date_debut?: string;
  date_fin?: string;
  is_multi_mois?: boolean;
  regime?: "CDDU_MONO" | "CDDU_MULTI" | "RG" | string;
};

type ContratsResponse = {
  items: ContratListItem[];
  hasMore: boolean;
};

// Helper pour formater les valeurs
function formatValue(value: any): string {
  if (value === null || value === undefined) return "—";
  if (value === "n/a" || value === "N/A" || value === "") return "—";
  return String(value);
}

// Composant Field pour l'affichage des données
function Field({ label, value }: { label: string; value: string }) {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-[160px_1fr] gap-2 py-2">
      <div className="text-sm text-slate-500">{label}</div>
      <div className="text-sm break-words">{value}</div>
    </div>
  );
}

// Composant Section
function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section className="rounded-2xl border bg-white">
      <div className="px-4 py-3 border-b font-medium text-slate-700 bg-slate-50/60">
        {title}
      </div>
      <div className="p-4">{children}</div>
    </section>
  );
}

// Fonction pour déterminer le lien vers un contrat
function hrefContrat(c: ContratListItem) {
  const isMulti = c.is_multi_mois === true || (c.regime && c.regime.toUpperCase() === "CDDU_MULTI");
  return isMulti ? `/contrats-multi/${c.id}` : `/contrats/${c.id}`;
}

// Fonction pour formater les dates
function formatDateFR(iso?: string) {
  if (!iso) return "—";
  const d = new Date(iso);
  if (isNaN(d.getTime())) return "—";
  return d.toLocaleDateString("fr-FR", { day: "2-digit", month: "2-digit", year: "numeric" });
}

export default function SalariePage() {
  const params = useParams();
  const matricule = params?.matricule as string;
  const router = useRouter();
  
  const [salarie, setSalarie] = useState<SalarieDetail | null>(null);
  
  // Titre dynamique basé sur le salarié
  const salarieName = salarie ? `${salarie.prenom} ${salarie.nom_usage || salarie.nom_naissance}`.trim() : `Salarié ${matricule}`;
  usePageTitle(`${salarieName}`);
  
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // États pour les contrats
  const [contrats, setContrats] = useState<ContratListItem[]>([]);
  const [contratsLoading, setContratsLoading] = useState(false);
  const [contratsError, setContratsError] = useState<string | null>(null);
  const [hasMore, setHasMore] = useState(false);

  // Modal "Nouveau contrat"
  const [newContratOpen, setNewContratOpen] = useState(false);
  
  // Pagination et filtres pour les contrats
  const now = new Date();
  const [year, setYear] = useState<number>(now.getFullYear());
  const [page, setPage] = useState<number>(1);
  const limit = 20;

  // Options d'années (N → N-6)
  const yearOptions = useMemo(() => {
    const base = now.getFullYear();
    return Array.from({ length: 7 }, (_, i) => base - i);
  }, [now]);

  useEffect(() => {
    if (!matricule) return;

    const fetchSalarie = async () => {
      try {
        setLoading(true);
        setError(null);
        
        // 🎭 Détection directe du mode démo
        const isDemoMode = typeof window !== 'undefined' && window.location.hostname === 'demo.odentas.fr';
        
        console.log('🔍 fetchSalarie debug:', {
          isDemoMode,
          hostname: typeof window !== 'undefined' ? window.location.hostname : 'server',
          matricule
        });
        
        // 🎭 Mode démo : utiliser les données fictives pour l'ID demo
        if (isDemoMode && matricule === 'demo-sal-001') {
          console.log('🎭 Demo mode detected, loading demo salarie...');
          
          const DEMO_SALARIE: SalarieDetail = {
            matricule: "demo-sal-001",
            civilite: "Mme",
            prenom: "Alice",
            nom_naissance: "MARTIN",
            nom_usage: "MARTIN",
            pseudo: "Alice M.",
            date_naissance: "1990-05-15",
            lieu_naissance: "Paris (75)",
            email: "alice.martin@demo.fr",
            telephone: "06 12 34 56 78",
            adresse: "123 Rue de la Comédie, 75001 Paris",
            nir: "2900515751234",
            conges_spectacles: "12345678901",
            iban: "FR76 3000 3000 0000 0000 0000 123",
            bic: "SOGEFRPP",
            transat_connecte: true,
            justificatifs: "RIB et pièce d'identité fournis",
            mineur_moins_16: false,
            resident_fr: true,
            rib_pdf: "/demo/rib-demo.pdf"
          };
          
          console.log('✅ Demo salarie loaded');
          setSalarie(DEMO_SALARIE);
          setLoading(false);
          return;
        }
        
        console.log(`🔍 Fetching salarie: ${matricule}`);
        
        const response = await fetch(`/api/salaries/${matricule}`, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Accept': 'application/json',
            'Cache-Control': 'no-cache',
          },
        });

        if (!response.ok) {
          const errorText = await response.text();
          console.error(`❌ API Error: ${response.status}`, errorText);
          throw new Error(`Erreur ${response.status}: ${errorText}`);
        }

        const data = await response.json();
        console.log('✅ Salarie data received:', data);
        setSalarie(data);
      } catch (err) {
        console.error('❌ Fetch error:', err);
        setError(err instanceof Error ? err.message : 'Erreur inconnue');
      } finally {
        setLoading(false);
      }
    };

    fetchSalarie();
  }, [matricule]);

  // Fonction pour récupérer les contrats
  const fetchContrats = async () => {
    if (!matricule) return;
    
    try {
      setContratsLoading(true);
      setContratsError(null);
      
      // 🎭 Détection directe du mode démo
      const isDemoMode = typeof window !== 'undefined' && window.location.hostname === 'demo.odentas.fr';
      
      console.log('🔍 fetchContrats debug:', {
        isDemoMode,
        hostname: typeof window !== 'undefined' ? window.location.hostname : 'server',
        matricule,
        year,
        page
      });
      
      // 🎭 Mode démo : utiliser les données fictives pour l'ID demo
      if (isDemoMode && matricule === 'demo-sal-001') {
        console.log('🎭 Demo mode detected, loading demo contrats...');
        
        const DEMO_CONTRATS: ContratListItem[] = [
          {
            id: "demo-cont-001",
            reference: "DEMO-2024-001",
            profession: "04201 - Comédien",
            date_debut: "2024-01-15",
            date_fin: "2024-06-30",
            is_multi_mois: true,
            regime: "CDDU_MULTI"
          },
          {
            id: "demo-cont-002",
            reference: "DEMO-2024-002",
            profession: "04201 - Comédien",
            date_debut: "2024-07-05",
            date_fin: "2024-07-28",
            is_multi_mois: false,
            regime: "CDDU_MONO"
          },
          {
            id: "demo-cont-003",
            reference: "DEMO-2023-015",
            profession: "04201 - Comédien",
            date_debut: "2023-09-01",
            date_fin: "2023-12-20",
            is_multi_mois: true,
            regime: "CDDU_MULTI"
          }
        ];
        
        // Filtrer par année
        const filteredContrats = DEMO_CONTRATS.filter(contrat => {
          if (!contrat.date_debut) return true;
          const contractYear = new Date(contrat.date_debut).getFullYear();
          return contractYear === year;
        });
        
        console.log('✅ Demo contrats loaded:', filteredContrats.length, 'for year', year);
        
        setContrats(filteredContrats);
        setHasMore(false); // Pas de pagination pour les données demo
        setContratsLoading(false);
        return;
      }
      
      console.log(`🔍 Fetching contrats for ${matricule}, year ${year}, page ${page}`);
      
      const response = await fetch(`/api/salaries/${matricule}/contrats?year=${year}&page=${page}&limit=${limit}`, {
        method: 'GET',
        credentials: 'include',
        headers: {
          'Accept': 'application/json',
          'Cache-Control': 'no-cache',
        },
      });

      if (!response.ok) {
        const errorText = await response.text();
        console.error(`❌ Contrats API Error: ${response.status}`, errorText);
        throw new Error(`Erreur ${response.status}: ${errorText}`);
      }

      const data: ContratsResponse = await response.json();
      console.log('✅ Contrats data received:', data);
      
      setContrats(data.items || []);
      setHasMore(data.hasMore || false);
    } catch (err) {
      console.error('❌ Fetch contrats error:', err);
      setContratsError(err instanceof Error ? err.message : 'Erreur inconnue');
    } finally {
      setContratsLoading(false);
    }
  };

  // Effect pour récupérer les contrats
  useEffect(() => {
    fetchContrats();
  }, [matricule, year, page]);

  // Affichage conditionnel basé sur l'état
  if (!matricule) {
    return (
      <div className="flex items-center justify-center min-h-[200px]">
        <div className="text-center">
          <p className="text-slate-500">Matricule non fourni</p>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[200px]">
        <div className="text-center">
          <Loader2 className="w-6 h-6 animate-spin mx-auto mb-2" />
          <p className="text-slate-500">Chargement du salarié...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-5">
        <div className="flex items-center gap-2">
          <Link href="/salaries" className="inline-flex items-center gap-1 text-sm underline">
            <ArrowLeft className="w-4 h-4" /> Retour
          </Link>
        </div>
        <div className="rounded-2xl border bg-rose-50 p-4">
          <h3 className="font-medium text-rose-800 mb-2">
            Erreur lors du chargement
          </h3>
          <p className="text-rose-700 text-sm">
            {error}
          </p>
          <button 
            onClick={() => window.location.reload()} 
            className="mt-3 px-3 py-1 bg-rose-100 text-rose-800 rounded text-sm hover:bg-rose-200"
          >
            Réessayer
          </button>
        </div>
      </div>
    );
  }

  if (!salarie) {
    return (
      <div className="space-y-5">
        <div className="flex items-center gap-2">
          <Link href="/salaries" className="inline-flex items-center gap-1 text-sm underline">
            <ArrowLeft className="w-4 h-4" /> Retour
          </Link>
        </div>
        <div className="text-center py-10">
          <p className="text-slate-500">Salarié non trouvé</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-5">
      {/* Navigation */}
      <div className="flex items-center gap-2">
        <Link href="/salaries" className="inline-flex items-center gap-1 text-sm underline">
          <ArrowLeft className="w-4 h-4" /> Retour
        </Link>
        <div className="ml-auto text-sm text-slate-500">Fiche salarié·e</div>
      </div>

      {/* Titre */}
      <div className="rounded-2xl border bg-white p-4">
        <div className="flex flex-wrap items-center gap-3">
          <div className="text-lg font-semibold">
            {formatValue(salarie.nom_usage).toUpperCase()} {formatValue(salarie.prenom)}
          </div>
          <div className="text-sm text-slate-500">Matricule : {matricule}</div>

          {/* Spacer pour pousser le bouton à droite */}
          <div className="ml-auto" />

          <button
            type="button"
            onClick={() => setNewContratOpen(true)}
            className="inline-flex items-center gap-2 px-3 py-2 rounded-lg text-sm text-white border-transparent bg-[#019669] hover:opacity-90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#019669]"
            title="Créer un nouveau contrat"
          >
            + Nouveau contrat
          </button>
        </div>
      </div>

      {/* Grille : Informations / Contrats */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        {/* Colonne gauche : Informations du salarié */}
        <Section title="Informations du salarié">
          <div className="space-y-2">
            <Field label="Matricule" value={salarie.matricule} />
            <Field label="Civilité" value={formatValue(salarie.civilite)} />
            <Field label="Prénom" value={formatValue(salarie.prenom)} />
            <Field label="Nom d'usage" value={formatValue(salarie.nom_usage)} />
            <Field label="Nom de naissance" value={formatValue(salarie.nom_naissance)} />
            <Field label="Pseudonyme" value={formatValue(salarie.pseudo)} />
            <Field label="Date de naissance" value={formatDateFR(salarie.date_naissance)} />
            <Field label="Lieu de naissance" value={formatValue(salarie.lieu_naissance)} />
            <Field label="Adresse email" value={formatValue(salarie.email)} />
            <Field label="Téléphone" value={formatValue(salarie.telephone)} />
            <Field label="Adresse" value={formatValue(salarie.adresse)} />
            <Field label="NIR" value={formatValue(salarie.nir)} />
            <Field label="Congés Spectacles" value={formatValue(salarie.conges_spectacles)} />
            <Field label="IBAN" value={formatValue(salarie.iban)} />
            <Field label="BIC" value={formatValue(salarie.bic)} />
            <Field label="Justificatifs" value={formatValue(salarie.justificatifs)} />
            
            <div className="pt-3 border-t">
              <Field 
                label="Espace Transat" 
                value={salarie.transat_connecte !== undefined 
                  ? (salarie.transat_connecte ? "Connecté" : "Non connecté") 
                  : "—"
                } 
              />
              <Field 
                label="Mineur < 16 ans" 
                value={salarie.mineur_moins_16 !== undefined 
                  ? (salarie.mineur_moins_16 ? "Oui" : "Non") 
                  : "—"
                } 
              />
              <Field 
                label="Résident français" 
                value={salarie.resident_fr !== undefined 
                  ? (salarie.resident_fr ? "Oui" : "Non") 
                  : "—"
                } 
              />
            </div>
          </div>
        </Section>

        {/* Colonne droite : Contrats du salarié */}
        <Section title="Contrats du salarié">
          {/* Filtres année + pagination */}
          <div className="flex flex-col sm:flex-row sm:items-center gap-3 mb-3">
            <div className="flex items-center gap-2">
              <span className="text-sm text-slate-600">Année :</span>
              <select
                value={year}
                onChange={(e) => {
                  setYear(parseInt(e.target.value, 10));
                  setPage(1);
                }}
                className="px-3 py-2 rounded-lg border bg-white text-sm"
              >
                {yearOptions.map((y) => (
                  <option key={y} value={y}>
                    {y}
                  </option>
                ))}
              </select>
            </div>

            <div className="sm:ml-auto flex items-center gap-2">
              <button
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1 || contratsLoading}
                className="px-2 py-1 rounded-lg border disabled:opacity-40"
                title="Page précédente"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
              <div className="text-sm">Page <strong>{page}</strong></div>
              <button
                onClick={() => setPage((p) => p + 1)}
                disabled={!hasMore || contratsLoading}
                className="px-2 py-1 rounded-lg border disabled:opacity-40"
                title="Page suivante"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
              <div className="ml-2 text-sm text-slate-500">
                {contratsLoading ? "Mise à jour…" : `${contrats.length} élément${contrats.length > 1 ? "s" : ""}${hasMore ? " (plus disponibles)" : ""}`}
              </div>
            </div>
          </div>

          {/* Grille des contrats */}
          <div className="space-y-3">
            {contratsError ? (
              <div className="p-6 text-center text-rose-600 bg-rose-50 rounded-xl">
                <p>Erreur lors du chargement des contrats</p>
                <button 
                  onClick={fetchContrats} 
                  className="mt-2 px-3 py-1 bg-rose-100 text-rose-800 rounded text-sm hover:bg-rose-200"
                >
                  Réessayer
                </button>
              </div>
            ) : contrats.length === 0 && !contratsLoading ? (
              <div className="p-6 text-center text-slate-500 bg-slate-50 rounded-xl">
                Aucun contrat pour {year}.
              </div>
            ) : (
              contrats.map((c) => (
                <Link
                  key={c.id}
                  href={hrefContrat(c)}
                  className="block p-4 border rounded-xl bg-gray-50 hover:shadow-md transition-shadow focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <h3 className="text-lg font-semibold">{c.reference}</h3>
                  <div className="flex flex-wrap items-center gap-2 mt-1">
                    {c.profession && (
                      <span className="inline-block px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                        {c.profession}
                      </span>
                    )}
                    {c.regime && (
                      <span className="inline-block px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600">
                        {c.regime === 'CDDU_MULTI' ? 'Multi-mois' : c.regime === 'CDDU_MONO' ? 'Mono-mois' : c.regime}
                      </span>
                    )}
                  </div>
                  <div className="flex flex-col sm:flex-row gap-1 sm:gap-4 mt-2">
                    <span className="flex items-center text-sm text-slate-600">
                      <svg className="w-4 h-4 mr-1 stroke-current" fill="none" viewBox="0 0 24 24">
                        <rect x="3" y="4" width="18" height="16" rx="2"/>
                        <path d="M7 2v2M17 2v2M3 10h18"/>
                      </svg>
                      Début : {formatDateFR(c.date_debut)}
                    </span>
                    <span className="flex items-center text-sm text-slate-600">
                      <svg className="w-4 h-4 mr-1 stroke-current" fill="none" viewBox="0 0 24 24">
                        <rect x="3" y="4" width="18" height="16" rx="2"/>
                        <path d="M7 2v2M17 2v2M3 10h18"/>
                      </svg>
                      Fin : {formatDateFR(c.date_fin)}
                    </span>
                  </div>
                </Link>
              ))
            )}
          </div>
        </Section>
      </div>
      {newContratOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          {/* Backdrop */}
          <div
            className="absolute inset-0 bg-black/50"
            onClick={() => setNewContratOpen(false)}
          />

          {/* Modal */}
          <div className="relative z-10 w-full max-w-md rounded-2xl border bg-white p-5 shadow-xl">
            <div className="text-base font-medium mb-1">Créer un nouveau contrat</div>
            <p className="text-sm text-slate-500 mb-4">
              Pour quel type de contrat souhaitez-vous procéder ?
            </p>

            <div className="grid grid-cols-1 gap-3">
              <button
                type="button"
                onClick={() => {
                  setNewContratOpen(false);
                  router.push(`/contrats/nouveau?salarie=${encodeURIComponent(matricule)}`);
                }}
                className="w-full px-3 py-2 rounded-lg border text-sm hover:bg-slate-50 text-left"
              >
                CDDU
                <div className="text-xs text-slate-500">Contrat à durée déterminée d'usage</div>
              </button>

              <button
                type="button"
                onClick={() => {
                  // Non fonctionnel pour l'instant
                  setNewContratOpen(false);
                }}
                className="w-full px-3 py-2 rounded-lg border text-sm opacity-70 cursor-not-allowed text-left"
                title="Bientôt disponible"
                disabled
              >
                Régime général
                <div className="text-xs text-slate-500">Bientôt disponible</div>
              </button>
            </div>

            <div className="mt-4 flex justify-end">
              <button
                type="button"
                onClick={() => setNewContratOpen(false)}
                className="text-sm px-3 py-2 rounded-lg border"
              >
                Annuler
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
