"use client";

import { type FormEvent, useEffect, useState } from "react";

type Recipient = {
  id: number;
  label: string;
  email: string;
  is_active: boolean;
};

export default function ProcedureRhRecipientsPanel() {
  const [items, setItems] = useState<Recipient[]>([]);
  const [label, setLabel] = useState("");
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  function api(path: string, init?: RequestInit) {
    return fetch(`${process.env.NEXT_PUBLIC_API_URL}${path}`, {
      ...init,
      cache: "no-store",
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
        ...(init?.body ? { "Content-Type": "application/json" } : {}),
        ...init?.headers,
      },
    });
  }

  async function load() {
    setLoading(true);
    setError(null);
    try {
      const response = await api(
        "/api/admin/parametres/procedure-rh-recipients",
      );
      const data = await response.json().catch(() => null);
      if (!response.ok) {
        throw new Error(data?.message ?? "Chargement impossible.");
      }
      setItems(data.items ?? []);
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "Chargement impossible.");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void load();
  }, []);

  async function addRecipient(event: FormEvent) {
    event.preventDefault();
    if (saving) return;
    setSaving(true);
    setMessage(null);
    setError(null);
    try {
      const response = await api(
        "/api/admin/parametres/procedure-rh-recipients",
        {
          method: "POST",
          body: JSON.stringify({ label, email }),
        },
      );
      const data = await response.json().catch(() => null);
      if (!response.ok) {
        throw new Error(data?.message ?? "Ajout impossible.");
      }
      setLabel("");
      setEmail("");
      setMessage(data.message ?? "Le destinataire RH a été ajouté.");
      await load();
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : "Ajout impossible.");
    } finally {
      setSaving(false);
    }
  }

  async function toggleRecipient(item: Recipient) {
    if (saving) return;
    setSaving(true);
    setMessage(null);
    setError(null);
    try {
      const response = await api(
        `/api/admin/parametres/procedure-rh-recipients/${item.id}`,
        {
          method: "PUT",
          body: JSON.stringify({ isActive: !item.is_active }),
        },
      );
      const data = await response.json().catch(() => null);
      if (!response.ok) {
        throw new Error(data?.message ?? "Modification impossible.");
      }
      setMessage(
        item.is_active
          ? "Le destinataire RH a été désactivé."
          : "Le destinataire RH a été réactivé.",
      );
      await load();
    } catch (reason) {
      setError(
        reason instanceof Error ? reason.message : "Modification impossible.",
      );
    } finally {
      setSaving(false);
    }
  }

  return (
    <section className="rounded-lg bg-white p-5 shadow">
      <div className="mb-4">
        <h2 className="text-xl font-bold">Destinataires des procédures RH</h2>
        <p className="text-sm text-slate-500">
          Seules les adresses actives seront proposées lors de l’envoi d’une
          demande de procédure.
        </p>
      </div>

      {message && (
        <p className="mb-3 rounded bg-green-50 p-3 text-green-700">{message}</p>
      )}
      {error && (
        <p role="alert" className="mb-3 rounded bg-red-50 p-3 text-red-700">
          {error}
        </p>
      )}

      <form
        onSubmit={addRecipient}
        className="mb-5 grid gap-3 rounded border bg-slate-50 p-4 md:grid-cols-[1fr_1.4fr_auto]"
      >
        <label>
          <span className="mb-1 block text-sm font-semibold">Libellé *</span>
          <input
            required
            maxLength={150}
            value={label}
            onChange={(event) => setLabel(event.target.value)}
            placeholder="Ex. Responsable RH Lesquin"
            className="w-full rounded border bg-white px-3 py-2"
          />
        </label>
        <label>
          <span className="mb-1 block text-sm font-semibold">Adresse e-mail *</span>
          <input
            required
            type="email"
            maxLength={255}
            value={email}
            onChange={(event) => setEmail(event.target.value)}
            placeholder="responsable.rh@exemple.com"
            className="w-full rounded border bg-white px-3 py-2"
          />
        </label>
        <button
          disabled={saving}
          className="self-end rounded bg-green-600 px-4 py-2 font-semibold text-white disabled:opacity-50"
        >
          Ajouter
        </button>
      </form>

      {loading ? (
        <p className="text-slate-500">Chargement…</p>
      ) : items.length === 0 ? (
        <p className="rounded border border-amber-300 bg-amber-50 p-3 text-amber-800">
          Aucun destinataire RH n’est encore configuré.
        </p>
      ) : (
        <div className="overflow-x-auto rounded border">
          <table className="w-full border-collapse text-sm">
            <thead>
              <tr className="bg-sky-100 text-left">
                <th className="border p-2">Libellé</th>
                <th className="border p-2">Adresse e-mail</th>
                <th className="border p-2">Statut</th>
                <th className="border p-2">Action</th>
              </tr>
            </thead>
            <tbody>
              {items.map((item) => (
                <tr key={item.id} className="even:bg-slate-50">
                  <td className="border p-2 font-medium">{item.label}</td>
                  <td className="border p-2">{item.email}</td>
                  <td className="border p-2">
                    <span
                      className={`rounded px-2 py-1 ${item.is_active ? "bg-green-100 text-green-700" : "bg-slate-200 text-slate-600"}`}
                    >
                      {item.is_active ? "Actif" : "Désactivé"}
                    </span>
                  </td>
                  <td className="border p-2">
                    <button
                      type="button"
                      disabled={saving}
                      onClick={() => void toggleRecipient(item)}
                      className={`rounded px-3 py-2 font-semibold text-white disabled:opacity-50 ${item.is_active ? "bg-amber-600" : "bg-green-600"}`}
                    >
                      {item.is_active ? "Désactiver" : "Réactiver"}
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </section>
  );
}
