"use client";

import type { SiteContent } from "@prisma/client";
import { useTranslations } from "next-intl";
import { FormEvent, useEffect, useState } from "react";

export function AdminContentForm() {
  const t = useTranslations("admin");
  const [row, setRow] = useState<SiteContent | null>(null);
  const [saved, setSaved] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      try {
        const res = await fetch("/api/admin/content");
        if (res.ok) setRow(await res.json());
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  async function onSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const body: Record<string, string> = {};
    fd.forEach((v, k) => {
      body[k] = String(v);
    });
    const res = await fetch("/api/admin/content", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    if (res.ok) {
      setSaved(true);
      setRow(await res.json());
      setTimeout(() => setSaved(false), 2000);
    }
  }

  if (loading || !row) {
    return <p className="text-muted">{loading ? "…" : "—"}</p>;
  }

  const field = (
    name: keyof SiteContent,
    label: string,
    multiline?: boolean
  ) => (
    <div key={String(name)}>
      <label className="mb-1 block text-sm text-muted">{label}</label>
      {multiline ? (
        <textarea
          name={String(name)}
          defaultValue={String(row[name] ?? "")}
          rows={4}
          className="w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground focus:border-gold focus:outline-none focus:ring-1 focus:ring-gold"
        />
      ) : (
        <input
          name={String(name)}
          defaultValue={String(row[name] ?? "")}
          className="w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground focus:border-gold focus:outline-none focus:ring-1 focus:ring-gold"
        />
      )}
    </div>
  );

  return (
    <form onSubmit={onSubmit} className="space-y-10">
      <section className="space-y-4">
        <h2 className="font-[family-name:var(--font-display)] text-xl text-gold">
          {t("aboutSection")}
        </h2>
        <div className="grid gap-4 md:grid-cols-2">
          {field("aboutEn", "About EN", true)}
          {field("aboutAr", "About AR", true)}
          {field("aboutRu", "About RU", true)}
          {field("aboutIt", "About IT", true)}
        </div>
      </section>

      <section className="space-y-4">
        <h2 className="font-[family-name:var(--font-display)] text-xl text-gold">
          {t("addressSection")}
        </h2>
        <div className="grid gap-4 md:grid-cols-2">
          {field("addressEn", "Address EN", true)}
          {field("addressAr", "Address AR", true)}
          {field("addressRu", "Address RU", true)}
          {field("addressIt", "Address IT", true)}
        </div>
        {field("mapEmbedUrl", t("mapEmbed"))}
      </section>

      <section className="space-y-4">
        <h2 className="font-[family-name:var(--font-display)] text-xl text-gold">
          {t("socialSection")}
        </h2>
        <div className="grid gap-4 md:grid-cols-2">
          {field("socialInstagram", "Instagram URL")}
          {field("socialFacebook", "Facebook URL")}
          {field("socialTiktok", "TikTok URL")}
          {field("socialWhatsapp", "WhatsApp link")}
          {field("socialEmail", "Email")}
        </div>
      </section>

      <div className="flex items-center gap-4">
        <button
          type="submit"
          className="rounded-md bg-gold px-6 py-3 text-sm font-medium text-background hover:bg-gold-hover"
        >
          {t("save")}
        </button>
        {saved && <span className="text-sm text-gold">{t("saved")}</span>}
      </div>
    </form>
  );
}
