"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { de } from "@/lib/i18n/de";
import {
  MerkmalValueEditor,
  initMerkmalWerte,
  werteToList,
  type MerkmalWerteState,
} from "./MerkmalValueEditor";
import { TemplatePicker } from "./TemplatePicker";
import type {
  MerkmalDefinition,
  MerkmalValueInput,
} from "@/lib/merkmale/types";
import { createVehicle, updateVehicle } from "@/server/actions/vehicles";

export interface VehicleFormTemplate {
  id: string;
  code: string;
  name: string;
}

interface CreateProps {
  mode: "create";
  templates: VehicleFormTemplate[];
  /** Lädt die Merkmal-Definitionen einer Vorlage (geschützte Server-Action). */
  loadTemplateMerkmale: (templateId: string) => Promise<MerkmalDefinition[]>;
}

interface EditProps {
  mode: "edit";
  vehicleId: string;
  initial: {
    name: string;
    funkrufname: string;
    notiz: string;
  };
  definitionen: MerkmalDefinition[];
  vorhandeneWerte: MerkmalValueInput[];
}

type Props = CreateProps | EditProps;

export function VehicleForm(props: Props) {
  const router = useRouter();
  const [error, setError] = React.useState<string | null>(null);
  const [pending, startTransition] = React.useTransition();

  const [templateId, setTemplateId] = React.useState<string>("");
  const [defs, setDefs] = React.useState<MerkmalDefinition[]>(
    props.mode === "edit" ? props.definitionen : [],
  );
  const [werte, setWerte] = React.useState<MerkmalWerteState>(
    props.mode === "edit"
      ? initMerkmalWerte(props.definitionen, props.vorhandeneWerte)
      : {},
  );

  async function onTemplateChange(id: string) {
    setTemplateId(id);
    if (props.mode !== "create") return;
    if (!id) {
      setDefs([]);
      setWerte({});
      return;
    }
    const loaded = await props.loadTemplateMerkmale(id);
    setDefs(loaded);
    setWerte(initMerkmalWerte(loaded));
  }

  function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    const fd = new FormData(e.currentTarget);
    const base = {
      name: String(fd.get("name") ?? ""),
      funkrufname: String(fd.get("funkrufname") ?? ""),
      notiz: String(fd.get("notiz") ?? ""),
    };
    const liste = werteToList(werte);

    startTransition(async () => {
      const res =
        props.mode === "create"
          ? await createVehicle({ ...base, templateId: templateId || undefined }, liste)
          : await updateVehicle({ ...base, id: props.vehicleId }, liste);
      if (!res.ok) {
        setError(res.error);
        return;
      }
      router.push("/verwaltung/fahrzeuge");
      router.refresh();
    });
  }

  const initial = props.mode === "edit" ? props.initial : undefined;

  return (
    <form onSubmit={onSubmit} className="max-w-2xl space-y-6">
      {props.mode === "create" ? (
        <TemplatePicker
          templates={props.templates}
          value={templateId}
          onChange={(id) => void onTemplateChange(id)}
        />
      ) : null}

      <div className="grid gap-1.5">
        <Label htmlFor="name">{de.verwaltung.name}</Label>
        <Input
          id="name"
          name="name"
          required
          defaultValue={initial?.name ?? ""}
        />
      </div>

      <div className="grid gap-1.5">
        <Label htmlFor="funkrufname">{de.verwaltung.funkrufname}</Label>
        <Input
          id="funkrufname"
          name="funkrufname"
          defaultValue={initial?.funkrufname ?? ""}
        />
      </div>

      <div className="grid gap-1.5">
        <Label htmlFor="notiz">{de.verwaltung.notiz}</Label>
        <Input id="notiz" name="notiz" defaultValue={initial?.notiz ?? ""} />
      </div>

      <fieldset className="rounded border border-rand bg-white p-5">
        <legend className="px-1 text-sm font-semibold text-navy">
          {de.verwaltung.merkmale}
        </legend>
        <MerkmalValueEditor
          definitionen={defs}
          werte={werte}
          onChange={setWerte}
        />
      </fieldset>

      {error ? (
        <p role="alert" className="text-sm text-signal">
          {error}
        </p>
      ) : null}

      <div className="flex gap-2">
        <Button type="submit" disabled={pending}>
          {de.verwaltung.speichern}
        </Button>
        <Button
          type="button"
          variant="outline"
          onClick={() => router.push("/verwaltung/fahrzeuge")}
        >
          {de.verwaltung.abbrechen}
        </Button>
      </div>
    </form>
  );
}
