"use client";

import { useState } from "react";
import { api, DeviceProfile, VehicleModel, VehicleType } from "@/lib/api";
import { useApi } from "@/hooks/useApi";
import { useLocale } from "@/i18n/LocaleProvider";
import { useVehicleTypes } from "@/lib/useVehicleTypes";
import {
  Button,
  Card,
  EmptyState,
  ErrorState,
  Field,
  Modal,
  Numeric,
  Select,
  SkeletonTable,
  StatusBadge,
} from "@/components/ui";

/**
 * The vehicle-model catalogue.
 *
 * <p>Exists so the add and import forms offer a choice rather than a text box. On a fleet of
 * hundreds a typed name produces "Ninebot MAX", "ninebot max" and "Ninebot Max G30" as three
 * models that no report can group, and nobody notices until the first fleet report is wrong.
 */

export function ModelsPanel({ profiles }: { profiles: DeviceProfile[] }) {
  const { t } = useLocale();
  const { options: vehicleTypeOptions, label: typeLabel } = useVehicleTypes();
  const models = useApi<VehicleModel[]>(() => api.vehicleModels(), []);
  const [adding, setAdding] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const [name, setName] = useState("");
  const [manufacturer, setManufacturer] = useState("");
  const [vehicleType, setVehicleType] = useState<VehicleType>("SCOOTER");
  const [defaultIotProfile, setDefaultIotProfile] = useState("");
  const [maxSpeedKmh, setMaxSpeedKmh] = useState("");
  const [rangeKm, setRangeKm] = useState("");

  function reset() {
    setName("");
    setManufacturer("");
    setVehicleType("SCOOTER");
    setDefaultIotProfile("");
    setMaxSpeedKmh("");
    setRangeKm("");
    setError(null);
  }

  async function create() {
    setBusy(true);
    setError(null);
    try {
      await api.createModel({
        name: name.trim(),
        manufacturer: manufacturer.trim() || null,
        vehicleType,
        defaultIotProfile: defaultIotProfile || null,
        maxSpeedKmh: maxSpeedKmh ? Number(maxSpeedKmh) : null,
        rangeKm: rangeKm ? Number(rangeKm) : null,
      });
      setAdding(false);
      reset();
      models.reload();
    } catch (e) {
      setError(e instanceof Error ? e.message : String(e));
    } finally {
      setBusy(false);
    }
  }

  async function retire(m: VehicleModel) {
    setBusy(true);
    try {
      await api.deleteModel(m.id);
      models.reload();
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <p className="max-w-2xl text-sm text-muted">{t("mdl.body")}</p>
        <Button variant="primary" onClick={() => setAdding(true)}>
          {t("mdl.add")}
        </Button>
      </div>

      {models.loading && !models.data && <SkeletonTable rows={5} />}
      {models.error ? <ErrorState onRetry={models.reload} /> : null}

      {models.data &&
        (models.data.length === 0 ? (
          <EmptyState icon={<span className="text-xl">🛴</span>} title={t("mdl.empty")} />
        ) : (
          <Card className="!p-0">
            <ul className="divide-y divide-line">
              {models.data.map((m) => (
                <li key={m.id} className="flex flex-wrap items-center gap-4 p-4">
                  <div className="min-w-[12rem] flex-1">
                    <p className="text-sm font-semibold">
                      {m.name}
                      {!m.active && (
                        <span className="ms-2">
                          <StatusBadge tone="neutral">{t("mdl.retired")}</StatusBadge>
                        </span>
                      )}
                    </p>
                    <p className="text-xs text-muted">
                      {[m.manufacturer, typeLabel(m.vehicleType)]
                        .filter(Boolean)
                        .join(" · ")}
                    </p>
                  </div>
                  <div className="flex flex-wrap items-center gap-2 text-xs text-muted">
                    {m.maxSpeedKmh != null && (
                      <span>
                        <Numeric>{m.maxSpeedKmh}</Numeric> km/h
                      </span>
                    )}
                    {m.rangeKm != null && (
                      <span>
                        <Numeric>{m.rangeKm}</Numeric> km
                      </span>
                    )}
                    {m.defaultIotProfile && (
                      <StatusBadge tone="info">{m.defaultIotProfile}</StatusBadge>
                    )}
                  </div>
                  {m.active && (
                    <Button variant="ghost" onClick={() => retire(m)} disabled={busy}>
                      {t("mdl.retire")}
                    </Button>
                  )}
                </li>
              ))}
            </ul>
          </Card>
        ))}

      <Modal
        open={adding}
        onClose={() => {
          setAdding(false);
          reset();
        }}
        title={t("mdl.add")}
        actions={
          <>
            <Button
              onClick={() => {
                setAdding(false);
                reset();
              }}
            >
              {t("common.cancel")}
            </Button>
            <Button
              variant="primary"
              onClick={create}
              disabled={busy || name.trim().length === 0}
            >
              {t("common.save")}
            </Button>
          </>
        }
      >
        <div className="space-y-4">
          <Field
            label={t("mdl.name")}
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Ninebot MAX G30"
          />
          <div className="grid gap-4 sm:grid-cols-2">
            <Field
              label={t("mdl.manufacturer")}
              value={manufacturer}
              onChange={(e) => setManufacturer(e.target.value)}
              placeholder="Segway-Ninebot"
            />
            <Select
              label={t("mdl.type")}
              value={vehicleType}
              onChange={(e) => setVehicleType(e.target.value as VehicleType)}
              options={vehicleTypeOptions}
            />
          </div>
          <Select
            label={t("mdl.defaultProfile")}
            value={defaultIotProfile}
            onChange={(e) => setDefaultIotProfile(e.target.value)}
            placeholder="-"
            options={profiles.map((p) => ({
              value: p.id,
              label: `${p.vendor}${p.model ? " " + p.model : ""} (${p.transport})`,
            }))}
          />
          <div className="grid gap-4 sm:grid-cols-2">
            <Field
              label={t("mdl.speed")}
              value={maxSpeedKmh}
              onChange={(e) => setMaxSpeedKmh(e.target.value)}
              inputMode="numeric"
              dir="ltr"
            />
            <Field
              label={t("mdl.range")}
              value={rangeKm}
              onChange={(e) => setRangeKm(e.target.value)}
              inputMode="numeric"
              dir="ltr"
            />
          </div>
          {error && <p className="text-sm text-danger">{error}</p>}
        </div>
      </Modal>
    </div>
  );
}
