"use client";

import { useEffect, useState } from "react";
import { getBleService } from "@enode/core/ble";
import {
  connectionChecklist,
  recordConnectionCheck,
  runConnectionCheck,
  type ConnectionCheckItem,
  type ConnectionCheckResult,
} from "@enode/core/ble/connection-check";
import {
  useTranslation,
  type TranslateFn,
} from "@enode/core/translations/hooks";
import { BottomSheetCard } from "@enode/ui/bottom-sheet-card";
import { Button } from "@enode/ui/button";
import {
  AlertIcon,
  CheckCircleIcon,
  InfoIcon,
} from "@enode/ui/feedback/icons";
import { openSupportReport } from "@enode/ui/feedback/support-report-store";
import { formatFirmware } from "./connect-sensor-view";

type Props = {
  open: boolean;
  onClose: () => void;
  // Listen for advertising sensors. False while a pooled sensor reconnects:
  // the native scanner is shared and this check's stop would end that scan.
  scan: boolean;
  // Developer-facing message of the connect attempt that failed before the
  // check; it travels in the report and is never shown.
  lastConnectError: string | null;
};

/**
 * The "Sensor doesn't connect?" check of the connect sheet: runs the BLE
 * connection check on open, shows what it found as a checklist, and sends the
 * result to support through the regular report sheet.
 */
export function SensorCheckSheet({ open, onClose, scan, lastConnectError }: Props) {
  const { t } = useTranslation();
  const [result, setResult] = useState<ConnectionCheckResult | null>(null);

  // One check per open. `scan` and `lastConnectError` are read at that moment;
  // a later change must not restart a running check.
  /* eslint-disable react-hooks/set-state-in-effect */
  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setResult(null);
    void runConnectionCheck({
      service: getBleService(),
      scan,
      lastConnectError,
    }).then((next) => {
      if (!cancelled) setResult(next);
    });
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);
  /* eslint-enable react-hooks/set-state-in-effect */

  function sendToSupport() {
    if (!result) return;
    recordConnectionCheck(result);
    openSupportReport(undefined, {
      includes: [t("Sensor connection check")],
    });
    onClose();
  }

  return (
    <BottomSheetCard
      open={open}
      onClose={onClose}
      ariaLabel={t("Sensor check")}
      zIndex={110}
      innerClassName="max-w-md"
    >
      <div className="px-6 pb-2 pt-6">
        <h2 className="heading-large">{t("Sensor check")}</h2>
        <SensorCheckView
          items={result ? connectionChecklist(result) : null}
          t={t}
        />
        <div className="mt-5 flex flex-col gap-3">
          <Button
            variant="primary"
            size="large"
            disabled={!result}
            onClick={sendToSupport}
          >
            {t("Send to support")}
          </Button>
          <Button variant="neutral" size="large" onClick={onClose}>
            {t("Close")}
          </Button>
        </div>
      </div>
    </BottomSheetCard>
  );
}

/** The checklist body; `items` is null while the check is running. */
export function SensorCheckView({
  items,
  t,
}: {
  items: ConnectionCheckItem[] | null;
  t: TranslateFn;
}) {
  if (!items) {
    return (
      <p className="body-normal mt-1 text-foreground-muted" role="status">
        {t("Checking Bluetooth and looking for sensors nearby…")}
      </p>
    );
  }
  return (
    <>
      <ul className="mt-3 flex flex-col gap-2">
        {items.map((item, index) => {
          const line = describeItem(item, t);
          return (
            // Items have no id of their own (two sensors give two firmware
            // lines) and the list never reorders.
            <li key={index} className="flex items-start gap-2">
              <LevelIcon level={line.level} />
              <span className="body-normal text-foreground-default">
                {line.text}
              </span>
            </li>
          );
        })}
      </ul>
      <p className="body-small mt-3 text-foreground-muted">
        {t("Still not working? Send this check to support.")}
      </p>
    </>
  );
}

type Level = "ok" | "problem" | "hint";

function LevelIcon({ level }: { level: Level }) {
  const className = "mt-0.5 size-5 shrink-0";
  if (level === "ok") {
    return <CheckCircleIcon className={`${className} text-feedback-success`} />;
  }
  if (level === "problem") {
    return <AlertIcon className={`${className} text-feedback-error`} />;
  }
  return <InfoIcon className={`${className} text-foreground-muted`} />;
}

