"use client";

import { useState, useMemo } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { 
  Loader2, 
  Plus, 
  Edit2, 
  Trash2, 
  X, 
  Save,
  Building2,
  Calendar,
  Bell,
  CheckCircle2,
  Mail
} from "lucide-react";
import CotisationsGrid from "@/components/staff/CotisationsGrid";

/* ================
   Types
   ================ */

// Structure d'une cotisation dans monthly_contributions
type Cotisation = {
  id: string;
  org_id: string;
  fund: string; // URSSAF, FTS, Audiens Retraite, etc.
  contrib_type: string | null;
  reference: string | null;
  period_label: string; // ex: "Août 2025 Int."
  due_date: string | null;
  paid_date: string | null;
  status: string; // "Fait", "En retard", "À payer"
  amount_due: number;
  amount_paid: number | null;
  amount_diff: number | null;
  notes: string | null;
  created_at: string;
};

type Organization = {
  id: string;
  name: string;
  code_employeur?: string | null;
};

// Structure regroupée pour l'affichage
type PeriodRow = {
  org_id: string;
  org_name: string;
  period_label: string;
  due_date: string | null;
  status: string;
  funds: {
    [fundName: string]: {
      id: string;
      amount_due: number;
      amount_paid: number | null;
      amount_diff: number | null;
      paid_date: string | null;
      notes: string | null;
    };
  };
  total_due: number;
  total_paid: number;
  is_notified?: boolean;
  notification_date?: string | null;
};

/* ================
   Helpers
   ================ */

const EURO = new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" });

// Liste des caisses (colonnes du tableau)
// Utiliser les noms exacts de la colonne 'fund' dans Supabase (MAJUSCULES avec underscores)
const FUNDS = [
  { key: "URSSAF", label: "URSSAF" },
  { key: "PE_SPECTACLE", label: "France Travail Spectacle" },
  { key: "AUDIENS_RETRAITE", label: "Audiens Retraite" },
  { key: "AUDIENS_PREVOYANCE", label: "Audiens Prévoyance" },
  { key: "CONGES_SPECTACLES", label: "Congés Spectacles" },
  { key: "PREVOYANCE_RG", label: "Prévoyance RG" },
  { key: "MUTUELLE_RG", label: "Mutuelle RG" },
  { key: "PAS", label: "PAS" },
];

/* ================
   Data Fetching
   ================ */

function useStaffCheck() {
  return useQuery({
    queryKey: ["staff-check"],
    queryFn: async () => {
      const res = await fetch("/api/me");
      if (!res.ok) return { isStaff: false };
      const data = await res.json();
      return { isStaff: Boolean(data.is_staff || data.isStaff) };
    },
    staleTime: 30_000,
  });
}

function useOrganizations() {
  return useQuery({
    queryKey: ["staff-organizations"],
    queryFn: async () => {
      const res = await fetch("/api/staff/organizations");
      if (!res.ok) throw new Error("Erreur lors du chargement des organisations");
      const data = await res.json();
      return (data.organizations || []) as Organization[];
    },
  });
}

function useCotisations(orgId?: string, year?: number) {
  return useQuery({
    queryKey: ["staff-cotisations", orgId, year],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (orgId) params.set("org_id", orgId);
      if (year) params.set("year", String(year));
      
      const res = await fetch(`/api/staff/cotisations?${params.toString()}`);
      if (!res.ok) throw new Error("Erreur lors du chargement des cotisations");
      const data = await res.json();
      return (data.cotisations || []) as Cotisation[];
    },
  });
}

type ContributionNotification = {
  id: string;
  org_id: string;
  period_label: string;
  notified_at: string;
  notified_by: string;
  email_sent_to: string;
  email_cc: string | null;
};

function useNotifications(orgId?: string, year?: number) {
  return useQuery({
    queryKey: ["staff-contribution-notifications", orgId, year],
    queryFn: async () => {
      const params = new URLSearchParams();
      if (orgId) params.set("org_id", orgId);
      if (year) params.set("year", String(year));
      
      const res = await fetch(`/api/staff/cotisations/notifications?${params.toString()}`);
      if (!res.ok) throw new Error("Erreur lors du chargement des notifications");
      const data = await res.json();
      return (data.notifications || []) as ContributionNotification[];
    },
  });
}

/* ================
   Modal d'édition d'une cellule
   ================ */

type CellModalProps = {
  cotisation: {
    id: string;
    org_id: string;
    org_name: string;
    period_label: string;
    fund: string;
    amount_due: number;
    amount_paid: number | null;
    amount_diff: number | null;
    paid_date: string | null;
    due_date: string | null;
    status: string;
    notes: string | null;
  } | null;
  onClose: () => void;
  onSave: (id: string, updates: Partial<Cotisation>) => Promise<void>;
};

