"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 type {
  MerkmalDefinition,
  MerkmalValueInput,
} from "@/lib/merkmale/types";
import { createEquipment, updateEquipment } from "@/server/actions/equipment";

export interface CategoryOption {
  id: string;
  name: string;
}
export interface VehicleOption {
  id: string;
  name: string;
}

interface CreateProps {
  mode: "create";
  categories: CategoryOption[];
  vehicles: VehicleOption[];
  loadCategoryMerkmale: (categoryId: string) => Promise<MerkmalDefinition[]>;
}

interface EditProps {
  mode: "edit";
  equipmentId: string;
  categories: CategoryOption[];
  vehicles: VehicleOption[];
  initial: { name: string; categoryId: string; vehicleId: string };
  definitionen: MerkmalDefinition[];
  vorhandeneWerte: MerkmalValueInput[];
  loadCategoryMerkmale: (categoryId: string) => Promise<MerkmalDefinition[]>;
}

type Props = CreateProps | EditProps;

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

  const [categoryId, setCategoryId] = React.useState<string>(
    props.mode === "edit" ? props.initial.categoryId : "",
  );
  const [vehicleId, setVehicleId] = React.useState<string>(
    props.mode === "edit" ? props.initial.vehicleId : "",
  );
  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 onCategoryChange(id: string) {
    setCategoryId(id);
    if (!id) {
      setDefs([]);
      setWerte({});
      return;
    }
    const loaded = await props.loadCategoryMerkmale(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") ?? ""),
      categoryId,
      vehicleId: vehicleId || undefined,
    };
    const liste = werteToList(werte);

    startTransition(async () => {
      const res =
        props.mode === "create"
          ? await createEquipment(base, liste)
          : await updateEquipment({ ...base, id: props.equipmentId }, liste);
      if (!res.ok) {
        setError(res.error);
        return;
      }
      router.push("/verwaltung/geraete");
      router.refresh();
    });
  }

  const initialName = props.mode === "edit" ? props.initial.name : "";

  return (
    <form onSubmit={onSubmit} className="max-w-2xl space-y-6">
      <div className="grid gap-1.5">
        <Label htmlFor="name">{de.verwaltung.name}</Label>
        <Input id="name" name="name" required defaultValue={initialName} />
      </div>

      <div className="grid gap-1.5">
        <Label htmlFor="categoryId">{de.verwaltung.kategorie}</Label>
        <select
          id="categoryId"
          name="categoryId"
          required
          className="h-10 w-full rounded border border-rand bg-white px-3 text-sm text-anthrazit focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-navy"
          value={categoryId}
          onChange={(e) => void onCategoryChange(e.target.value)}
        >
          <option value="">—</option>
          {props.categories.map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>
      </div>

      <div className="grid gap-1.5">
        <Label htmlFor="vehicleId">{de.verwaltung.zuordnung}</Label>
        <select
          id="vehicleId"
          name="vehicleId"
          className="h-10 w-full rounded border border-rand bg-white px-3 text-sm text-anthrazit focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-navy"
          value={vehicleId}
          onChange={(e) => setVehicleId(e.target.value)}
        >
          <option value="">{de.verwaltung.imGeraetehaus}</option>
          {props.vehicles.map((v) => (
            <option key={v.id} value={v.id}>
              {v.name}
            </option>
          ))}
        </select>
      </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/geraete")}
        >
          {de.verwaltung.abbrechen}
        </Button>
      </div>
    </form>
  );
}