type Line = { level: Level; text: string };
type ItemOf<Id extends ConnectionCheckItem["id"]> = Extract<
  ConnectionCheckItem,
  { id: Id }
>;

// Copy stays inline as literals so every line is extractable for translation.
function describeItem(item: ConnectionCheckItem, t: TranslateFn): Line {
  switch (item.id) {
    case "bluetooth":
      return describeBluetooth(item.status, t);
    case "bluetooth-permission":
      return describeBluetoothPermission(item.status, t);
    case "location":
      return describeLocation(item.status, t);
    case "scan":
      return describeScan(item, t);
    case "battery":
      return describeBattery(item, t);
    case "firmware":
      return {
        level: "ok",
        text: t("Sensor version {version}", {
          version: formatFirmware(item.version),
        }),
      };
  }
}

function describeBluetooth(
  status: ItemOf<"bluetooth">["status"],
  t: TranslateFn,
): Line {
  switch (status) {
    case "ok":
      return { level: "ok", text: t("Bluetooth is on.") };
    case "off":
      return {
        level: "problem",
        text: t("Bluetooth is off. Turn it on in your device settings."),
      };
    case "unauthorized":
      return {
        level: "problem",
        text: t(
          "Enode isn't allowed to use Bluetooth. Allow it for Enode in your device settings.",
        ),
      };
    case "unsupported":
      return {
        level: "problem",
        text: t("This device doesn't support Bluetooth sensors."),
      };
    case "unknown":
      return { level: "hint", text: t("Couldn't read the Bluetooth state.") };
  }
}

function describeBluetoothPermission(
  status: ItemOf<"bluetooth-permission">["status"],
  t: TranslateFn,
): Line {
  switch (status) {
    case "ok":
      return { level: "ok", text: t("Bluetooth access is allowed.") };
    case "denied":
      return {
        level: "problem",
        text: t(
          'Bluetooth access is denied. Allow "Nearby devices" for Enode in your device settings.',
        ),
      };
    case "undecided":
      return {
        level: "hint",
        text: t(
          "Bluetooth access hasn't been allowed yet. Allow it when your device asks.",
        ),
      };
  }
}

function describeLocation(
  status: ItemOf<"location">["status"],
  t: TranslateFn,
): Line {
  switch (status) {
    case "ok":
      return { level: "ok", text: t("Location access is allowed.") };
    case "permission-denied":
      return {
        level: "problem",
        text: t(
          "Location access is denied. This Android version needs it to find sensors. Allow it for Enode in your device settings.",
        ),
      };
    case "permission-undecided":
      return {
        level: "hint",
        text: t(
          "Location access hasn't been allowed yet. This Android version needs it to find sensors.",
        ),
      };
    case "services-off":
      return {
        level: "problem",
        text: t(
          "Location is switched off. This Android version needs it to find sensors. Turn it on in your device settings.",
        ),
      };
  }
}

function describeScan(item: ItemOf<"scan">, t: TranslateFn): Line {
  if (item.status === "found") {
    return item.weak
      ? {
          level: "problem",
          text: t(
            "A sensor was found, but its signal is weak. Hold it next to your device.",
          ),
        }
      : {
          level: "ok",
          text: t(
            "{count, plural, one {# sensor found nearby.} other {# sensors found nearby.}}",
            { count: item.count },
          ),
        };
  }
  if (item.status === "none") {
    return {
      level: "problem",
      text: t(
        "No sensor found nearby. Check that the sensor is switched on and close to your device.",
      ),
    };
  }
  return { level: "problem", text: t("Couldn't search for sensors.") };
}

function describeBattery(item: ItemOf<"battery">, t: TranslateFn): Line {
  if (item.status === "unknown") {
    return {
      level: "hint",
      text: t(
        "A sensor with an empty battery can't be found. Charge it and try again.",
      ),
    };
  }
  const percent = Math.round(item.percent);
  return item.status === "low"
    ? {
        level: "problem",
        text: t("Sensor battery is low ({percent}%). Charge the sensor.", {
          percent,
        }),
      }
    : { level: "ok", text: t("Sensor battery: {percent}%", { percent }) };
}
