"use client";

/**
 * Finding a batch to add to a write-off or an internal issue (plan A). Batches come from the API earliest expiry
 * first per product, never stock in transit; a batch already on the document is not offered again.
 */

import * as React from "react";
import { PlusIcon, SearchIcon } from "lucide-react";

import { Button } from "@/components/ui/button";
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
import type { OpsBatchOption } from "@/lib/api";
import { formatDate } from "@/lib/format";
import { Loading } from "@/components/medora/loading";

export function BatchPicker({ load, taken, onAdd, label = "Find a product or batch" }: { load: (search: string) => Promise<OpsBatchOption[]>; taken: Set<number>; onAdd: (o: OpsBatchOption) => void; label?: string }) {
  const [q, setQ] = React.useState("");
  const [rows, setRows] = React.useState<OpsBatchOption[] | null>(null);
  React.useEffect(() => {
    let live = true;
    const t = setTimeout(() => {
      load(q)
        .then((r) => live && setRows(r))
        .catch(() => live && setRows([]));
    }, 250);
    return () => {
      live = false;
      clearTimeout(t);
    };
  }, [q, load]);
  const shown = (rows ?? []).filter((r) => !taken.has(r.batchId)).slice(0, 30);
  return (
    <div className="space-y-2">
      <InputGroup>
        <InputGroupAddon>
          <SearchIcon />
        </InputGroupAddon>
        <InputGroupInput aria-label={label} placeholder={label} value={q} onChange={(e) => setQ(e.target.value)} />
      </InputGroup>
      {rows === null ? (
        <Loading what="batches" shape="list" rows={4} />
      ) : shown.length ? (
        <ul className="max-h-56 divide-y divide-[var(--color-border-subtle)] overflow-y-auto rounded-lg border border-[var(--color-border-panel)] text-sm bg-card">
          {shown.map((o) => (
            <li key={o.batchId} className="flex items-center justify-between gap-3 px-3 py-1.5">
              <span>
                <span className="font-medium">{o.name}</span>
                <span className="block text-xs text-muted-foreground">
                  <span className="font-mono">{o.batch || "No batch number"}</span>
                  {o.expiryDate ? ` · expires ${formatDate(o.expiryDate)}` : ""} · {o.available.toLocaleString("en-US")} {o.unit || "units"}
                  {o.location ? ` · ${o.location}` : ""}
                </span>
              </span>
              <Button size="sm" variant="outline" onClick={() => onAdd(o)}>
                <PlusIcon />
                Add
              </Button>
            </li>
          ))}
        </ul>
      ) : (
        <p className="text-sm text-muted-foreground">{q ? "No batch with stock matches." : "No stock here."}</p>
      )}
    </div>
  );
}
