// components/staff/SalarieModal.tsx
"use client";

import { useState, useEffect } from "react";
import { X, Save, User, Mail, Phone, MapPin, CreditCard, Briefcase, Settings, Calendar, UserCheck } from "lucide-react";
import { toast } from "sonner";

type Salarie = {
  id: string;
  code_salarie?: string | null;
  num_salarie?: number | null;
  nom?: string | null;
  nom_de_naissance?: string | null;
  prenom?: string | null;
  salarie?: string | null;
  civilite?: string | null;
  pseudonyme?: string | null;
  date_naissance?: string | null;
  lieu_de_naissance?: string | null;
  adresse_mail?: string | null;
  tel?: string | null;
  adresse?: string | null;
  nir?: string | null;
  iban?: string | null;
  bic?: string | null;
  derniere_profession?: string | null;
  employer_id?: string | null;
  infos_caisses_organismes?: string | null;
  conges_spectacles?: string | null;
  abattement_2024?: string | null;
  compte_transat?: string | null;
  topaze?: string | null;
  justificatifs_personnels?: string | null;
  rf_au_sens_fiscal?: boolean | null;
  intermittent_mineur_16?: boolean | null;
  notif_nouveau_salarie?: string | null;
  notif_employeur?: string | null;
  created_at?: string | null;
  updated_at?: string | null;
};

interface SalarieModalProps {
  isOpen: boolean;
  onClose: () => void;
  salarie: Salarie | null;
  onUpdate: (updatedSalarie: Salarie) => void;
}

