"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { consultations } from "@/data/consultations";

type Category = "organizacja" | "bezpieczenstwo" | "koszty" | "inne";
type Item = {
  id: string;
  consultationId: string;
  text: string;
  category: Category;
  createdAt: string;
  visibility: "wewnetrzne" | "publiczne";
};

export default function AdminStanowiska() {
  const [consultationId, setConsultationId] = useState(consultations[0]?.id ?? "");
  const [items, setItems] = useState<Item[]>([]);
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState<string | null>(null);

  async function load() {
    setLoading(true);
    setErr(null);
    try {
      const res = await fetch(`/api/stanowiska?consultationId=${encodeURIComponent(consultationId)}`);
      const data = await res.json();
      if (!res.ok || !data?.ok) throw new Error(data?.message || "Błąd pobierania");
      setItems(data.items ?? []);
    } catch (e: any) {
      setErr(e?.message || "Błąd");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    if (consultationId) load();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [consultationId]);

  async function setVisibility(id: string, visibility: Item["visibility"]) {
    await fetch("/api/stanowiska", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ consultationId, id, visibility }),
    });
    await load();
  }

  async function remove(id: string) {
    await fetch(`/api/stanowiska?consultationId=${encodeURIComponent(consultationId)}&id=${encodeURIComponent(id)}`, {
      method: "DELETE",
    });
    await load();
  }

  return (
    <div>
      <div className="mb-4 flex justify-end">
        <a
          href="/admin/logout"
          className="text-sm rounded-full border px-4 py-1 text-gray-600 hover:text-black"
        >
          Wyloguj
        </a>
      </div>

      <h1 className="text-3xl font-bold mb-2">Panel moderatora</h1>
      <p className="text-gray-700 mb-6">
        Moderacja stanowisk (wewnętrznie). Publicznie pokazujemy podsumowania — treści nie są publikowane automatycznie.
      </p>

      <div className="rounded-2xl border p-5 mb-6">
        <label className="text-sm font-medium">
          Konsultacja
          <select
            value={consultationId}
            onChange={(e) => setConsultationId(e.target.value)}
            className="mt-2 w-full rounded-xl border p-2"
          >
            {consultations.map((c) => (
              <option key={c.id} value={c.id}>
                {c.title}
              </option>
            ))}
          </select>
        </label>

        <div className="mt-4 flex gap-3">
          <button
            onClick={load}
            className="rounded-full border px-4 py-2 text-sm font-medium hover:bg-gray-50"
          >
            Odśwież
          </button>
          {loading && <span className="text-sm text-gray-500">Ładowanie…</span>}
          {err && <span className="text-sm text-red-600">{err}</span>}
        </div>
      </div>

      <div className="space-y-3">
        {items.length === 0 ? (
          <p className="text-gray-600">Brak stanowisk.</p>
        ) : (
          items.map((it) => (
            <div key={it.id} className="rounded-2xl border p-5">
              <div className="flex flex-wrap items-center justify-between gap-3">
                <div className="text-sm text-gray-600">
                  <span className="font-medium">{it.category}</span> •{" "}
                  {new Date(it.createdAt).toLocaleString("pl-PL")}
                </div>

                <span
                  className={[
                    "text-xs font-medium rounded-full px-3 py-1 border",
                    it.visibility === "publiczne" ? "bg-gray-900 text-white border-gray-900" : "bg-white",
                  ].join(" ")}
                >
                  {it.visibility === "publiczne" ? "ZAAKCEPTOWANE" : "WEWNĘTRZNE"}
                </span>
              </div>

              <p className="mt-3 text-gray-900 whitespace-pre-wrap">{it.text}</p>

              <div className="mt-4 flex flex-wrap gap-2">
                <button
                  onClick={() => setVisibility(it.id, "publiczne")}
                  className="rounded-full bg-gray-900 px-4 py-2 text-sm font-medium text-white hover:opacity-90"
                >
                  Akceptuj (do cytatów)
                </button>
                <button
                  onClick={() => setVisibility(it.id, "wewnetrzne")}
                  className="rounded-full border px-4 py-2 text-sm font-medium hover:bg-gray-50"
                >
                  Cofnij akceptację
                </button>
                <button
                  onClick={() => remove(it.id)}
                  className="rounded-full border px-4 py-2 text-sm font-medium hover:bg-gray-50"
                >
                  Usuń
                </button>
              </div>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
