"use client";

import { useCallback, useEffect, useState } from "react";
import type { SensorSummaryDto } from "@enode/core/api/dtos/sensors";
import { getSensors } from "@enode/core/api/sensors";
import { displaySerial } from "@enode/core/ble/auth/sat-wire";
import { sensorApiReason } from "@enode/core/sensor-access/api-errors";
import {
  isOrganisationSensor,
  sensorCanManage,
} from "@enode/core/sensor-access/sensor-management";
import { useTranslation, type TranslateFn } from "@enode/core/translations/hooks";
import { Button } from "@enode/ui/button";
import { SkeletonRows } from "@enode/ui/feedback/skeleton";
import { NavRow, NavRowDivider } from "@enode/ui/settings/nav-row";
import { SettingsCardGroup } from "@enode/ui/settings/settings-card-group";
import { TAP_TARGET } from "@enode/ui/tap-target";

type Load =
  | { status: "loading" }
  /** `unavailable`: 503 `signing_unavailable`, the server can't sign sensor access now. */
  | { status: "error"; unavailable: boolean }
  | { status: "ready"; sensors: SensorSummaryDto[] };

/**
 * The account's sensors as the app's "My sensors" names them: owner, member,
 * or provided by the organisation (the same rule and words as the tracking
 * app's `SensorRow`).
 */
function sensorRoleLine(sensor: SensorSummaryDto, t: TranslateFn): string {
  const manages = sensorCanManage(sensor);
  if (isOrganisationSensor(sensor) && !manages) {
    return t("Available through {organisation}", {
      organisation: sensor.organisation?.name || t("your organisation"),
    });
  }
  return manages ? t("Owner") : t("Member");
}

/**
 * Account › Devices › Sensors in the portal (17.11.26): the sensors this
 * account owns or may use (`GET /sensors`), read-only, each with its serial
 * and the account's role. Pairing, sharing, transfer and release need the
 * sensor at hand and stay in the enode app (Account › Devices › Sensors),
 * which the footer says.
 */
export function SensorsView() {
  const { t } = useTranslation();
  const [load, setLoad] = useState<Load>({ status: "loading" });
  const [reloadKey, setReloadKey] = useState(0);
  const reload = useCallback(() => {
    setLoad({ status: "loading" });
    setReloadKey((key) => key + 1);
  }, []);

  useEffect(() => {
    let cancelled = false;
    getSensors()
      .then((sensors) => {
        if (!cancelled) setLoad({ status: "ready", sensors });
      })
      .catch((err: unknown) => {
        console.error("Failed to load sensors:", err);
        if (cancelled) return;
        setLoad({
          status: "error",
          unavailable: sensorApiReason(err) === "signing_unavailable",
        });
      });
    return () => {
      cancelled = true;
    };
  }, [reloadKey]);

  return (
    <SettingsCardGroup
      header={t("My sensors")}
      findId="acc-devices.sensors"
      footer={t(
        "Pair and manage your sensors in the enode app under Account › Devices › Sensors.",
      )}
    >
      {load.status === "loading" && (
        <SkeletonRows rows={3} className="px-4 py-3" />
      )}
      {load.status === "error" && (
        // The same card the list renders in, so a failed load keeps the
        // page's shape (as the Recording list's error).
        <div role="alert" className="px-4 py-3">
          <p className="body-prominent text-foreground-default">
            {load.unavailable
              ? t("Sensor access unavailable")
              : t("Couldn't load your sensors.")}
          </p>
          {load.unavailable && (
            <p className="body-small mt-0.5 text-foreground-muted">
              {t("Sensor access is unavailable right now. Try again later.")}
            </p>
          )}
          <Button
            variant="neutral"
            size="rounded"
            className={`mt-3 ${TAP_TARGET}`}
            onClick={reload}
          >
            {t("Try again")}
          </Button>
        </div>
      )}
      {load.status === "ready" && load.sensors.length === 0 && (
        <NavRow
          label={t("No sensor yet")}
          sublabel={t(
            "No sensor is paired with your account yet. Connect one and pair it.",
          )}
        />
      )}
      {load.status === "ready" &&
        load.sensors.map((sensor, i) => (
          <div key={sensor.serial}>
            {i > 0 && <NavRowDivider inset="none" />}
            <NavRow
              label={displaySerial(sensor.serial)}
              value={sensorRoleLine(sensor, t)}
            />
          </div>
        ))}
    </SettingsCardGroup>
  );
}