export default function SalarieModal({ isOpen, onClose, salarie, onUpdate }: SalarieModalProps) {
  const [formData, setFormData] = useState<Salarie | null>(null);
  const [saving, setSaving] = useState(false);
  const [activeTab, setActiveTab] = useState("personal");

  useEffect(() => {
    if (salarie && isOpen) {
      setFormData({ ...salarie });
      setActiveTab("personal");
    }
  }, [salarie, isOpen]);

  const handleSave = async () => {
    if (!formData) return;

    setSaving(true);
    try {
      const res = await fetch(`/api/staff/salaries/update`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      if (!res.ok) {
        const error = await res.json().catch(() => ({}));
        throw new Error(error?.error || "Erreur de sauvegarde");
      }

      onUpdate(formData);
      toast.success("Salarié mis à jour avec succès");
      onClose();
    } catch (error: any) {
      console.error("Erreur sauvegarde:", error);
      toast.error(error.message || "Erreur lors de la sauvegarde");
    } finally {
      setSaving(false);
    }
  };

  const updateField = (field: keyof Salarie, value: any) => {
    if (!formData) return;
    setFormData({ ...formData, [field]: value });
  };

  if (!isOpen || !formData) return null;

  const fullName = formData.salarie || [formData.nom, formData.prenom].filter(Boolean).join(" ").trim() || formData.nom || "";

  const tabs = [
    { id: "personal", label: "Personnel", icon: User },
    { id: "contact", label: "Contact", icon: Mail },
    { id: "banking", label: "Bancaire", icon: CreditCard },
    { id: "professional", label: "Professionnel", icon: Briefcase },
    { id: "technical", label: "Technique", icon: Settings },
  ];

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-4xl h-[85vh] flex flex-col overflow-hidden">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b flex-shrink-0">
          <div>
            <h2 className="text-xl font-semibold text-slate-900">
              Informations personnelles
            </h2>
            <p className="text-sm text-slate-600">{fullName}</p>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-slate-100 rounded-full transition-colors"
          >
            <X className="size-5" />
          </button>
        </div>

        {/* Tabs */}
        <div className="flex overflow-x-auto bg-slate-50 flex-shrink-0">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex items-center gap-2 px-4 py-3 text-sm font-medium whitespace-nowrap transition-colors ${
                activeTab === tab.id
                  ? "text-blue-600 border-b-2 border-blue-600"
                  : "text-slate-600 hover:text-slate-900"
              }`}
            >
              <tab.icon className="size-4" />
              {tab.label}
            </button>
          ))}
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto">
          <div className="p-6 min-h-full">
            {activeTab === "personal" && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Nom</label>
                  <input
                    type="text"
                    value={formData.nom || ""}
                    onChange={(e) => updateField("nom", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Nom de naissance</label>
                  <input
                    type="text"
                    value={formData.nom_de_naissance || ""}
                    onChange={(e) => updateField("nom_de_naissance", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Prénom</label>
                  <input
                    type="text"
                    value={formData.prenom || ""}
                    onChange={(e) => updateField("prenom", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Civilité</label>
                  <select
                    value={formData.civilite || ""}
                    onChange={(e) => updateField("civilite", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">Sélectionner</option>
                    <option value="Monsieur">Monsieur</option>
                    <option value="Madame">Madame</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Pseudonyme</label>
                  <input
                    type="text"
                    value={formData.pseudonyme || ""}
                    onChange={(e) => updateField("pseudonyme", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Date de naissance</label>
                  <input
                    type="date"
                    value={formData.date_naissance?.slice(0, 10) || ""}
                    onChange={(e) => updateField("date_naissance", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-slate-700 mb-1">Lieu de naissance</label>
                  <input
                    type="text"
                    value={formData.lieu_de_naissance || ""}
                    onChange={(e) => updateField("lieu_de_naissance", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>
            )}

            {activeTab === "contact" && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Email</label>
                  <input
                    type="email"
                    value={formData.adresse_mail || ""}
                    onChange={(e) => updateField("adresse_mail", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Téléphone</label>
                  <input
                    type="tel"
                    value={formData.tel || ""}
                    onChange={(e) => updateField("tel", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-slate-700 mb-1">Adresse</label>
                  <textarea
                    value={formData.adresse || ""}
                    onChange={(e) => updateField("adresse", e.target.value)}
                    rows={3}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">NIR</label>
                  <input
                    type="text"
                    value={formData.nir || ""}
                    onChange={(e) => updateField("nir", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 font-mono"
                  />
                </div>
              </div>
            )}

            {activeTab === "banking" && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">IBAN</label>
                  <input
                    type="text"
                    value={formData.iban || ""}
                    onChange={(e) => updateField("iban", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 font-mono"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">BIC</label>
                  <input
                    type="text"
                    value={formData.bic || ""}
                    onChange={(e) => updateField("bic", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 font-mono"
                  />
                </div>
              </div>
            )}

            {activeTab === "professional" && (
              <div className="grid grid-cols-1 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Congés spectacles</label>
                  <input
                    type="text"
                    value={formData.conges_spectacles || ""}
                    onChange={(e) => updateField("conges_spectacles", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Compte Transat</label>
                  <select
                    value={formData.compte_transat || ""}
                    onChange={(e) => updateField("compte_transat", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">Sélectionner</option>
                    <option value="Connecté">Connecté</option>
                    <option value="Non connecté">Non connecté</option>
                    <option value="En attente">En attente</option>
                  </select>
                </div>
                <div className="flex items-center gap-3">
                  <input
                    type="checkbox"
                    id="rf_fiscal"
                    checked={formData.rf_au_sens_fiscal || false}
                    onChange={(e) => updateField("rf_au_sens_fiscal", e.target.checked)}
                    className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                  />
                  <label htmlFor="rf_fiscal" className="text-sm font-medium text-slate-700">RF au sens fiscal</label>
                </div>
                <div className="flex items-center gap-3">
                  <input
                    type="checkbox"
                    id="mineur16"
                    checked={formData.intermittent_mineur_16 || false}
                    onChange={(e) => updateField("intermittent_mineur_16", e.target.checked)}
                    className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                  />
                  <label htmlFor="mineur16" className="text-sm font-medium text-slate-700">Intermittent mineur -16 ans</label>
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Informations caisses/organismes</label>
                  <input
                    type="text"
                    value={formData.infos_caisses_organismes || ""}
                    disabled
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg bg-slate-50 text-slate-500"
                  />
                </div>
              </div>
            )}

            {activeTab === "technical" && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Code salarié</label>
                  <input
                    type="text"
                    value={formData.code_salarie || ""}
                    onChange={(e) => updateField("code_salarie", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 font-mono"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Numéro salarié</label>
                  <input
                    type="number"
                    value={formData.num_salarie || ""}
                    onChange={(e) => updateField("num_salarie", e.target.value ? parseInt(e.target.value) : null)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 font-mono"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">ID Employeur</label>
                  <input
                    type="text"
                    value={formData.employer_id || ""}
                    onChange={(e) => updateField("employer_id", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 font-mono"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Justificatifs personnels</label>
                  <input
                    type="text"
                    value={formData.justificatifs_personnels || ""}
                    onChange={(e) => updateField("justificatifs_personnels", e.target.value)}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Créé le</label>
                  <input
                    type="text"
                    value={formData.created_at ? new Date(formData.created_at).toLocaleString('fr-FR') : ""}
                    disabled
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg bg-slate-50 text-slate-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Modifié le</label>
                  <input
                    type="text"
                    value={formData.updated_at ? new Date(formData.updated_at).toLocaleString('fr-FR') : ""}
                    disabled
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg bg-slate-50 text-slate-500"
                  />
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 p-6 border-t flex-shrink-0">
          <button
            onClick={onClose}
            className="px-4 py-2 text-sm font-medium text-slate-700 hover:bg-slate-100 rounded-lg transition-colors"
          >
            Annuler
          </button>
          <button
            onClick={handleSave}
            disabled={saving}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white rounded-lg font-medium transition-colors"
          >
            <Save className="size-4" />
            {saving ? "Sauvegarde..." : "Sauvegarder"}
          </button>
        </div>
      </div>
    </div>
  );
}