"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import {
  Check,
  ChevronsUpDown,
  ChevronLeft,
  ChevronRight,
  Loader2,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { getCitiesAction } from "@/features/locations/actions/cities-actions";
import type { CityOption } from "@/features/packages/types/package-form.types";
import { FIX_PACKAGES_ADMIN } from "@/lib/strings";

const DEBOUNCE_MS = 400;

interface CityComboboxProps {
  value: number | null;
  selectedCityName?: string;
  onSelect: (city: CityOption | null) => void;
  disabled?: boolean;
  hasError?: boolean;
  id?: string;
  "aria-invalid"?: boolean;
  "aria-describedby"?: string;
}

export function CityCombobox({
  value,
  selectedCityName,
  onSelect,
  disabled,
  hasError,
  id,
  ...ariaProps
}: CityComboboxProps) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [cities, setCities] = useState<CityOption[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [lastPage, setLastPage] = useState(1);
  const [total, setTotal] = useState(0);
  const lastFetchKeyRef = useRef("");

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(search);
      setCurrentPage(1);
    }, DEBOUNCE_MS);
    return () => clearTimeout(timer);
  }, [search]);

  const fetchCities = useCallback(async () => {
    const fetchKey = `${debouncedSearch}::${currentPage}`;
    if (lastFetchKeyRef.current === fetchKey) return;

    lastFetchKeyRef.current = fetchKey;
    setIsLoading(true);

    try {
      const result = await getCitiesAction(
        debouncedSearch || undefined,
        currentPage
      );

      if (result.success && result.data) {
        setCities(
          result.data.data.map((c) => ({ id: Number(c.id), name: c.name }))
        );
        setLastPage(result.data.last_page);
        setTotal(result.data.total);
      }
    } catch {
      setCities([]);
    } finally {
      setIsLoading(false);
    }
  }, [debouncedSearch, currentPage]);

  useEffect(() => {
    if (open) {
      fetchCities();
    }
  }, [open, fetchCities]);

  useEffect(() => {
    if (!open) {
      setSearch("");
      setDebouncedSearch("");
      setCurrentPage(1);
      lastFetchKeyRef.current = "";
    }
  }, [open]);

  const displayLabel =
    value && selectedCityName
      ? selectedCityName
      : FIX_PACKAGES_ADMIN.SELECT_CITY;

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          id={id}
          variant="outline"
          role="combobox"
          aria-expanded={open}
          disabled={disabled}
          className={cn(
            "w-full justify-between font-normal",
            !value && "text-muted-foreground",
            hasError && "border-destructive"
          )}
          {...ariaProps}
        >
          <span className="truncate">
            {disabled ? FIX_PACKAGES_ADMIN.LOADING_CITIES : displayLabel}
          </span>
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent
        className="!w-[--radix-popover-trigger-width] p-0"
        align="start"
      >
        <Command shouldFilter={false}>
          <CommandInput
            placeholder={FIX_PACKAGES_ADMIN.SEARCH_CITY_PLACEHOLDER}
            value={search}
            onValueChange={setSearch}
          />
          <CommandList>
            {isLoading ? (
              <div className="flex items-center justify-center py-6">
                <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
              </div>
            ) : cities.length === 0 ? (
              <CommandEmpty>{FIX_PACKAGES_ADMIN.NO_CITIES_FOUND}</CommandEmpty>
            ) : (
              <CommandGroup>
                {cities.map((city) => (
                  <CommandItem
                    key={city.id}
                    value={String(city.id)}
                    onSelect={() => {
                      onSelect(city.id === value ? null : city);
                      setOpen(false);
                    }}
                  >
                    <Check
                      className={cn(
                        "mr-2 h-4 w-4",
                        value === city.id ? "opacity-100" : "opacity-0"
                      )}
                    />
                    {city.name}
                  </CommandItem>
                ))}
              </CommandGroup>
            )}
          </CommandList>
          {lastPage > 1 && (
            <div className="flex items-center justify-between border-t px-3 py-2">
              <Button
                type="button"
                variant="ghost"
                size="sm"
                disabled={currentPage <= 1 || isLoading}
                onClick={() => setCurrentPage((p) => p - 1)}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <span className="text-xs text-muted-foreground">
                {FIX_PACKAGES_ADMIN.PAGE} {currentPage} / {lastPage}
                {total > 0 && ` (${total})`}
              </span>
              <Button
                type="button"
                variant="ghost"
                size="sm"
                disabled={currentPage >= lastPage || isLoading}
                onClick={() => setCurrentPage((p) => p + 1)}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          )}
        </Command>
      </PopoverContent>
    </Popover>
  );
}
