"use client";
import { useId, useState } from "react";
import { Popover } from "radix-ui";
import { Check, ChevronsUpDown } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Field } from "@/components/shared/field";
import type { FinancialChargepoints } from "./contract";
export function SearchablePicker({
  name,
  label,
  choices,
  defaultValue = "",
  disabled,
  retry,
}: {
  name: string;
  label: string;
  choices: FinancialChargepoints;
  defaultValue?: string;
  disabled?: boolean;
  retry: () => void;
}) {
  const [open, setOpen] = useState(false),
    [search, setSearch] = useState(""),
    [value, setValue] = useState(defaultValue);
  const id = useId();
  const selected = choices.options.find((option) => option.value === value);
  const matches = choices.options
    .filter((option) => option.active !== false)
    .filter((option) =>
      option.label
        .toLocaleLowerCase()
        .includes(search.trim().toLocaleLowerCase()),
    );
  return (
    <div className="min-w-0 space-y-2">
      <span id={id} className="field-label text-sm">
        {label} *
      </span>
      <input type="hidden" name={name} value={selected?.value ?? ""} />
      <Popover.Root
        open={open}
        onOpenChange={(next) => {
          setOpen(next);
          if (next) setSearch("");
        }}
      >
        <Popover.Trigger asChild>
          <Button
            type="button"
            variant="outline"
            aria-labelledby={id}
            disabled={
              disabled || !!choices.error || choices.options.length === 0
            }
            className="w-full min-w-0 justify-between font-normal"
          >
            <span className="truncate">
              {selected?.label ?? `Select ${label.toLowerCase()}`}
            </span>
            <ChevronsUpDown className="size-4 shrink-0" aria-hidden="true" />
          </Button>
        </Popover.Trigger>
        <Popover.Content
          align="start"
          sideOffset={5}
          className="z-50 w-[var(--radix-popover-trigger-width)] rounded-lg border bg-popover p-3 text-popover-foreground shadow-lg"
          aria-label={`Choose ${label.toLowerCase()}`}
        >
          <Field
            type="search"
            label={`Search ${label.toLowerCase()}`}
            value={search}
            onChange={(event) => setSearch(event.target.value)}
            autoComplete="off"
            placeholder={
              name === "investor_user_id"
                ? "Name or email"
                : "Chargepoint name or status"
            }
          />
          <p role="status" className="my-2 text-xs text-muted-foreground">
            {matches.length} matches
          </p>
          <div className="max-h-56 overflow-y-auto">
            {matches.map((option) => (
              <Button
                key={option.value}
                type="button"
                variant="ghost"
                className="h-auto min-h-10 w-full justify-between whitespace-normal text-left font-normal"
                onClick={() => {
                  setValue(option.value);
                  setOpen(false);
                }}
              >
                <span className="break-words">{option.label}</span>
                {value === option.value && (
                  <Check className="size-4 shrink-0" aria-hidden="true" />
                )}
              </Button>
            ))}
            {matches.length === 0 && (
              <p className="py-3 text-sm text-muted-foreground">
                No matching {label.toLowerCase()} found.
              </p>
            )}
          </div>
        </Popover.Content>
      </Popover.Root>
      {choices.error ? (
        <p role="alert" className="text-sm text-destructive">
          {choices.error}{" "}
          <Button type="button" size="sm" variant="outline" onClick={retry}>
            Retry
          </Button>
        </p>
      ) : (
        choices.options.length === 0 && (
          <p className="text-sm text-muted-foreground">
            No {label.toLowerCase()} available.
          </p>
        )
      )}
    </div>
  );
}
