"use client";

import { useEffect, useId, useRef, useState } from "react";
import { Popover } from "radix-ui";
import { Check, ChevronsUpDown, X } from "lucide-react";
import { Field } from "@/components/shared/field";
import { Button } from "@/components/ui/button";

type PickerKind = "locations" | "users";
type PickerOption = { id: string; label: string };
type PickerProps = {
  kind: PickerKind;
  label: string;
  selectedIds: string[];
  onChange: (ids: string[]) => void;
};

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

async function readLookupResponse(url: string, signal: AbortSignal) {
  let response: Response;
  try {
    response = await fetch(url, { cache: "no-store", signal });
  } catch (error) {
    if (error instanceof DOMException && error.name === "AbortError") throw error;
    throw new Error("The options could not be loaded. Please try again.");
  }

  const value: unknown = await response.json().catch(() => null);
  if (!response.ok) {
    const message = isRecord(value) && typeof value.error === "string"
      ? value.error
      : "The options could not be loaded. Please try again.";
    throw new Error(message);
  }
  if (!isRecord(value) || !Array.isArray(value.options)) {
    throw new Error("The options service returned an unsupported response.");
  }
  return value;
}

function locationOptionsFrom(value: Record<string, unknown>): PickerOption[] {
  const options: PickerOption[] = [];
  for (const entry of value.options as unknown[]) {
    if (
      !isRecord(entry) ||
      typeof entry.id !== "string" ||
      typeof entry.name !== "string"
    ) {
      throw new Error("The location service returned unsupported options.");
    }
    options.push({ id: entry.id, label: entry.name });
  }
  return options;
}

function userOptionsFrom(value: Record<string, unknown>): {
  options: PickerOption[];
  nextPage: number | null;
} {
  const options: PickerOption[] = [];
  for (const entry of value.options as unknown[]) {
    if (
      !isRecord(entry) ||
      typeof entry.id !== "string" ||
      typeof entry.label !== "string"
    ) {
      throw new Error("The customer service returned unsupported options.");
    }
    options.push({ id: entry.id, label: entry.label });
  }
  const pagination = value.pagination;
  if (
    !isRecord(pagination) ||
    typeof pagination.hasNextPage !== "boolean" ||
    typeof pagination.nextPage !== "number"
  ) {
    throw new Error("The customer service returned unsupported pagination data.");
  }
  return {
    options,
    nextPage: pagination.hasNextPage ? pagination.nextPage : null,
  };
}

function appendUniqueOptions(
  current: PickerOption[],
  incoming: PickerOption[],
): PickerOption[] {
  const options = new Map(current.map((option) => [option.id, option]));
  for (const option of incoming) options.set(option.id, option);
  return [...options.values()];
}

