"use client";

import { useActionState } from "react";
import type { GameFormState } from "@/lib/admin-actions";

export interface GameFormInitial {
  title?: string;
  slug?: string;
  description?: string;
  categoryId?: number;
  developer?: string | null;
  publisher?: string | null;
  officialUrl?: string;
  thumbnail?: string | null;
  embedAllowed?: boolean;
  embedUrl?: string | null;
  status?: string;
  featured?: boolean;
  trending?: boolean;
  instructions?: string | null;
  controls?: string | null;
}

interface GameFormProps {
  categories: { id: number; name: string }[];
  initial?: GameFormInitial;
  action: (prev: GameFormState, formData: FormData) => Promise<GameFormState>;
  submitLabel: string;
}

const INITIAL_STATE: GameFormState = { errors: {}, values: {}, message: "" };

function FieldError({ message }: { message?: string }) {
  if (!message) return null;
  return (
    <p role="alert" className="mt-1 text-xs text-red-400">
      {message}
    </p>
  );
}

const inputCls =
  "h-11 w-full rounded-xl border border-slate-700 bg-slate-950 px-4 text-sm text-white placeholder:text-slate-600 focus:border-brand-500 focus:outline-none";
const areaCls =
  "w-full rounded-xl border border-slate-700 bg-slate-950 px-4 py-3 text-sm text-white placeholder:text-slate-600 focus:border-brand-500 focus:outline-none";
const labelCls = "mb-1 block text-sm font-medium text-slate-300";

/**
 * Admin game form (uncontrolled inputs preserve typing across validation
 * round-trips; server action returns per-field errors).
 */
