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

type Initial = {
  slug: string;
  number: string;
  status: string;
  category: string;
  stack: string;
  href: string;
  featured: boolean;
  summaryDe: string;
  summaryEn: string;
  stanceDe: string;
  stanceEn: string;
  bodyDe: string;
  bodyEn: string;
  sortIndex: number;
};

export function ProjectForm({
  initial,
  locale,
  isNew,
}: {
  initial: Initial;
  locale: Locale;
  isNew: boolean;
}) {
  const dict = getDict(locale);
  const router = useRouter();
  const [state, setState] = useState<Initial>(initial);
  const [saving, setSaving] = useState(false);
  const [status, setStatus] = useState<string | null>(null);

  function update<K extends keyof Initial>(key: K, value: Initial[K]) {
    setState((prev) => ({ ...prev, [key]: value }));
  }

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setSaving(true);
    setStatus(null);
    try {
      const url = isNew ? "/api/admin/projects" : `/api/admin/projects/${initial.slug}`;
      const method = isNew ? "POST" : "PUT";
      const body = {
        slug: state.slug,
        number: state.number,
        status: state.status,
        category: state.category,
        stack: state.stack,
        href: state.href || null,
        featured: state.featured,
        summaryDe: state.summaryDe,
        summaryEn: state.summaryEn,
        stanceDe: state.stanceDe,
        stanceEn: state.stanceEn,
        bodyDe: state.bodyDe,
        bodyEn: state.bodyEn,
        sortIndex: state.sortIndex,
      };
      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (!res.ok) {
        const text = await res.text();
        setStatus(text || "Error");
        return;
      }
      setStatus(dict.admin.saved);
      if (isNew) {
        router.push(`/admin/projects/${state.slug}`);
        router.refresh();
      } else {
        router.refresh();
      }
    } finally {
      setSaving(false);
    }
  }

  async function onDelete() {
    if (isNew) return;
    if (!confirm(dict.admin.confirmDelete)) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/admin/projects/${initial.slug}`, { method: "DELETE" });
      if (!res.ok) {
        const text = await res.text();
        setStatus(text || "Error");
        return;
      }
      router.push("/admin/projects");
      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-3">
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">slug</span>
          <input
            className={inputClass}
            value={state.slug}
            onChange={(e) => update("slug", e.target.value.toLowerCase().replace(/[^a-z0-9-]+/g, "-"))}
            required
          />
          <span className="mt-1 block font-mono text-[10px] text-muted">{dict.admin.slugHelp}</span>
        </label>
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">number</span>
          <input className={inputClass} value={state.number} onChange={(e) => update("number", e.target.value)} />
        </label>
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">sort_index</span>
          <input
            type="number"
            className={inputClass}
            value={state.sortIndex}
            onChange={(e) => update("sortIndex", Number(e.target.value))}
          />
        </label>
      </div>
      <div className="grid gap-4 md:grid-cols-3">
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">status</span>
          <input className={inputClass} value={state.status} onChange={(e) => update("status", e.target.value)} />
        </label>
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">category</span>
          <input className={inputClass} value={state.category} onChange={(e) => update("category", e.target.value)} />
        </label>
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">stack</span>
          <input className={inputClass} value={state.stack} onChange={(e) => update("stack", e.target.value)} />
        </label>
      </div>
      <div className="grid gap-4 md:grid-cols-3">
        <label className="block md:col-span-2">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">href</span>
          <input
            className={inputClass}
            value={state.href}
            onChange={(e) => update("href", e.target.value)}
            placeholder="https://..."
          />
        </label>
        <label className="flex items-center gap-2 self-end pb-2">
          <input
            type="checkbox"
            checked={state.featured}
            onChange={(e) => update("featured", e.target.checked)}
            className="h-4 w-4 accent-[var(--accent)]"
          />
          <span className="font-mono text-xs uppercase text-muted">featured</span>
        </label>
      </div>
      <div className="grid gap-4 md:grid-cols-2">
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">summary (DE)</span>
          <textarea
            className={`${inputClass} min-h-[80px]`}
            value={state.summaryDe}
            onChange={(e) => update("summaryDe", e.target.value)}
          />
        </label>
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">summary (EN)</span>
          <textarea
            className={`${inputClass} min-h-[80px]`}
            value={state.summaryEn}
            onChange={(e) => update("summaryEn", e.target.value)}
          />
        </label>
      </div>
      <div className="grid gap-4 md:grid-cols-2">
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">stance (DE)</span>
          <textarea
            className={`${inputClass} min-h-[80px]`}
            value={state.stanceDe}
            onChange={(e) => update("stanceDe", e.target.value)}
          />
        </label>
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">stance (EN)</span>
          <textarea
            className={`${inputClass} min-h-[80px]`}
            value={state.stanceEn}
            onChange={(e) => update("stanceEn", e.target.value)}
          />
        </label>
      </div>
      <div className="grid gap-4 md:grid-cols-2">
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">body (DE)</span>
          <textarea
            className={`${inputClass} min-h-[200px]`}
            value={state.bodyDe}
            onChange={(e) => update("bodyDe", e.target.value)}
          />
        </label>
        <label className="block">
          <span className="mb-1 block font-mono text-xs uppercase text-muted">body (EN)</span>
          <textarea
            className={`${inputClass} min-h-[200px]`}
            value={state.bodyEn}
            onChange={(e) => update("bodyEn", e.target.value)}
          />
        </label>
      </div>
      <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>
        {!isNew ? (
          <button
            type="button"
            onClick={onDelete}
            disabled={saving}
            className="border border-[var(--danger)] px-4 py-2 font-mono text-sm uppercase text-[var(--danger)] disabled:opacity-50"
          >
            Löschen
          </button>
        ) : null}
        {status ? <span className="font-mono text-xs text-[var(--accent-2)]">{status}</span> : null}
      </div>
    </form>
  );
}
