"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { de } from "@/lib/i18n/de";
import { assetStatusEnum } from "@/db/schema";
import {
  setEquipmentStatus,
  deleteEquipment,
} from "@/server/actions/equipment";

type Status = (typeof assetStatusEnum.enumValues)[number];

const STATUS_LABEL: Record<Status, string> = {
  einsatzbereit: de.status.einsatzbereit,
  wartung: de.status.wartung,
  ausser_dienst: de.status.ausser_dienst,
};

export function EquipmentControls({
  equipmentId,
  status,
}: {
  equipmentId: string;
  status: Status;
}) {
  const router = useRouter();
  const [pending, startTransition] = React.useTransition();
  const [error, setError] = React.useState<string | null>(null);

  function onStatus(next: Status) {
    setError(null);
    startTransition(async () => {
      const res = await setEquipmentStatus({ id: equipmentId, status: next });
      if (!res.ok) {
        setError(res.error);
        return;
      }
      router.refresh();
    });
  }

  function onDelete() {
    if (!window.confirm(de.verwaltung.loeschenBestaetigen)) return;
    setError(null);
    startTransition(async () => {
      const res = await deleteEquipment({ id: equipmentId });
      if (!res.ok) {
        setError(res.error);
        return;
      }
      router.push("/verwaltung/geraete");
      router.refresh();
    });
  }

  return (
    <div className="flex flex-wrap items-center gap-3 rounded border border-rand bg-white p-4">
      <label className="text-sm font-medium text-anthrazit" htmlFor="estatus">
        {de.verwaltung.status}
      </label>
      <select
        id="estatus"
        className="h-9 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={status}
        disabled={pending}
        onChange={(e) => onStatus(e.target.value as Status)}
      >
        {assetStatusEnum.enumValues.map((v) => (
          <option key={v} value={v}>
            {STATUS_LABEL[v]}
          </option>
        ))}
      </select>
      <span className="flex-1" />
      <Button
        type="button"
        variant="outline"
        size="sm"
        disabled={pending}
        onClick={onDelete}
      >
        {de.verwaltung.loeschen}
      </Button>
      {error ? <span className="w-full text-sm text-signal">{error}</span> : null}
    </div>
  );
}