export function GameForm({ categories, initial, action, submitLabel }: GameFormProps) {
  const [state, formAction, pending] = useActionState(action, INITIAL_STATE);
  const v = (name: keyof GameFormInitial): string | undefined =>
    state.values[name] !== undefined ? state.values[name] : undefined;

  return (
    <form action={formAction} className="max-w-3xl space-y-5">
      {state.message ? (
        <p role="alert" className="rounded-xl border border-red-500/40 bg-red-500/10 px-4 py-3 text-sm text-red-300">
          {state.message}
        </p>
      ) : null}

      <div className="grid gap-5 sm:grid-cols-2">
        <div>
          <label htmlFor="title" className={labelCls}>Title *</label>
          <input id="title" name="title" required maxLength={120} defaultValue={v("title") ?? initial?.title ?? ""} className={inputCls} />
          <FieldError message={state.errors.title} />
        </div>
        <div>
          <label htmlFor="slug" className={labelCls}>Slug <span className="text-slate-500">(blank = auto)</span></label>
          <input id="slug" name="slug" maxLength={80} defaultValue={v("slug") ?? initial?.slug ?? ""} placeholder="neon-racer" className={inputCls} />
          <FieldError message={state.errors.slug} />
        </div>
      </div>

      <div>
        <label htmlFor="description" className={labelCls}>Short description *</label>
        <textarea id="description" name="description" required rows={3} maxLength={2000} defaultValue={v("description") ?? initial?.description ?? ""} className={areaCls} />
        <FieldError message={state.errors.description} />
      </div>

      <div className="grid gap-5 sm:grid-cols-2">
        <div>
          <label htmlFor="categoryId" className={labelCls}>Category *</label>
          <select id="categoryId" name="categoryId" required defaultValue={v("categoryId") ?? String(initial?.categoryId ?? categories[0]?.id ?? "")} className={inputCls}>
            {categories.map((c) => (
              <option key={c.id} value={c.id}>{c.name}</option>
            ))}
          </select>
          <FieldError message={state.errors.categoryId} />
        </div>
        <div>
          <label htmlFor="status" className={labelCls}>Status *</label>
          <select id="status" name="status" defaultValue={v("status") ?? initial?.status ?? "draft"} className={inputCls}>
            <option value="draft">Draft (private)</option>
            <option value="published">Published (public)</option>
            <option value="disabled">Disabled (hidden)</option>
          </select>
          <FieldError message={state.errors.status} />
        </div>
      </div>

      <div className="grid gap-5 sm:grid-cols-2">
        <div>
          <label htmlFor="developer" className={labelCls}>Developer</label>
          <input id="developer" name="developer" maxLength={120} defaultValue={v("developer") ?? initial?.developer ?? ""} className={inputCls} />
          <FieldError message={state.errors.developer} />
        </div>
        <div>
          <label htmlFor="publisher" className={labelCls}>Publisher</label>
          <input id="publisher" name="publisher" maxLength={120} defaultValue={v("publisher") ?? initial?.publisher ?? ""} className={inputCls} />
          <FieldError message={state.errors.publisher} />
        </div>
      </div>

      <div className="grid gap-5 sm:grid-cols-2">
        <div>
          <label htmlFor="officialUrl" className={labelCls}>Official game URL (HTTPS) *</label>
          <input id="officialUrl" name="officialUrl" type="url" required defaultValue={v("officialUrl") ?? initial?.officialUrl ?? ""} placeholder="https://…" className={inputCls} />
          <FieldError message={state.errors.officialUrl} />
        </div>
        <div>
          <label htmlFor="thumbnail" className={labelCls}>Thumbnail <span className="text-slate-500">(HTTPS URL or /path)</span></label>
          <input id="thumbnail" name="thumbnail" defaultValue={v("thumbnail") ?? initial?.thumbnail ?? ""} placeholder="https://… or /thumbs/game.webp" className={inputCls} />
          <FieldError message={state.errors.thumbnail} />
        </div>
      </div>

      <fieldset className="rounded-2xl border border-slate-800 p-4">
        <legend className="px-2 text-sm font-semibold text-white">Embedding</legend>
        <label className="flex cursor-pointer items-center gap-3 text-sm text-slate-200">
          <input
            type="checkbox"
            name="embedAllowed"
            defaultChecked={initial?.embedAllowed ?? false}
            className="h-5 w-5 accent-indigo-500"
          />
          Embedding explicitly permitted by the provider
        </label>
        <div className="mt-3">
          <label htmlFor="embedUrl" className={labelCls}>Authorized embed URL (HTTPS, allowlisted host)</label>
          <input id="embedUrl" name="embedUrl" type="url" defaultValue={v("embedUrl") ?? initial?.embedUrl ?? ""} placeholder="https://…" className={inputCls} />
          <FieldError message={state.errors.embedUrl} />
        </div>
      </fieldset>

      <div className="flex flex-wrap gap-5">
        <label className="flex cursor-pointer items-center gap-2 text-sm text-slate-200">
          <input type="checkbox" name="featured" defaultChecked={initial?.featured ?? false} className="h-5 w-5 accent-indigo-500" />
          Featured
        </label>
        <label className="flex cursor-pointer items-center gap-2 text-sm text-slate-200">
          <input type="checkbox" name="trending" defaultChecked={initial?.trending ?? false} className="h-5 w-5 accent-indigo-500" />
          Trending
        </label>
      </div>

      <div>
        <label htmlFor="instructions" className={labelCls}>How to play</label>
        <textarea id="instructions" name="instructions" rows={3} maxLength={5000} defaultValue={v("instructions") ?? initial?.instructions ?? ""} className={areaCls} />
        <FieldError message={state.errors.instructions} />
      </div>
      <div>
        <label htmlFor="controls" className={labelCls}>Controls</label>
        <textarea id="controls" name="controls" rows={2} maxLength={2000} defaultValue={v("controls") ?? initial?.controls ?? ""} className={areaCls} />
        <FieldError message={state.errors.controls} />
      </div>

      <button
        type="submit"
        disabled={pending}
        className="inline-flex h-11 items-center rounded-xl bg-brand-600 px-6 font-semibold text-white hover:bg-brand-500 disabled:opacity-60"
      >
        {pending ? "Saving…" : submitLabel}
      </button>
    </form>
  );
}
