"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Alerte } from "@/types/type";

type AlertesTabProps = {
  cos: number | string;
};

export default function AlertesTab({ cos }: AlertesTabProps) {
  const [alertes, setAlertes] = useState<Alerte[]>([]);
  const [alertView, setAlertView] = useState<"employee" | "all">("employee");
  const [search, setSearch] = useState("");
  const [establishmentFilter, setEstablishmentFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState<"all" | "todo" | "done">("all");
  const [sortBy, setSortBy] = useState<"name" | "firstname" | "alert">("name");
  const [selectedAlerte, setSelectedAlerte] = useState<Alerte | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [editLibAlerte, setEditLibAlerte] = useState("");
  const [isCreating, setIsCreating] = useState(false);
  const [newLibAlerte, setNewLibAlerte] = useState("");

  const router = useRouter();

  const filteredAlertes = alertes
    .filter((alerte) => {
      const value = search.trim().toLowerCase();

      const matchesSearch =
        !value ||
        alerte.employe?.NSA?.toLowerCase().includes(value) ||
        alerte.employe?.PRE?.toLowerCase().includes(value) ||
        alerte.libalerte?.toLowerCase().includes(value) ||
        alerte.etablissement?.toLowerCase().includes(value);

      const matchesEstablishment =
        establishmentFilter === "all" ||
        alerte.etablissement === establishmentFilter;

      const matchesStatus =
        statusFilter === "all" ||
        (statusFilter === "todo" && !alerte.fait) ||
        (statusFilter === "done" && alerte.fait);

      return matchesSearch && matchesEstablishment && matchesStatus;
    })
    .sort((a, b) => {
      if (sortBy === "firstname") {
        return (a.employe?.PRE ?? "").localeCompare(
          b.employe?.PRE ?? "",
          "fr",
          { sensitivity: "base" },
        );
      }

      if (sortBy === "alert") {
        return (a.libalerte ?? "").localeCompare(
          b.libalerte ?? "",
          "fr",
          { sensitivity: "base" },
        );
      }

      return (a.employe?.NSA ?? "").localeCompare(
        b.employe?.NSA ?? "",
        "fr",
        { sensitivity: "base" },
      );
    });

  const establishments = Array.from(
    new Set(
      alertes
        .map((alerte) => alerte.etablissement)
        .filter((value): value is string => Boolean(value)),
    ),
  ).sort((a, b) => a.localeCompare(b, "fr"));

  useEffect(() => {
    setSelectedAlerte(null);
  }, [cos, alertView]);

  async function fetchAlertes() {
    const token = localStorage.getItem("token");

    let url = "";

    if (alertView === "employee") {
      if (!cos) return;

      url = `${process.env.NEXT_PUBLIC_API_URL}/api/employes/${cos}/alertes`;
    } else {
      url = `${process.env.NEXT_PUBLIC_API_URL}/api/alertes`;
    }

    const response = await fetch(url, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      cache: "no-store"
    });

    const data = await response.json();
    console.log("Vue actuelle :", alertView);
console.log("URL alertes :", url);

  if (!response.ok) {
    console.error("Erreur récupération alertes :", data);
    return;
  }

  setAlertes(data.items ?? []);
  }

  async function handleMarkAsDone() {
    if (!selectedAlerte) return;

    const token = localStorage.getItem("token");

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/employes/${cos}/alertes`,
      {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          id: selectedAlerte.id,
          fait: true,
        }),
      },
    );

    if (!response.ok) {
      const error = await response.json().catch(() => null);
      console.error("Erreur modification alerte :", error);
      alert("Impossible de marquer l’alerte comme traitée.");
      return;
    }

    setSelectedAlerte(null);
    await fetchAlertes();
  }

  async function handleDelete() {
    if (!selectedAlerte) return;

    const confirmed = window.confirm(
      "Voulez-vous vraiment supprimer cette alerte ?",
    );

    if (!confirmed) return;

    const token = localStorage.getItem("token");

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_API_URL}/api/employes/${cos}/alertes?id=${selectedAlerte.id}`,
      {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${token}`,
        },
      },
    );

    if (!response.ok) {
      alert("Impossible de supprimer l’alerte.");
      return;
    }

    setSelectedAlerte(null);
    await fetchAlertes();
  }

  async function handleUpdate() {
  if (!selectedAlerte) return;

  const token = localStorage.getItem("token");

  const response = await fetch(
    `${process.env.NEXT_PUBLIC_API_URL}/api/employes/${cos}/alertes`,
    {
      method: "PUT",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        id: selectedAlerte.id,
        libalerte: editLibAlerte,
      }),
    },
  );

  if (!response.ok) {
    const error = await response.json().catch(() => null);
    console.error("Erreur modification alerte :", error);
    alert("Impossible de modifier l’alerte.");
    return;
  }

  setIsEditing(false);
  setSelectedAlerte(null);
  await fetchAlertes();
}

async function handleCreate() {
  const libalerte = newLibAlerte.trim();

  if (!libalerte) {
    alert("Le libellé de l’alerte est obligatoire.");
    return;
  }

  const token = localStorage.getItem("token");

  const response = await fetch(
    `${process.env.NEXT_PUBLIC_API_URL}/api/employes/${cos}/alertes`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        libalerte,
        fait: false,
        dateajout: new Date().toISOString(),
      }),
    },
  );

  const data = await response.json().catch(() => null);

  if (!response.ok) {
    console.error("Erreur création alerte :", data);
    alert("Impossible de créer l’alerte.");
    return;
  }

  setIsCreating(false);
setNewLibAlerte("");

await fetchAlertes();
}
  useEffect(() => {
    fetchAlertes();
  }, [cos, alertView]);

  return (
    <section className="flex h-full min-h-0 flex-col gap-3">
      <div className="flex flex-wrap items-center gap-3">
        <h2 className="text-lg font-bold text-sky-700">Alertes</h2>

        <div className="flex gap-2">
          <button
            type="button"
            onClick={() => {
              setAlertView("employee");
              setSearch("");
            }}
            className={`rounded-md px-4 py-2 text-sm font-semibold transition-colors ${alertView === "employee"
              ? "bg-sky-700 text-white"
              : "bg-slate-200 text-slate-700 hover:bg-slate-300"
              }`}
          >
            Alertes du salarié
          </button>

          <button
            type="button"
            onClick={() => {
              setAlertView("all");
              setSearch("");
            }}
            className={`rounded-md px-4 py-2 text-sm font-semibold transition-colors ${alertView === "all"
              ? "bg-sky-700 text-white"
              : "bg-slate-200 text-slate-700 hover:bg-slate-300"
              }`}
          >
            Toutes les alertes en cours
          </button>
        </div>

        <span className="ml-auto text-sm text-slate-500">
          {alertView === "employee"
            ? `${filteredAlertes.length} alerte${filteredAlertes.length > 1 ? "s" : ""}`
            : `${filteredAlertes.length} alerte${filteredAlertes.length > 1 ? "s" : ""} en cours`}
        </span>
      </div>
{alertView === "employee" && (
  <button
    type="button"
    onClick={() => {
      setSelectedAlerte(null);
      setIsCreating(true);
      setNewLibAlerte("");
    }}
    className="rounded-md bg-sky-700 px-3 py-2 text-sm font-semibold text-white hover:bg-sky-800"
  >
    Nouvelle alerte
  </button>
)}
      {alertView === "all" && (
        <input
          type="text"
          placeholder="Rechercher un salarié, un établissement ou une alerte..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="rounded-md border border-slate-300 px-3 py-2 text-sm outline-none focus:border-sky-600 text-black"
        />
      )}

      {alertView === "all" && (
        <div className="flex flex-wrap gap-2">
          <select
            value={establishmentFilter}
            onChange={(e) => setEstablishmentFilter(e.target.value)}
            className="rounded-md border border-slate-300 bg-white px-3 py-2 text-sm outline-none focus:border-sky-600 text-black"
          >
            <option value="all">Tous les établissements</option>

            {establishments.map((establishment) => (
              <option key={establishment} value={establishment}>
                {establishment}
              </option>
            ))}
          </select>

          <select
            value={statusFilter}
            onChange={(e) =>
              setStatusFilter(e.target.value as "all" | "todo" | "done")
            }
            className="rounded-md border border-slate-300 bg-white px-3 py-2 text-sm outline-none focus:border-sky-600 text-black"
          >
            <option value="all">Tous les statuts</option>
            <option value="todo">À traiter</option>
            <option value="done">Traitées</option>
          </select>

          <select
            value={sortBy}
            onChange={(e) =>
              setSortBy(e.target.value as "name" | "firstname" | "alert")
            }
            className="rounded-md border border-slate-300 bg-white px-3 py-2 text-sm outline-none focus:border-sky-600 text-black"
          >
            <option value="name">Trier par nom</option>
            <option value="firstname">Trier par prénom</option>
            <option value="alert">Trier par alerte</option>
          </select>

          <button
            type="button"
            onClick={() => {
              setSearch("");
              setEstablishmentFilter("all");
              setStatusFilter("all");
              setSortBy("name");
            }}
            className="rounded-md border border-slate-300 bg-white px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-100 text-black"
          >
            Réinitialiser
          </button>
        </div>
      )}

      <div className="min-h-0 flex-1 overflow-hidden rounded-md border border-slate-300 bg-white">
        {alertes.length === 0 ? (
          <div className="flex h-full min-h-28 items-center justify-center p-4">
            <p className="text-sm text-slate-500">
              {alertView === "employee"
                ? "Aucune alerte pour ce salarié."
                : "Aucune alerte en cours."}
            </p>
          </div>
        ) : alertView === "employee" ? (
          <div className="flex h-full min-h-0 flex-col">
            <div className="min-h-0 flex-1 overflow-y-auto">
              {filteredAlertes.map((alerte) => (
                <button
                  key={alerte.id}
                  type="button"
                  onClick={() => {
                    setSelectedAlerte(alerte);
                    setIsEditing(false);
                    setEditLibAlerte(alerte.libalerte ?? "");
                    setIsCreating(false);
                  }}
                  className={`block w-full border-b border-slate-200 p-3 text-left text-sm text-black transition-colors last:border-b-0 ${selectedAlerte?.id === alerte.id
                    ? "bg-sky-100"
                    : "hover:bg-slate-50"
                    }`}
                >
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="font-semibold text-slate-900">
                        {alerte.libalerte ?? "Alerte sans libellé"}
                      </p>

                      <p className="mt-1 text-xs text-slate-500">
                        Statut : {alerte.fait ? "Traitée" : "À traiter"}
                      </p>
                    </div>

                    <span
                      className={`shrink-0 rounded-full px-2.5 py-1 text-xs font-semibold ${alerte.fait
                        ? "bg-emerald-100 text-emerald-700"
                        : "bg-amber-100 text-amber-700"
                        }`}
                    >
                      {alerte.fait ? "Traitée" : "À traiter"}
                    </span>
                  </div>
                </button>
              ))}
            </div>

            {isCreating ? (
  <div className="shrink-0 border-t border-slate-300 bg-slate-50 p-3">
    <label className="mb-1 block text-sm font-semibold text-slate-700">
      Nouvelle alerte
    </label>

    <textarea
      value={newLibAlerte}
      onChange={(e) => setNewLibAlerte(e.target.value)}
      placeholder="Saisir le libellé de l’alerte..."
      className="min-h-24 w-full rounded-md border border-slate-300 p-2 text-sm text-black outline-none focus:border-sky-600"
    />

    <div className="mt-3 flex gap-2">
      <button
        type="button"
        onClick={handleCreate}
        className="rounded-md bg-sky-700 px-3 py-2 text-sm font-semibold text-white hover:bg-sky-800"
      >
        Créer
      </button>

      <button
        type="button"
        onClick={() => {
          setIsCreating(false);
          setNewLibAlerte("");
        }}
        className="rounded-md bg-slate-200 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-300"
      >
        Annuler
      </button>
    </div>
  </div>
) : selectedAlerte ? (
              <div className="shrink-0 border-t border-slate-300 bg-slate-50 p-3">
                <p className="text-sm font-semibold text-slate-700">
                  Alerte sélectionnée :
                </p>

                {isEditing ? (
                  <div className="mt-3">
                    <label className="mb-1 block text-sm font-semibold text-slate-700">
                      Libellé de l'alerte
                    </label>

                    <textarea
                      value={editLibAlerte}
                      onChange={(e) => setEditLibAlerte(e.target.value)}
                      className="min-h-24 w-full rounded-md border border-slate-300 p-2 text-sm text-black"
                    />

                    <div className="mt-3 flex gap-2">
                      <button
                        type="button"
                        onClick={handleUpdate}
                        className="rounded-md bg-sky-700 px-3 py-2 text-sm font-semibold text-white"
                      >
                        Enregistrer
                      </button>

                      <button
                        type="button"
                        onClick={() => {
                          setIsEditing(false);
                          setEditLibAlerte(selectedAlerte.libalerte ?? "");
                        }}
                        className="rounded-md bg-slate-300 px-3 py-2 text-sm font-semibold"
                      >
                        Annuler
                      </button>
                    </div>
                  </div>
                ) : (
                  <p className="mt-1 text-sm text-black">
                    {selectedAlerte.libalerte}
                  </p>
                )}

                <div className="mt-3 flex flex-wrap gap-2">
                  <button
                    type="button"
                    onClick={() => setIsEditing(true)}
                    className="rounded-md bg-sky-600 px-3 py-2 text-sm font-semibold text-white"
                  >
                    Modifier
                  </button>

                  <button
                    type="button"
                    onClick={handleMarkAsDone}
                    className="rounded-md bg-emerald-600 px-3 py-2 text-sm font-semibold text-white"
                  >
                    Marquer comme traitée
                  </button>

                  <button
                    type="button"
                    onClick={handleDelete}
                    className="rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white"
                  >
                    Supprimer
                  </button>
                </div>
              </div>
            ): null}
          </div>

        ) : (
          <div className="h-full overflow-auto">
            <table className="w-full min-w-[1000px] border-collapse text-sm">
              <thead className="sticky top-0 z-10 bg-slate-100 text-left text-xs font-semibold uppercase text-slate-600">
                <tr>
                  <th className="border-b border-slate-300 px-3 py-2">
                    Établissement
                  </th>

                  <th className="border-b border-slate-300 px-3 py-2">
                    Nom
                  </th>

                  <th className="border-b border-slate-300 px-3 py-2">
                    Prénom
                  </th>

                  <th className="border-b border-slate-300 px-3 py-2">
                    Contrat
                  </th>

                  <th className="border-b border-slate-300 px-3 py-2">
                    Date embauche
                  </th>

                  <th className="border-b border-slate-300 px-3 py-2">
                    Alerte
                  </th>

                  <th className="border-b border-slate-300 px-3 py-2 text-center">
                    Statut
                  </th>
                </tr>
              </thead>

              <tbody>
                {filteredAlertes.map((alerte) => (
                  <tr
                    key={alerte.id}
                    onClick={() => {
                      const employeeCos = alerte.employe?.COS;

                      if (!employeeCos) return;

                      router.push(`/employes/${employeeCos}?tab=alertes`);
                    }}
                    className="cursor-pointer border-b border-slate-200 transition-colors last:border-b-0 hover:bg-sky-50"
                  >
                    <td className="whitespace-nowrap px-3 py-2 text-slate-700">
                      {alerte.etablissement ?? "—"}
                    </td>

                    <td className="whitespace-nowrap px-3 py-2 font-semibold text-slate-900">
                      {alerte.employe?.NSA ?? alerte.nom ?? "—"}
                    </td>

                    <td className="whitespace-nowrap px-3 py-2 text-slate-800">
                      {alerte.employe?.PRE ?? alerte.prenom ?? "—"}
                    </td>

                    <td className="whitespace-nowrap px-3 py-2 text-slate-700">
                      {alerte.contrat ?? "—"}
                    </td>

                    <td className="whitespace-nowrap px-3 py-2 text-slate-700">
                      {alerte.dateembauche
                        ? new Date(alerte.dateembauche).toLocaleDateString("fr-FR")
                        : "—"}
                    </td>

                    <td className="min-w-[340px] px-3 py-2 font-medium text-slate-900">
                      {alerte.libalerte ?? "—"}
                    </td>

                    <td className="whitespace-nowrap px-3 py-2 text-center">
                      <span
                        className={`inline-flex rounded-full px-2.5 py-1 text-xs font-semibold ${alerte.fait
                          ? "bg-emerald-100 text-emerald-700"
                          : "bg-red-100 text-red-700"
                          }`}
                      >
                        {alerte.fait ? "Traitée" : "Urgent"}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </section>
  );
}