"use client";

import React, {
  useCallback,
  useEffect,
  useMemo,
  useState,
  useTransition,
} from "react";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Search, Loader2, X } from "lucide-react";
import { useDebounce } from "@/hooks/useDebounce";
import { useAction } from "@/hooks/useAction";
import { searchOrders } from "@/actions/orders";
import { formatCurrency } from "@/lib/format";

interface OrderReferenceFieldProps {
  value: string;
  onChange: (value: string) => void;
  label?: string;
  placeholder?: string;
  disabled?: boolean;
}

interface OrderSearchResult {
  id: string;
  title: string;
  subtitle: string;
  amount_total?: string | number;
}

export function OrderReferenceField({
  value,
  onChange,
  label,
  placeholder = "Bestellung suchen...",
  disabled = false,
}: OrderReferenceFieldProps) {
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState("");
  const debouncedQuery = useDebounce(query, 300);
  const [results, setResults] = useState<OrderSearchResult[]>([]);
  const [selectedLabel, setSelectedLabel] = useState<string>("");
  const [isPending, startTransition] = useTransition();
  const { execute } = useAction(searchOrders);

  const displayValue = useMemo(() => {
    if (selectedLabel) return selectedLabel;
    if (value) return `Bestellung: ${value.slice(0, 8)}`;
    return "";
  }, [selectedLabel, value]);

  useEffect(() => {
    if (!value) setSelectedLabel("");
  }, [value]);

  const handleSelect = useCallback(
    (order: OrderSearchResult) => {
      onChange(order.id);
      setSelectedLabel(
        `${order.title}${order.subtitle ? ` · ${order.subtitle}` : ""}`,
      );
      setOpen(false);
      setQuery("");
    },
    [onChange],
  );

  useEffect(() => {
    const trimmedQuery = debouncedQuery.trim();
    if (!trimmedQuery) {
      setResults([]);
      return;
    }

    // BOLT: Instant UUID Resolution.
    // If the input is a valid UUID, we skip the broad search and attempt to resolve it directly.
    const uuidRegex =
      /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    const isUuid = uuidRegex.test(trimmedQuery);

    startTransition(async () => {
      const response = await execute({
        query: trimmedQuery,
        limit: isUuid ? 1 : 10,
      });
      if (response?.success && Array.isArray(response.data)) {
        const normalizedResults: OrderSearchResult[] = response.data.map(
          (item: any) => ({
            id: item.id ?? "",
            title: item.title ?? "",
            subtitle: item.subtitle ?? "",
            amount_total: item.amount_total,
          }),
        );

        setResults(normalizedResults);

        // Auto-select if it's a direct UUID match and exactly one result
        if (isUuid && normalizedResults.length === 1) {
          handleSelect(normalizedResults[0]);
        }
      }
    });
  }, [debouncedQuery, execute, handleSelect]);

  const handleClear = () => {
    onChange("");
    setSelectedLabel("");
    setQuery("");
  };

  return (
    <div className="space-y-2">
      {label && (
        <label className="block text-sm font-medium text-foreground">
          {label}
        </label>
      )}

      <Popover open={open} onOpenChange={(nextOpen) => setOpen(nextOpen)}>
        <PopoverTrigger asChild>
          <Button
            variant="outline"
            className="w-full justify-between text-left"
            disabled={disabled}
            type="button"
          >
            <span
              className={
                displayValue ? "truncate" : "text-muted-foreground truncate"
              }
            >
              {displayValue || placeholder}
            </span>
            {value ? (
              <X
                className="h-4 w-4 text-muted-foreground"
                aria-label="Auswahl löschen"
                onClick={(event) => {
                  event.stopPropagation();
                  handleClear();
                }}
              />
            ) : (
              <Search
                className="h-4 w-4 text-muted-foreground"
                aria-hidden="true"
              />
            )}
          </Button>
        </PopoverTrigger>

        <PopoverContent className="w-full p-0">
          <Command>
            <CommandInput
              placeholder={placeholder}
              value={query}
              onValueChange={setQuery}
              autoFocus
            />
            <CommandList>
              <CommandEmpty>
                {isPending ? "Suche..." : "Keine Bestellungen gefunden."}
              </CommandEmpty>
              <CommandGroup>
                {results.map((order) => (
                  <CommandItem
                    key={order.id}
                    onSelect={() => handleSelect(order)}
                  >
                    <div className="flex flex-col gap-0.5">
                      <span className="truncate font-medium">
                        {order.title}
                      </span>
                      <span className="text-[11px] text-muted-foreground">
                        {order.subtitle}
                      </span>
                    </div>
                  </CommandItem>
                ))}
              </CommandGroup>
            </CommandList>
          </Command>
        </PopoverContent>
      </Popover>
    </div>
  );
}
