import * as React from "react";
import { Button } from "@/shared/common/ui/button";
import {
  Popover,
  PopoverTrigger,
  PopoverContent,
} from "@/shared/common/ui/popover";
import {
  Command,
  CommandInput,
  CommandList,
  CommandItem,
  CommandEmpty,
  CommandGroup,
} from "@/shared/common/ui/command";
import { CheckIcon, ChevronDown } from "lucide-react";
import { cn } from "@/shared/lib/utils";

const normalizeSearchText = (value: string) =>
  value.normalize("NFKC").toLocaleLowerCase().replace(/\s+/g, " ").trim();

interface SingleSelectProps {
  options: { label: string; value: string }[];
  value?: string;
  placeholder?: string;
  onValueChange: (value: string) => void;
  className?: string;
}

export const SingleSelect = React.forwardRef<
  HTMLButtonElement,
  SingleSelectProps
>(
  (
    {
      options = [],
      value,
      placeholder = "Select an option",
      onValueChange,
      className,
      ...props
    },
    ref,
  ) => {
    const [isOpen, setIsOpen] = React.useState(false);
    const [searchQuery, setSearchQuery] = React.useState("");

    const normalizedQuery = normalizeSearchText(searchQuery);
    const filteredOptions = options.filter((opt) =>
      normalizeSearchText(opt.label).includes(normalizedQuery),
    );

    const selectedOption = options.find((o) => o.value === value);

    const handleSelect = (val: string) => {
      onValueChange(val);
      setIsOpen(false);
    };

    return (
      <Popover open={isOpen} onOpenChange={setIsOpen}>
        <PopoverTrigger asChild>
          <Button
            ref={ref}
            {...props}
            className={cn(
              "flex h-10 w-full min-w-0 max-w-full shrink items-center justify-between overflow-hidden rounded-md border border-gray-300 bg-white text-gray-900",
              "px-3 py-2 text-sm font-normal shadow-sm transition-all duration-150",
              "hover:bg-gray-50 hover:border-gray-400 focus:ring-2 focus:ring-primary-200 focus:border-primary-500",
              "dark:border-gray-600 dark:bg-gray-700 dark:text-gray-200",
              "dark:hover:bg-gray-600 dark:hover:border-gray-500",
              isOpen &&
                "border-primary-500 ring-2 ring-primary-100 dark:ring-primary-900/40",
              className,
            )}
          >
            <span
              className={cn(
                "block min-w-0 flex-1 truncate text-left",
                selectedOption
                  ? "font-medium text-gray-900 dark:text-gray-100"
                  : "font-normal text-gray-500 dark:text-gray-400",
              )}
              title={selectedOption ? selectedOption.label : undefined}
            >
              {selectedOption ? selectedOption.label : placeholder}
            </span>
            <ChevronDown
              className={cn(
                "ml-2 h-4 w-4 shrink-0 text-gray-500 transition-transform duration-200",
                "dark:text-gray-400",
                isOpen && "rotate-180",
              )}
            />
          </Button>
        </PopoverTrigger>

        <PopoverContent
          className="w-[var(--radix-popover-trigger-width)] max-w-full p-0 border border-gray-200 rounded-lg shadow-lg bg-white dark:border-gray-600 dark:bg-gray-800"
          align="start"
        >
          <Command shouldFilter={false}>
            <CommandInput
              placeholder="Search..."
              value={searchQuery}
              onValueChange={setSearchQuery}
              className="text-sm dark:text-gray-200 dark:placeholder:text-gray-500"
            />
            <CommandList
              className="max-h-60 overflow-y-auto"
              onWheel={(event) => event.stopPropagation()}
            >
              <CommandEmpty className="py-3 text-gray-500 text-sm text-center dark:text-gray-400">
                No results found.
              </CommandEmpty>

              <CommandGroup>
                {filteredOptions.map((opt) => (
                  <CommandItem
                    key={opt.value}
                    value={opt.label}
                    onSelect={() => handleSelect(opt.value)}
                    className={cn(
                      "cursor-pointer flex items-center justify-between px-3 py-2 rounded-md text-sm transition-colors duration-100",

                      "hover:bg-primary-50 hover:text-primary-700",
                      "focus:bg-primary-50",

                      "dark:hover:bg-primary-700 dark:focus:bg-primary-700 dark:text-gray-200",

                      // Remove cmdk's default active styling
                      "data-[selected=true]:text-inherit",
                      "data-[selected=true]:bg-transparent",

                      value === opt.value &&
                        "bg-primary-100 text-primary-700 font-medium dark:bg-primary-900/50 dark:text-primary-300",
                    )}
                  >
                    <span className="min-w-0 flex-1 truncate">{opt.label}</span>
                    {value === opt.value && (
                      <CheckIcon className="h-4 w-4 shrink-0 text-primary-600" />
                    )}
                  </CommandItem>
                ))}
              </CommandGroup>
            </CommandList>
          </Command>
        </PopoverContent>
      </Popover>
    );
  },
);

SingleSelect.displayName = "SingleSelect";
