"use client";

import type { GalleryImage } from "@prisma/client";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { useEffect, useState } from "react";

export function AdminGalleryManager() {
  const t = useTranslations("admin");
  const [items, setItems] = useState<GalleryImage[]>([]);
  const [loading, setLoading] = useState(true);

  async function refresh() {
    const res = await fetch("/api/admin/gallery");
    if (res.ok) setItems(await res.json());
  }

  useEffect(() => {
    (async () => {
      await refresh();
      setLoading(false);
    })();
  }, []);

  async function addImage(form: FormData) {
    const body = {
      url: String(form.get("url") ?? ""),
      altEn: String(form.get("altEn") ?? ""),
      altAr: String(form.get("altAr") ?? ""),
      altRu: String(form.get("altRu") ?? ""),
      altIt: String(form.get("altIt") ?? ""),
    };
    const res = await fetch("/api/admin/gallery", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    if (res.ok) await refresh();
  }

  async function remove(id: string) {
    if (!confirm("Delete?")) return;
    await fetch(`/api/admin/gallery?id=${encodeURIComponent(id)}`, {
      method: "DELETE",
    });
    await refresh();
  }

  if (loading) return <p className="text-muted">…</p>;

  return (
    <div className="space-y-10">
      <p className="text-sm text-muted">{t("galleryLead")}</p>

      <form
        onSubmit={async (e) => {
          e.preventDefault();
          const fd = new FormData(e.currentTarget);
          await addImage(fd);
          e.currentTarget.reset();
        }}
        className="grid gap-3 rounded-xl border border-border bg-card/40 p-6 md:grid-cols-2"
      >
        <div className="md:col-span-2">
          <label className="mb-1 block text-sm text-muted">{t("url")}</label>
          <input
            required
            name="url"
            className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm"
            placeholder="https://…"
          />
        </div>
        <div>
          <label className="mb-1 block text-sm text-muted">{t("altEn")}</label>
          <input name="altEn" className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm" />
        </div>
        <div>
          <label className="mb-1 block text-sm text-muted">{t("altAr")}</label>
          <input name="altAr" className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm" />
        </div>
        <div>
          <label className="mb-1 block text-sm text-muted">{t("altRu")}</label>
          <input name="altRu" className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm" />
        </div>
        <div>
          <label className="mb-1 block text-sm text-muted">{t("altIt")}</label>
          <input name="altIt" className="w-full rounded-md border border-border bg-background px-3 py-2 text-sm" />
        </div>
        <div className="md:col-span-2">
          <button
            type="submit"
            className="rounded-md bg-gold px-4 py-2 text-sm font-medium text-background"
          >
            {t("addImage")}
          </button>
        </div>
      </form>

      {items.length === 0 ? (
        <p className="text-muted">{t("noImages")}</p>
      ) : (
        <ul className="grid gap-6 md:grid-cols-2">
          {items.map((img) => (
            <li
              key={img.id}
              className="overflow-hidden rounded-xl border border-border bg-card/30"
            >
              <div className="relative aspect-video w-full bg-background">
                <Image
                  src={img.url}
                  alt={img.altEn || "img"}
                  fill
                  className="object-cover"
                  unoptimized
                />
              </div>
              <div className="flex items-center justify-between gap-2 p-3">
                <p className="truncate text-xs text-muted">{img.url}</p>
                <button
                  type="button"
                  onClick={() => remove(img.id)}
                  className="shrink-0 text-sm text-red-400 hover:underline"
                >
                  {t("delete")}
                </button>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
