import { useEffect, useState } from "react";
import { api } from "../api.js";

interface PendingRecipe {
  id: string;
  titleSv: string;
  descriptionSv: string;
  status: string;
  creatorDisplayName: string | null;
  moderationNote: string | null;
  createdAt: string;
}

export function ModerationPage() {
  const [recipes, setRecipes] = useState<PendingRecipe[]>([]);
  const [error, setError] = useState<string | null>(null);

  const load = () => {
    api<{ recipes: PendingRecipe[] }>("/admin/v1/moderation/recipes")
      .then((r) => setRecipes(r.recipes))
      .catch((e) => setError(String(e.message)));
  };
  useEffect(load, []);

  const act = async (id: string, action: "approve" | "reject" | "request_changes") => {
    const note =
      action === "approve" ? undefined : (prompt("Motivering till skaparen:") ?? undefined);
    await api(`/admin/v1/moderation/recipes/${id}`, { method: "POST", body: { action, note } });
    load();
  };

  return (
    <div>
      <h2>Receptmoderering</h2>
      <p className="muted">
        Flöde enligt spec §35: submission → AI-kontroll → dubblettkontroll → moderering →
        publicering.
      </p>
      {error && <div className="error-text">{error}</div>}
      {recipes.length === 0 && <div className="panel">Inga recept väntar på granskning. 🎉</div>}
      {recipes.map((recipe) => (
        <div className="panel" key={recipe.id}>
          <div className="row" style={{ justifyContent: "space-between" }}>
            <div>
              <strong>{recipe.titleSv}</strong> <span className="badge">{recipe.status}</span>
              <div className="muted">
                av {recipe.creatorDisplayName ?? "okänd"} ·{" "}
                {new Date(recipe.createdAt).toLocaleString("sv-SE")}
              </div>
            </div>
            <div className="row">
              <button className="primary" onClick={() => act(recipe.id, "approve")}>
                Godkänn
              </button>
              <button className="ghost" onClick={() => act(recipe.id, "request_changes")}>
                Begär ändringar
              </button>
              <button className="ghost danger" onClick={() => act(recipe.id, "reject")}>
                Avslå
              </button>
            </div>
          </div>
          <p>{recipe.descriptionSv}</p>
          {recipe.moderationNote && (
            <div className="muted">AI-kontroll & dubbletter: {recipe.moderationNote}</div>
          )}
        </div>
      ))}
    </div>
  );
}