export function VoucherIdPicker({
  kind,
  label,
  selectedIds,
  onChange,
}: PickerProps) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");
  const [options, setOptions] = useState<PickerOption[]>([]);
  const [selectedOptions, setSelectedOptions] = useState<Record<string, PickerOption>>({});
  const [nextPage, setNextPage] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState("");
  const [selectionError, setSelectionError] = useState("");
  const [retryKey, setRetryKey] = useState(0);
  const moreController = useRef<AbortController | null>(null);
  const labelId = useId();

  useEffect(() => {
    if (kind !== "locations") return;
    const controller = new AbortController();

    void readLookupResponse(
      "/api/vouchers/options?kind=locations",
      controller.signal,
    )
      .then((value) => {
        if (!controller.signal.aborted) setOptions(locationOptionsFrom(value));
      })
      .catch((cause) => {
        if (!controller.signal.aborted) {
          setError(
            cause instanceof Error
              ? cause.message
              : "The location service could not load options.",
          );
        }
      })
      .finally(() => {
        if (!controller.signal.aborted) setLoading(false);
      });

    return () => controller.abort();
  }, [kind, retryKey]);

  useEffect(() => {
    if (kind !== "users") return;
    const controller = new AbortController();
    const timer = window.setTimeout(() => {
      void readLookupResponse(
        `/api/vouchers/options?kind=users&search=${encodeURIComponent(search)}&page=1`,
        controller.signal,
      )
        .then((value) => {
          if (controller.signal.aborted) return;
          const result = userOptionsFrom(value);
          setOptions(result.options);
          setNextPage(result.nextPage);
        })
        .catch((cause) => {
          if (!controller.signal.aborted) {
            setError(
              cause instanceof Error
                ? cause.message
                : "The customer service could not load options.",
            );
          }
        })
        .finally(() => {
          if (!controller.signal.aborted) setLoading(false);
        });
    }, search ? 250 : 0);

    return () => {
      window.clearTimeout(timer);
      controller.abort();
      moreController.current?.abort();
    };
  }, [kind, search, retryKey]);

  const visibleOptions = kind === "locations"
    ? options.filter((option) =>
        option.label.toLocaleLowerCase().includes(search.trim().toLocaleLowerCase()),
      )
    : options;

  function updateSearch(value: string) {
    setSearch(value);
    setSelectionError("");
    if (kind === "users") {
      setOptions([]);
      setNextPage(null);
      setLoading(true);
      setError("");
    }
    moreController.current?.abort();
    setLoadingMore(false);
  }

  function retryLookup() {
    setLoading(true);
    setLoadingMore(false);
    setError("");
    setRetryKey((current) => current + 1);
  }

  function toggleOption(option: PickerOption) {
    setSelectionError("");
    if (selectedIds.includes(option.id)) {
      onChange(selectedIds.filter((id) => id !== option.id));
      setSelectedOptions((current) => {
        const selected = { ...current };
        delete selected[option.id];
        return selected;
      });
      return;
    }
    if (selectedIds.length >= 100) {
      setSelectionError("You can select up to 100 options.");
      return;
    }
    onChange([...selectedIds, option.id]);
    setSelectedOptions((current) => ({ ...current, [option.id]: option }));
  }

  function removeOption(id: string) {
    onChange(selectedIds.filter((selectedId) => selectedId !== id));
    setSelectedOptions((current) => {
      const selected = { ...current };
      delete selected[id];
      return selected;
    });
    setSelectionError("");
  }

  async function loadMoreUsers() {
    if (kind !== "users" || nextPage === null || loadingMore) return;
    const controller = new AbortController();
    moreController.current = controller;
    setLoadingMore(true);
    setError("");
    try {
      const value = await readLookupResponse(
        `/api/vouchers/options?kind=users&search=${encodeURIComponent(search)}&page=${nextPage}`,
        controller.signal,
      );
      const result = userOptionsFrom(value);
      if (controller.signal.aborted) return;
      setOptions((current) => appendUniqueOptions(current, result.options));
      setNextPage(result.nextPage);
    } catch (cause) {
      if (!controller.signal.aborted) {
        setError(
          cause instanceof Error
            ? cause.message
            : "The customer service could not load more options.",
        );
      }
    } finally {
      if (!controller.signal.aborted) setLoadingMore(false);
    }
  }

  function clearSelection() {
    onChange([]);
    setSelectedOptions({});
    setSelectionError("");
  }

  return (
    <div className="min-w-0 space-y-2">
      <div className="flex items-center justify-between gap-2">
        <span id={labelId} className="field-label text-sm">{label}</span>
        {selectedIds.length > 0 && (
          <Button type="button" size="sm" variant="ghost" onClick={clearSelection}>
            Clear
          </Button>
        )}
      </div>
      <Popover.Root open={open} onOpenChange={setOpen}>
        <Popover.Trigger asChild>
          <Button
            type="button"
            variant="outline"
            aria-labelledby={labelId}
            aria-describedby={`${labelId}-selection`}
            aria-expanded={open}
            className="w-full min-w-0 justify-between font-normal"
          >
            <span className="truncate">
              {selectedIds.length > 0
                ? `${selectedIds.length} selected`
                : `Choose ${label.toLowerCase()}`}
            </span>
            <ChevronsUpDown className="size-4 shrink-0" aria-hidden="true" />
          </Button>
        </Popover.Trigger>
        <Popover.Portal>
          <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) => updateSearch(event.target.value)}
              autoComplete="off"
              placeholder={kind === "locations" ? "Search location name" : "Search name or email"}
            />
            <div className="my-2 max-h-56 overflow-y-auto" aria-live="polite">
              {loading && <p className="py-3 text-sm text-muted-foreground">Loading options…</p>}
              {!loading && !error && visibleOptions.length === 0 && (
                <p className="py-3 text-sm text-muted-foreground">
                  No matching {label.toLowerCase()} found.
                </p>
              )}
              {(!error || visibleOptions.length > 0) && visibleOptions.map((option) => {
                const selected = selectedIds.includes(option.id);
                return (
                  <Button
                    key={option.id}
                    type="button"
                    variant="ghost"
                    aria-pressed={selected}
                    disabled={!selected && selectedIds.length >= 100}
                    className="h-auto min-h-10 w-full justify-between whitespace-normal text-left font-normal"
                    onClick={() => toggleOption(option)}
                  >
                    <span className="break-words">{option.label}</span>
                    {selected && <Check className="size-4 shrink-0" aria-hidden="true" />}
                  </Button>
                );
              })}
            </div>
            {error && (
              <p role="alert" className="text-sm text-destructive">
                {error} {" "}
                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  onClick={retryLookup}
                >
                  Retry
                </Button>
              </p>
            )}
            {!loading && !error && kind === "users" && nextPage !== null && (
              <Button
                type="button"
                variant="outline"
                className="mt-2 w-full"
                disabled={loadingMore}
                onClick={() => void loadMoreUsers()}
              >
                {loadingMore ? "Loading…" : "Load more customers"}
              </Button>
            )}
          </Popover.Content>
        </Popover.Portal>
      </Popover.Root>
      {selectedIds.length > 0 && (
        <div className="flex flex-wrap gap-2" aria-label={`Selected ${label.toLowerCase()}`}>
          {selectedIds.map((id) => {
            const option = selectedOptions[id];
            const optionLabel = option?.label ?? `Selected ${kind === "locations" ? "location" : "customer"}`;
            return (
              <span
                key={id}
                className="inline-flex max-w-full items-center gap-1 rounded-full border bg-muted px-2.5 py-1 text-xs"
              >
                <span className="truncate">{optionLabel}</span>
                <button
                  type="button"
                  aria-label={`Remove ${optionLabel}`}
                  className="rounded-full p-0.5 hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                  onClick={() => removeOption(id)}
                >
                  <X className="size-3.5" aria-hidden="true" />
                </button>
              </span>
            );
          })}
        </div>
      )}
      {selectionError && <p role="alert" className="text-sm text-destructive">{selectionError}</p>}
      <p id={`${labelId}-selection`} className="text-xs text-muted-foreground">
        Optional · {selectedIds.length}/100 selected
      </p>
    </div>
  );
}