function CellEditModal({ cotisation, onClose, onSave }: CellModalProps) {
  const [amountDue, setAmountDue] = useState(cotisation?.amount_due?.toString() || "");
  const [amountPaid, setAmountPaid] = useState(cotisation?.amount_paid?.toString() || "");
  const [paidDate, setPaidDate] = useState(cotisation?.paid_date || "");
  const [dueDate, setDueDate] = useState(cotisation?.due_date || "");
  const [periodLabel, setPeriodLabel] = useState(cotisation?.period_label || "");
  const [status, setStatus] = useState(cotisation?.status || "À payer");
  const [notes, setNotes] = useState(cotisation?.notes || "");
  const [markAsNotified, setMarkAsNotified] = useState(false);
  const [saving, setSaving] = useState(false);

  if (!cotisation) return null;

  const handleSave = async () => {
    setSaving(true);
    try {
      const updates: Partial<Cotisation> & { mark_as_notified?: boolean } = {
        amount_due: parseFloat(amountDue) || 0,
        amount_paid: amountPaid ? parseFloat(amountPaid) : null,
        paid_date: paidDate || null,
        due_date: dueDate || null,
        period_label: periodLabel,
        status,
        notes: notes || null,
      };
      
      // Calcul automatique de amount_diff
      const due = parseFloat(amountDue) || 0;
      const paid = amountPaid ? parseFloat(amountPaid) : null;
      updates.amount_diff = paid !== null ? due - paid : null;
      
      // Ajouter le marquage manuel de notification
      if (markAsNotified) {
        updates.mark_as_notified = true;
      }
      
      await onSave(cotisation.id, updates);
      onClose();
    } catch (error) {
      console.error("Erreur lors de la sauvegarde:", error);
      alert("Erreur lors de la sauvegarde");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="sticky top-0 bg-gradient-to-r from-purple-600 to-blue-600 text-white px-6 py-4 flex items-center justify-between rounded-t-2xl">
          <div>
            <h2 className="text-xl font-semibold">Modifier la cotisation</h2>
            <p className="text-sm text-purple-100 mt-1">
              {cotisation.org_name} · {cotisation.period_label} · {cotisation.fund}
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-white hover:bg-white/20 rounded-lg p-2 transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Body */}
        <div className="p-6 space-y-6">
          {/* Période et échéance */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Période *
              </label>
              <input
                type="text"
                value={periodLabel}
                onChange={(e) => setPeriodLabel(e.target.value)}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                placeholder="Ex: Août 2025 Int."
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Date d'échéance
              </label>
              <input
                type="date"
                value={dueDate}
                onChange={(e) => setDueDate(e.target.value)}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              />
            </div>
          </div>

          {/* Montants */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Montant dû *
              </label>
              <input
                type="number"
                step="0.01"
                value={amountDue}
                onChange={(e) => setAmountDue(e.target.value)}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                placeholder="0.00"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Montant payé
              </label>
              <input
                type="number"
                step="0.01"
                value={amountPaid}
                onChange={(e) => setAmountPaid(e.target.value)}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                placeholder="0.00"
              />
            </div>
          </div>

          {/* Dates et statut */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Date de paiement
              </label>
              <input
                type="date"
                value={paidDate}
                onChange={(e) => setPaidDate(e.target.value)}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Statut *
              </label>
              <select
                value={status}
                onChange={(e) => setStatus(e.target.value)}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              >
                <option value="À payer">À payer</option>
                <option value="En retard">En retard</option>
                <option value="Fait">Fait</option>
              </select>
            </div>
          </div>

          {/* Marquer comme notifié */}
          <div className="border-t pt-4">
            <label className="flex items-center gap-3 cursor-pointer group">
              <input
                type="checkbox"
                checked={markAsNotified}
                onChange={(e) => setMarkAsNotified(e.target.checked)}
                className="w-5 h-5 text-purple-600 border-slate-300 rounded focus:ring-2 focus:ring-purple-500 cursor-pointer"
              />
              <div className="flex items-center gap-2">
                <Bell className="w-4 h-4 text-slate-600 group-hover:text-purple-600 transition" />
                <span className="text-sm font-medium text-slate-700 group-hover:text-purple-600 transition">
                  Marquer cette période comme notifiée au client
                </span>
              </div>
            </label>
            <p className="text-xs text-slate-500 mt-2 ml-8">
              Cochez cette case si vous avez notifié le client manuellement (téléphone, email externe, etc.)
            </p>
          </div>

          {/* Notes */}
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              Notes
            </label>
            <textarea
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
              rows={3}
              className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent resize-none"
              placeholder="Remarques ou informations complémentaires..."
            />
          </div>
        </div>

        {/* Footer */}
        <div className="sticky bottom-0 bg-slate-50 px-6 py-4 flex items-center justify-end gap-3 rounded-b-2xl border-t">
          <button
            onClick={onClose}
            className="px-4 py-2 text-slate-700 hover:bg-slate-200 rounded-lg transition"
            disabled={saving}
          >
            Annuler
          </button>
          <button
            onClick={handleSave}
            disabled={saving || !amountDue}
            className="px-4 py-2 bg-gradient-to-r from-purple-600 to-blue-600 text-white rounded-lg hover:from-purple-700 hover:to-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 transition"
          >
            {saving ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Enregistrement...
              </>
            ) : (
              <>
                <Save className="w-4 h-4" />
                Enregistrer
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ================
   Modal de création d'une période complète
   ================ */

type CreatePeriodModalProps = {
  onClose: () => void;
  onCreate: (periodData: {
    org_id: string;
    period_label: string;
    due_date: string;
    status: string;
    funds: { fund: string; amount_due: number }[];
  }) => Promise<void>;
};

function CreatePeriodModal({ onClose, onCreate }: CreatePeriodModalProps) {
  const { data: organizations = [] } = useOrganizations();
  
  const [orgId, setOrgId] = useState("");
  const [periodLabel, setPeriodLabel] = useState("");
  const [dueDate, setDueDate] = useState("");
  const [status, setStatus] = useState("À payer");
  const [amounts, setAmounts] = useState<{ [fund: string]: string }>({});
  const [creating, setCreating] = useState(false);

  const handleCreate = async () => {
    if (!orgId || !periodLabel) {
      alert("Veuillez remplir tous les champs obligatoires");
      return;
    }

    setCreating(true);
    try {
      const funds = FUNDS.map(fundObj => ({
        fund: fundObj.key,
        amount_due: parseFloat(amounts[fundObj.key] || "0") || 0,
      }));
      // On garde toutes les caisses, même avec montant = 0
      // Utile pour les périodes sans paie ou pour garder la structure complète

      await onCreate({
        org_id: orgId,
        period_label: periodLabel,
        due_date: dueDate,
        status,
        funds,
      });
      onClose();
    } catch (error) {
      console.error("Erreur lors de la création:", error);
      alert("Erreur lors de la création");
    } finally {
      setCreating(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="sticky top-0 bg-gradient-to-r from-purple-600 to-blue-600 text-white px-6 py-4 flex items-center justify-between rounded-t-2xl">
          <div>
            <h2 className="text-xl font-semibold">Créer une nouvelle période</h2>
            <p className="text-sm text-purple-100 mt-1">
              Ajouter les cotisations pour toutes les caisses d'une période
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-white hover:bg-white/20 rounded-lg p-2 transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Body */}
        <div className="p-6 space-y-6">
          {/* Infos générales */}
          <div className="grid grid-cols-2 gap-4">
            <div className="col-span-2">
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Organisation *
              </label>
              <select
                value={orgId}
                onChange={(e) => setOrgId(e.target.value)}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              >
                <option value="">Sélectionner une organisation</option>
                {organizations.map((org) => (
                  <option key={org.id} value={org.id}>
                    {org.name}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Période *
              </label>
              <input
                type="text"
                value={periodLabel}
                onChange={(e) => setPeriodLabel(e.target.value)}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                placeholder="ex: Août 2025 Int."
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Date d'échéance
              </label>
              <input
                type="date"
                value={dueDate}
                onChange={(e) => setDueDate(e.target.value)}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              />
            </div>

            <div className="col-span-2">
              <label className="block text-sm font-medium text-slate-700 mb-2">
                Statut *
              </label>
              <select
                value={status}
                onChange={(e) => setStatus(e.target.value)}
                className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              >
                <option value="À payer">À payer</option>
                <option value="En retard">En retard</option>
                <option value="Fait">Fait</option>
              </select>
            </div>
          </div>

          {/* Montants par caisse */}
          <div>
            <h3 className="text-sm font-medium text-slate-700 mb-3">Montants par caisse</h3>
            <div className="grid grid-cols-2 gap-4">
              {FUNDS.map((fundObj) => (
                <div key={fundObj.key}>
                  <label className="block text-xs font-medium text-slate-600 mb-1">
                    {fundObj.label}
                  </label>
                  <input
                    type="number"
                    step="0.01"
                    value={amounts[fundObj.key] || ""}
                    onChange={(e) => setAmounts({ ...amounts, [fundObj.key]: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent text-sm"
                    placeholder="0.00"
                  />
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="sticky bottom-0 bg-slate-50 px-6 py-4 flex items-center justify-end gap-3 rounded-b-2xl border-t">
          <button
            onClick={onClose}
            className="px-4 py-2 text-slate-700 hover:bg-slate-200 rounded-lg transition"
            disabled={creating}
          >
            Annuler
          </button>
          <button
            onClick={handleCreate}
            disabled={creating || !orgId || !periodLabel}
            className="px-4 py-2 bg-gradient-to-r from-purple-600 to-blue-600 text-white rounded-lg hover:from-purple-700 hover:to-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 transition"
          >
            {creating ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Création...
              </>
            ) : (
              <>
                <Plus className="w-4 h-4" />
                Créer la période
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ================
   Modal de suppression d'une période complète
   ================ */

type DeletePeriodModalProps = {
  period: PeriodRow | null;
  onClose: () => void;
  onDelete: (ids: string[]) => Promise<void>;
};

function DeletePeriodModal({ period, onClose, onDelete }: DeletePeriodModalProps) {
  const [deleting, setDeleting] = useState(false);

  if (!period) return null;

  const handleDelete = async () => {
    setDeleting(true);
    try {
      const ids = Object.values(period.funds).map(f => f.id);
      await onDelete(ids);
      onClose();
    } catch (error) {
      console.error("Erreur lors de la suppression:", error);
      alert("Erreur lors de la suppression");
    } finally {
      setDeleting(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md">
        <div className="p-6 space-y-4">
          <div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mx-auto">
            <Trash2 className="w-6 h-6 text-red-600" />
          </div>
          
          <div className="text-center">
            <h3 className="text-lg font-semibold text-slate-900">
              Supprimer cette période ?
            </h3>
            <p className="text-sm text-slate-600 mt-2">
              {period.org_name} · {period.period_label}
            </p>
            <p className="text-sm text-slate-500 mt-2">
              Toutes les cotisations de cette période seront supprimées. Cette action est irréversible.
            </p>
          </div>

          <div className="flex items-center gap-3 pt-4">
            <button
              onClick={onClose}
              className="flex-1 px-4 py-2 text-slate-700 hover:bg-slate-100 rounded-lg transition"
              disabled={deleting}
            >
              Annuler
            </button>
            <button
              onClick={handleDelete}
              disabled={deleting}
              className="flex-1 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 transition"
            >
              {deleting ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  Suppression...
                </>
              ) : (
                <>
                  <Trash2 className="w-4 h-4" />
                  Supprimer
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ================
   Modal d'édition d'une période complète
   ================ */

type EditPeriodModalProps = {
  period: PeriodRow | null;
  onClose: () => void;
  onSave: (orgId: string, oldPeriodLabel: string, updates: {
    period_label: string;
    due_date: string;
    status: string;
  }) => Promise<void>;
};

function EditPeriodModal({ period, onClose, onSave }: EditPeriodModalProps) {
  const [periodLabel, setPeriodLabel] = useState(period?.period_label || "");
  const [dueDate, setDueDate] = useState(period?.due_date || "");
  const [status, setStatus] = useState(period?.status || "À payer");
  const [saving, setSaving] = useState(false);

  if (!period) return null;

  const handleSave = async () => {
    if (!periodLabel) {
      alert("Le libellé de période est obligatoire");
      return;
    }

    setSaving(true);
    try {
      await onSave(period.org_id, period.period_label, {
        period_label: periodLabel,
        due_date: dueDate,
        status,
      });
      onClose();
    } catch (error) {
      console.error("Erreur lors de la sauvegarde:", error);
      alert("Erreur lors de la sauvegarde");
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg">
        {/* Header */}
        <div className="sticky top-0 bg-gradient-to-r from-purple-600 to-blue-600 text-white px-6 py-4 flex items-center justify-between rounded-t-2xl">
          <div>
            <h2 className="text-xl font-semibold">Modifier la période</h2>
            <p className="text-sm text-purple-100 mt-1">
              {period.org_name} · {period.period_label}
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-white hover:bg-white/20 rounded-lg p-2 transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Body */}
        <div className="p-6 space-y-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              Libellé de période *
            </label>
            <input
              type="text"
              value={periodLabel}
              onChange={(e) => setPeriodLabel(e.target.value)}
              className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              placeholder="ex: Août 2025 Int."
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              Date d'échéance
            </label>
            <input
              type="date"
              value={dueDate}
              onChange={(e) => setDueDate(e.target.value)}
              className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              Statut *
            </label>
            <select
              value={status}
              onChange={(e) => setStatus(e.target.value)}
              className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            >
              <option value="À payer">À payer</option>
              <option value="En retard">En retard</option>
              <option value="Fait">Fait</option>
            </select>
          </div>

          <div className="text-xs text-slate-500 bg-blue-50 p-3 rounded-lg">
            Ces modifications seront appliquées à toutes les cotisations de cette période ({Object.keys(period.funds).length} caisse{Object.keys(period.funds).length > 1 ? 's' : ''}).
          </div>
        </div>

        {/* Footer */}
        <div className="sticky bottom-0 bg-slate-50 px-6 py-4 flex items-center justify-end gap-3 rounded-b-2xl border-t">
          <button
            onClick={onClose}
            className="px-4 py-2 text-slate-700 hover:bg-slate-200 rounded-lg transition"
            disabled={saving}
          >
            Annuler
          </button>
          <button
            onClick={handleSave}
            disabled={saving || !periodLabel}
            className="px-4 py-2 bg-gradient-to-r from-purple-600 to-blue-600 text-white rounded-lg hover:from-purple-700 hover:to-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 transition"
          >
            {saving ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Enregistrement...
              </>
            ) : (
              <>
                <Save className="w-4 h-4" />
                Enregistrer
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ================
   Modal de notification de cotisations
   ================ */

type NotifyContributionModalProps = {
  period: PeriodRow | null;
  orgDetails: {
    email_notifs: string | null;
    email_notifs_cc: string | null;
  } | null;
  isRenotification?: boolean;
  lastNotificationDate?: string;
  onClose: () => void;
  onConfirm: () => Promise<void>;
};

function NotifyContributionModal({ period, orgDetails, isRenotification, lastNotificationDate, onClose, onConfirm }: NotifyContributionModalProps) {
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);

  if (!period || !orgDetails) return null;

  // Fonction pour calculer la période de prélèvement
  const calculateCollectionPeriod = (periodLabel: string): string => {
    try {
      // Extraire le mois et l'année (ex: "Août 2025" ou "Août 2025 Int.")
      const match = periodLabel.match(/^([^\s]+)\s+(\d{4})/);
      if (!match) {
        return "Entre le 15 et le 30 du mois suivant";
      }

      const monthName = match[1];
      const year = parseInt(match[2]);
      
      // Mapping des mois français vers numéros
      const monthsMap: { [key: string]: number } = {
        'Janvier': 0, 'Février': 1, 'Mars': 2, 'Avril': 3,
        'Mai': 4, 'Juin': 5, 'Juillet': 6, 'Août': 7,
        'Septembre': 8, 'Octobre': 9, 'Novembre': 10, 'Décembre': 11
      };

      const monthIndex = monthsMap[monthName];
      if (monthIndex === undefined) {
        return "Entre le 15 et le 30 du mois suivant";
      }

      // Calculer le mois suivant
      const date = new Date(year, monthIndex, 1);
      date.setMonth(date.getMonth() + 1);
      
      const nextMonth = date.toLocaleDateString('fr-FR', { month: 'long' });
      const nextYear = date.getFullYear();
      
      return `Entre le 15 et le 30 ${nextMonth} ${nextYear}`;
    } catch (error) {
      return "Entre le 15 et le 30 du mois suivant";
    }
  };

  const collectionPeriod = calculateCollectionPeriod(period.period_label);

  const handleConfirm = async () => {
    setSending(true);
    try {
      await onConfirm();
      setSent(true);
      setTimeout(() => {
        onClose();
        setSent(false);
      }, 2000);
    } catch (error) {
      console.error("Erreur lors de l'envoi:", error);
      alert("Erreur lors de l'envoi de la notification");
    } finally {
      setSending(false);
    }
  };

  // Affichage de succès
  if (sent) {
    return (
      <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
        <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md">
          <div className="p-6 space-y-4">
            <div className="w-12 h-12 rounded-full bg-green-100 flex items-center justify-center mx-auto">
              <CheckCircle2 className="w-6 h-6 text-green-600" />
            </div>
            
            <div className="text-center">
              <h3 className="text-lg font-semibold text-slate-900">
                Notification envoyée !
              </h3>
              <p className="text-sm text-slate-600 mt-2">
                L'email a été envoyé avec succès
              </p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md">
        {/* Header */}
        <div className="sticky top-0 bg-gradient-to-r from-amber-500 to-orange-500 text-white px-6 py-4 flex items-center justify-between rounded-t-2xl">
          <div>
            <h2 className="text-xl font-semibold">Envoyer une notification</h2>
            <p className="text-sm text-amber-100 mt-1">
              Échéance de cotisations
            </p>
          </div>
          <button
            onClick={onClose}
            className="text-white hover:bg-white/20 rounded-lg p-2 transition"
            disabled={sending}
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Body */}
        <div className="p-6 space-y-4">
          <div className="text-center">
            <div className="w-12 h-12 rounded-full bg-amber-100 flex items-center justify-center mx-auto mb-3">
              <Bell className="w-6 h-6 text-amber-600" />
            </div>
            <p className="text-sm text-slate-600">
              {isRenotification 
                ? "Un nouvel email de rappel sera envoyé au client concernant les cotisations pour :" 
                : "Un email de rappel sera envoyé au client concernant les cotisations à venir pour :"}
            </p>
          </div>

          {isRenotification && lastNotificationDate && (
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
              <p className="text-xs text-blue-700">
                ℹ️ Déjà notifié le {new Date(lastNotificationDate).toLocaleDateString('fr-FR', { 
                  day: 'numeric', 
                  month: 'long', 
                  year: 'numeric',
                  hour: '2-digit', 
                  minute: '2-digit' 
                })}
              </p>
            </div>
          )}

          {/* Informations de la période */}
          <div className="bg-slate-50 rounded-lg p-4 space-y-2">
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium text-slate-700">Organisation :</span>
              <span className="text-sm text-slate-900 font-semibold">{period.org_name}</span>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium text-slate-700">Période :</span>
              <span className="text-sm text-slate-900 font-semibold">{period.period_label}</span>
            </div>
          </div>

          {/* Destinataires */}
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4 space-y-3">
            <div className="flex items-start gap-2">
              <Mail className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
              <div className="flex-1 min-w-0">
                <p className="text-xs font-medium text-blue-900 mb-1">Destinataire principal :</p>
                <p className="text-sm text-blue-700 break-all">
                  {orgDetails.email_notifs || "Non configuré"}
                </p>
              </div>
            </div>
            
            {orgDetails.email_notifs_cc && (
              <div className="flex items-start gap-2 pt-2 border-t border-blue-200">
                <Mail className="w-4 h-4 text-blue-600 mt-0.5 flex-shrink-0" />
                <div className="flex-1 min-w-0">
                  <p className="text-xs font-medium text-blue-900 mb-1">Copie (CC) :</p>
                  <p className="text-sm text-blue-700 break-all">
                    {orgDetails.email_notifs_cc}
                  </p>
                </div>
              </div>
            )}
          </div>

          {/* Contenu de l'email */}
          <div className="bg-slate-50 rounded-lg p-4">
            <p className="text-xs font-medium text-slate-700 mb-2">Contenu de l'email :</p>
            <p className="text-xs text-slate-600 leading-relaxed">
              • Période concernée : <strong>{period.period_label}</strong><br />
              • Date de prélèvement théorique : <strong>{collectionPeriod}</strong><br />
              {period.total_due === 0 ? (
                <>• Message : En l'absence de paie pour cette période, aucune cotisation ne sera prélevée</>
              ) : (
                <>• Message : Rappel des prélèvements de cotisations à venir</>
              )}
            </p>
          </div>

          {!orgDetails.email_notifs && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-3">
              <p className="text-xs text-red-700">
                ⚠️ Aucun email de notification configuré pour cette organisation
              </p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="sticky bottom-0 bg-slate-50 px-6 py-4 flex items-center justify-end gap-3 rounded-b-2xl border-t">
          <button
            onClick={onClose}
            className="px-4 py-2 text-slate-700 hover:bg-slate-200 rounded-lg transition"
            disabled={sending}
          >
            Annuler
          </button>
          <button
            onClick={handleConfirm}
            disabled={sending || !orgDetails.email_notifs}
            className="px-4 py-2 bg-gradient-to-r from-amber-500 to-orange-500 text-white rounded-lg hover:from-amber-600 hover:to-orange-600 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 transition"
          >
            {sending ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Envoi...
              </>
            ) : (
              <>
                <Bell className="w-4 h-4" />
                Envoyer la notification
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ================
   Page principale
   ================ */

export default function StaffGestionCotisationsPage() {
  const { data: staffCheck, isLoading: isLoadingStaff } = useStaffCheck();
  const queryClient = useQueryClient();
  const { data: organizations = [] } = useOrganizations();

  const now = new Date();
  const currentYear = now.getFullYear();
  const years = useMemo(() => {
    return Array.from({ length: 7 }, (_, i) => currentYear - i);
  }, [currentYear]);

  // Filtres
  const [selectedOrgId, setSelectedOrgId] = useState<string>("");
  const [selectedYear, setSelectedYear] = useState<number>(currentYear);

  // Modales - DOIVENT être déclarés avant tout return conditionnel
  const [editingCell, setEditingCell] = useState<{
    id: string;
    org_id: string;
    org_name: string;
    period_label: string;
    fund: string;
    amount_due: number;
    amount_paid: number | null;
    amount_diff: number | null;
    paid_date: string | null;
    due_date: string | null;
    status: string;
    notes: string | null;
  } | null>(null);
  const [creatingPeriod, setCreatingPeriod] = useState(false);
  const [deletingPeriod, setDeletingPeriod] = useState<PeriodRow | null>(null);
  const [editingPeriod, setEditingPeriod] = useState<PeriodRow | null>(null);
  const [notifyingPeriod, setNotifyingPeriod] = useState<PeriodRow | null>(null);
  const [notifyOrgDetails, setNotifyOrgDetails] = useState<{
    email_notifs: string | null;
    email_notifs_cc: string | null;
  } | null>(null);

  // Données
  const { data: cotisations = [], isLoading, isError } = useCotisations(
    selectedOrgId || undefined,
    selectedYear
  );

  // Récupérer les notifications
  const { data: notifications = [] } = useNotifications(
    selectedOrgId || undefined,
    selectedYear
  );

  // Mutations
  const updateMutation = useMutation({
    mutationFn: async ({ id, updates }: { id: string; updates: Partial<Cotisation> }) => {
      const res = await fetch(`/api/staff/cotisations/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(updates),
      });
      if (!res.ok) throw new Error("Erreur lors de la mise à jour");
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["staff-cotisations"] });
      queryClient.invalidateQueries({ queryKey: ["staff-contribution-notifications"] });
    },
  });

  const createMutation = useMutation({
    mutationFn: async (periodData: {
      org_id: string;
      period_label: string;
      due_date: string;
      status: string;
      funds: { fund: string; amount_due: number }[];
    }) => {
      // Créer une cotisation pour chaque caisse
      const promises = periodData.funds.map(({ fund, amount_due }) =>
        fetch("/api/staff/cotisations", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            org_id: periodData.org_id,
            period_label: periodData.period_label,
            fund,
            due_date: periodData.due_date,
            status: periodData.status,
            amount_due,
          }),
        })
      );
      await Promise.all(promises);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["staff-cotisations"] });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: async (ids: string[]) => {
      const promises = ids.map(id =>
        fetch(`/api/staff/cotisations/${id}`, { method: "DELETE" })
      );
      await Promise.all(promises);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["staff-cotisations"] });
    },
  });

  const updatePeriodMutation = useMutation({
    mutationFn: async ({
      org_id,
      old_period_label,
      updates,
    }: {
      org_id: string;
      old_period_label: string;
      updates: { period_label: string; due_date: string; status: string };
    }) => {
      const res = await fetch("/api/staff/cotisations/bulk-update", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ org_id, old_period_label, updates }),
      });
      if (!res.ok) throw new Error("Erreur lors de la mise à jour");
      return res.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["staff-cotisations"] });
    },
  });

  // Vérification staff - APRÈS tous les hooks
  if (isLoadingStaff) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader2 className="w-8 h-8 animate-spin text-purple-600" />
      </div>
    );
  }

  if (!staffCheck?.isStaff) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-slate-900 mb-2">Accès refusé</h1>
          <p className="text-slate-600">Cette page est réservée aux membres du staff.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6 max-w-full">
      {/* Header */}
      <div className="rounded-2xl border bg-white p-4 sm:p-6">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div className="min-w-0 flex-1">
            <h1 className="text-xl sm:text-2xl font-bold text-slate-900 break-words">Gestion des cotisations</h1>
            <p className="text-slate-600 mt-1 text-sm sm:text-base break-words">
              Visualisez et modifiez les cotisations par organisation et par période
            </p>
          </div>
        </div>
      </div>

      {/* Filtres rapides */}
      <div className="rounded-2xl border bg-white p-4 sm:p-6">
        <h2 className="text-lg font-semibold text-slate-900 mb-4">Filtres rapides</h2>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              <Building2 className="w-4 h-4 inline mr-2" />
              Organisation
            </label>
            <select
              value={selectedOrgId}
              onChange={(e) => setSelectedOrgId(e.target.value)}
              className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            >
              <option value="">Toutes les organisations</option>
              {organizations.map((org) => (
                <option key={org.id} value={org.id}>
                  {org.name}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">
              <Calendar className="w-4 h-4 inline mr-2" />
              Année
            </label>
            <select
              value={selectedYear}
              onChange={(e) => setSelectedYear(parseInt(e.target.value))}
              className="w-full px-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            >
              {years.map((year) => (
                <option key={year} value={year}>
                  {year}
                </option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Grille des cotisations */}
      {isLoading ? (
        <div className="py-12 text-center text-slate-500">
          <Loader2 className="w-6 h-6 inline animate-spin mr-2" />
          Chargement des cotisations...
        </div>
      ) : isError ? (
        <div className="py-8 text-center text-rose-600">
          Erreur lors du chargement des cotisations
        </div>
      ) : (
        <CotisationsGrid
          initialCotisations={cotisations}
          organizations={organizations}
          notifications={notifications}
          onEditCell={(cellData) => setEditingCell(cellData)}
          onEditPeriod={(period) => setEditingPeriod(period)}
          onNotifyPeriod={async (period) => {
            // Récupérer les détails de l'organisation via Supabase
            try {
              const firstFundId = Object.values(period.funds)[0]?.id;
              if (!firstFundId) {
                alert("Aucune cotisation disponible pour cette période");
                return;
              }

              const { createClientComponentClient } = await import('@supabase/auth-helpers-nextjs');
              const supabase = createClientComponentClient();
              
              const { data: orgDetails, error } = await supabase
                .from('organization_details')
                .select('email_notifs, email_notifs_cc')
                .eq('org_id', period.org_id)
                .single();

              if (error || !orgDetails) {
                console.error("Erreur:", error);
                setNotifyOrgDetails({
                  email_notifs: null,
                  email_notifs_cc: null,
                });
              } else {
                setNotifyOrgDetails({
                  email_notifs: orgDetails.email_notifs || null,
                  email_notifs_cc: orgDetails.email_notifs_cc || null,
                });
              }
              
              setNotifyingPeriod(period);
            } catch (error) {
              console.error("Erreur lors du chargement des détails:", error);
              alert("Erreur lors du chargement des informations de l'organisation");
            }
          }}
          onDeletePeriod={(period) => setDeletingPeriod(period)}
          onCreatePeriod={() => setCreatingPeriod(true)}
        />
      )}

      {/* Modales */}
      {editingCell && (
        <CellEditModal
          cotisation={editingCell}
          onClose={() => setEditingCell(null)}
          onSave={async (id, updates) => {
            await updateMutation.mutateAsync({ id, updates });
          }}
        />
      )}

      {creatingPeriod && (
        <CreatePeriodModal
          onClose={() => setCreatingPeriod(false)}
          onCreate={async (periodData) => {
            await createMutation.mutateAsync(periodData);
          }}
        />
      )}

      {deletingPeriod && (
        <DeletePeriodModal
          period={deletingPeriod}
          onClose={() => setDeletingPeriod(null)}
          onDelete={async (ids) => {
            await deleteMutation.mutateAsync(ids);
          }}
        />
      )}

      {editingPeriod && (
        <EditPeriodModal
          period={editingPeriod}
          onClose={() => setEditingPeriod(null)}
          onSave={async (orgId, oldPeriodLabel, updates) => {
            await updatePeriodMutation.mutateAsync({
              org_id: orgId,
              old_period_label: oldPeriodLabel,
              updates,
            });
          }}
        />
      )}

      {notifyingPeriod && notifyOrgDetails && (
        <NotifyContributionModal
          period={notifyingPeriod}
          orgDetails={notifyOrgDetails}
          isRenotification={notifyingPeriod.is_notified || false}
          lastNotificationDate={notifyingPeriod.notification_date || undefined}
          onClose={() => {
            setNotifyingPeriod(null);
            setNotifyOrgDetails(null);
          }}
          onConfirm={async () => {
            // Récupérer l'ID de la première cotisation pour appeler l'API
            const firstFundId = Object.values(notifyingPeriod.funds)[0]?.id;
            if (!firstFundId) {
              throw new Error("Aucune cotisation disponible");
            }

            const res = await fetch(`/api/staff/cotisations/${firstFundId}/notify-client`, {
              method: 'POST',
            });

            if (!res.ok) {
              const error = await res.json();
              throw new Error(error.error || "Erreur lors de l'envoi");
            }

            // Invalider les queries pour rafraîchir les données
            queryClient.invalidateQueries({ queryKey: ["staff-contribution-notifications"] });
          }}
        />
      )}
    </div>
  );
}
