"use client";

import * as React from "react";
import { BarcodeIcon, CheckIcon, XIcon } from "lucide-react";

import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";

import { TONE_TEXT } from "./tones";

export type ScanResult = { kind: "found"; label: string } | { kind: "not-found"; code: string } | { kind: "lookup" } | null;

/**
 * Scanner-style field. A hardware scanner types digits and presses Enter; this captures that on focus
 * and shows the outcome of the last scan. `initialResult` seeds the state for documentation.
 * `catalogue` maps barcode to product name; without it every scan reports "not found".
 */
export function BarcodeScanInput({
  initialResult = null,
  disabled = false,
  catalogue,
}: {
  initialResult?: ScanResult;
  disabled?: boolean;
  catalogue?: Record<string, string>;
}) {
  const [result, setResult] = React.useState<ScanResult>(initialResult);
  const [focused, setFocused] = React.useState(false);
  const ref = React.useRef<HTMLInputElement>(null);

  function submit() {
    const code = ref.current?.value.trim() ?? "";
    if (!code) return;
    const label = catalogue?.[code] ?? null;
    setResult(label ? { kind: "found", label } : { kind: "not-found", code });
    if (ref.current) ref.current.value = "";
  }

  return (
    <div className="w-full max-w-md space-y-1.5">
      <div className="relative flex items-center">
        <BarcodeIcon className="pointer-events-none absolute left-2.5 size-4 text-muted-foreground" />
        <Input
          ref={ref}
          disabled={disabled}
          inputMode="numeric"
          aria-label="Scan or type a barcode"
          placeholder={disabled ? "Scanner unavailable" : "Scan barcode or type and press Enter"}
          className={cn("pl-8", focused && "border-ring")}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
          onKeyDown={(e) => {
            if (e.key === "Enter") {
              e.preventDefault();
              submit();
            }
          }}
        />
      </div>
      <p className={cn("flex h-4 items-center gap-1.5 text-xs", result?.kind === "found" ? TONE_TEXT.success : result?.kind === "not-found" ? TONE_TEXT.error : "text-muted-foreground")} role="status">
        {result?.kind === "lookup" ? (
          <>
            <Spinner className="size-3" /> Looking up product
          </>
        ) : result?.kind === "found" ? (
          <>
            <CheckIcon className="size-3.5" /> Added {result.label}
          </>
        ) : result?.kind === "not-found" ? (
          <>
            <XIcon className="size-3.5" /> No product with barcode <span className="tabular-nums">{result.code}</span>
          </>
        ) : disabled ? null : (
          focused ? "Ready to scan" : "Click here, then scan"
        )}
      </p>
    </div>
  );
}
