"use client";

import { useState, useTransition } from "react";
import { Button, Card } from "@/components/ui";
import { Field, inputClass } from "@/components/ui/form";
import { MediaPicker } from "@/components/features/page-editor/media-picker";
import { createEventAction, updateEventAction } from "@/lib/actions/events";

export interface EventFormValues {
  name: string; slug: string; description: string; startsLocal: string; endsLocal: string; timezone: string; venue: string; locationText: string;
  website: string; organizer: string; logoMediaId: string | null; bannerMediaId: string | null; seoTitle: string; seoDescription: string;
}

export function EventForm({ mode, siteId, base, eventId, initial, disabled }: { mode: "create" | "edit"; siteId: string; base: string; eventId?: string; initial: EventFormValues; disabled?: boolean }) {
  const [v, setV] = useState(initial);
  const [pending, start] = useTransition();
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null);
  const set = <K extends keyof EventFormValues>(k: K, value: EventFormValues[K]) => { setV((s) => ({ ...s, [k]: value })); setStatus(null); };
  const text = (k: keyof EventFormValues, label: string, opts: { help?: string; type?: string; max?: number } = {}) => (
    <Field id={`ev-${k}`} label={label} error={errors[k]} help={opts.help}>
      <input id={`ev-${k}`} type={opts.type ?? "text"} value={String(v[k] ?? "")} maxLength={opts.max} disabled={disabled} onChange={(e) => set(k, e.target.value as never)} className={inputClass} aria-invalid={errors[k] ? true : undefined} />
    </Field>
  );

  function submit() {
    setErrors({});
    start(async () => {
      const payload = { ...v, logoMediaId: v.logoMediaId ?? undefined, bannerMediaId: v.bannerMediaId ?? undefined };
      const res = mode === "create" ? await createEventAction(base, siteId, payload) : await updateEventAction(eventId ?? "", payload);
      if (res && !res.ok) { setErrors(res.fieldErrors ?? {}); setStatus({ ok: false, text: res.error }); }
      else if (res?.ok) setStatus({ ok: true, text: res.message ?? "Saved" });
    });
  }

  return (
    <Card className="p-4">
      <form onSubmit={(e) => { e.preventDefault(); submit(); }} className="grid gap-4 sm:grid-cols-2" noValidate>
        <div className="sm:col-span-2">{text("name", "Event name", { max: 160 })}</div>
        {text("slug", "URL name", { help: mode === "create" ? "Leave blank to generate from the name." : undefined, max: 120 })}
        {text("timezone", "Time zone", { help: "IANA name, e.g. Europe/London or Asia/Kolkata. Session times are entered in this zone." })}
        {text("startsLocal", "Starts", { type: "datetime-local" })}
        {text("endsLocal", "Ends", { type: "datetime-local" })}
        {text("venue", "Venue", { max: 160 })}
        {text("locationText", "Location (city, country)", { max: 255 })}
        {text("organizer", "Organizer", { max: 160 })}
        {text("website", "Website", { help: "https://…" })}
        <Field id="ev-description" label="Description" error={errors.description} className="sm:col-span-2">
          <textarea id="ev-description" rows={5} value={v.description} disabled={disabled} maxLength={10000} onChange={(e) => set("description", e.target.value)} className={inputClass} />
        </Field>
        <div className="space-y-1"><span className="block text-xs font-medium">Logo</span><MediaPicker siteId={siteId} label="logo" value={v.logoMediaId} onChange={(x) => set("logoMediaId", x)} disabled={disabled || mode === "create"} />{mode === "create" ? <p className="text-xs text-muted-foreground">Add images after creating the event.</p> : null}</div>
        <div className="space-y-1"><span className="block text-xs font-medium">Banner</span><MediaPicker siteId={siteId} label="banner" value={v.bannerMediaId} onChange={(x) => set("bannerMediaId", x)} disabled={disabled || mode === "create"} /></div>
        {text("seoTitle", "SEO title", { max: 70 })}
        {text("seoDescription", "Meta description", { max: 320 })}
        {!disabled ? (
          <div className="flex items-center gap-3 sm:col-span-2">
            <Button type="submit" disabled={pending}>{pending ? "Saving…" : mode === "create" ? "Create event" : "Save event"}</Button>
            {status ? <p role={status.ok ? "status" : "alert"} className={status.ok ? "text-sm text-success" : "text-sm text-danger"}>{status.text}</p> : null}
          </div>
        ) : <p className="text-sm text-muted-foreground sm:col-span-2">You can view event details but not change them.</p>}
      </form>
    </Card>
  );
}
