"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import type { Locale } from "@/i18n/routes";
import { getDict } from "@/i18n/dictionaries";
import type { Profile, ProfileLink } from "@/lib/models";

type Initial = Profile & { factsDe: string[]; factsEn: string[]; bioDe: string; bioEn: string };

function linksToText(links: ProfileLink[]): string {
  return links.map((l) => `${l.label}\t${l.href}\t${l.kind}`).join("\n");
}

function textToLinks(text: string): ProfileLink[] {
  return text
    .split("\n")
    .map((line) => line.trim())
    .filter(Boolean)
    .map((line) => {
      const [label, href, kind] = line.split(/\t|\s{2,}/).map((s) => s.trim());
      return { label: label ?? "", href: href ?? "", kind: kind ?? "external" } satisfies ProfileLink;
    })
    .filter((l) => l.label && l.href);
}

export function ProfileForm({
  initial,
  locale,
}: {
  initial: Initial;
  locale: Locale;
}) {
  const dict = getDict(locale);
  const router = useRouter();
  const [handle, setHandle] = useState(initial.handle);
  const [realName, setRealName] = useState(initial.realName);
  const [role, setRole] = useState(initial.role);
  const [location, setLocation] = useState(initial.location);
  const [bioDe, setBioDe] = useState(initial.bioDe);
  const [bioEn, setBioEn] = useState(initial.bioEn);
  const [factsDe, setFactsDe] = useState(initial.factsDe.join("\n"));
  const [factsEn, setFactsEn] = useState(initial.factsEn.join("\n"));
  const [links, setLinks] = useState(linksToText(initial.links));
  const [saving, setSaving] = useState(false);
  const [status, setStatus] = useState<string | null>(null);

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setSaving(true);
    setStatus(null);
    try {
      const res = await fetch("/api/admin/profile", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          handle,
          realName,
          role,
          location,
          bioDe,
          bioEn,
          factsDe: factsDe.split("\n").map((s) => s.trim()).filter(Boolean),
          factsEn: factsEn.split("\n").map((s) => s.trim()).filter(Boolean),
          links: textToLinks(links),
        }),
      });
      if (!res.ok) {
        setStatus("Error");
        return;
      }
      setStatus(dict.admin.saved);
      router.refresh();
    } finally {
      setSaving(false);
    }
  }

  const inputClass =
    "w-full border border-hairline bg-[var(--bg-deep)] px-3 py-2 font-mono text-sm text-[var(--fg)] focus:border-accent focus:outline-none";

  return (
    <form onSubmit={onSubmit} className="space-y-4">
      <div className="grid gap-4 md:grid-cols-2">
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">handle</span>
          <input className={inputClass} value={handle} onChange={(e) => setHandle(e.target.value)} required />
        </label>
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">real name</span>
          <input className={inputClass} value={realName} onChange={(e) => setRealName(e.target.value)} required />
        </label>
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">role</span>
          <input className={inputClass} value={role} onChange={(e) => setRole(e.target.value)} required />
        </label>
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">location</span>
          <input className={inputClass} value={location} onChange={(e) => setLocation(e.target.value)} required />
        </label>
      </div>
      <label className="block">
        <span className="mb-1 block font-mono text-xs uppercase text-muted">bio (DE)</span>
        <textarea
          className={`${inputClass} min-h-[160px]`}
          value={bioDe}
          onChange={(e) => setBioDe(e.target.value)}
          required
        />
      </label>
      <label className="block">
        <span className="mb-1 block font-mono text-xs uppercase text-muted">bio (EN)</span>
        <textarea
          className={`${inputClass} min-h-[160px]`}
          value={bioEn}
          onChange={(e) => setBioEn(e.target.value)}
          required
        />
      </label>
      <div className="grid gap-4 md:grid-cols-2">
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">facts (DE, eine pro Zeile)</span>
          <textarea
            className={`${inputClass} min-h-[120px]`}
            value={factsDe}
            onChange={(e) => setFactsDe(e.target.value)}
          />
        </label>
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">facts (EN, eine pro Zeile)</span>
          <textarea
            className={`${inputClass} min-h-[120px]`}
            value={factsEn}
            onChange={(e) => setFactsEn(e.target.value)}
          />
        </label>
      </div>
      <label className="block">
        <span className="mb-1 block font-mono text-xs uppercase text-muted">links (label · TAB · href · TAB · kind pro Zeile)</span>
        <textarea
          className={`${inputClass} min-h-[120px]`}
          value={links}
          onChange={(e) => setLinks(e.target.value)}
        />
      </label>
      <div className="flex items-center gap-4">
        <button
          type="submit"
          disabled={saving}
          className="border border-accent bg-accent px-4 py-2 font-mono text-sm uppercase text-[var(--bg)] disabled:opacity-50"
        >
          {saving ? dict.admin.saving : dict.admin.save}
        </button>
        {status ? <span className="font-mono text-xs text-[var(--accent-2)]">{status}</span> : null}
      </div>
    </form>
  );
}
