import { useQuery } from "@tanstack/react-query";
import * as React from "react";
import { useDebounce } from "use-debounce";
import {
  Command,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import Axios from "@/lib/Axios";
import { cn } from "@/lib/utils";
import { PaginationStructT } from "@/types/global";
import { UserListT } from "@/types/user";
import { Check } from "lucide-react";

export const searchProductsByName = async (query: string = "") => {
  const resp = await Axios.get(`/users/assignemployees?search=${query}&limit=5`)
    .then((res) => {
      return res.data.data || res.data;
    });

  return resp;
};

export function SearchReportTo({ selectedResult, onSelectResult }: any) {
  const [searchQuery, setSearchQuery] = React.useState("");

  const handleSelectResult = (data: UserListT | null) => {
    onSelectResult(data);
    // Optionally reset the search query upon selection
    // setSearchQuery('');
  };

  return (
    <Command
      shouldFilter={false}
      className="h-auto rounded-lg border border-b-0 shadow-md w-full"
    >
      <CommandInput
        value={searchQuery}
        onValueChange={(e) => {
          setSearchQuery(e);
        }}
        placeholder="Search for employee"
      />

      <SearchResults
        query={searchQuery}
        selectedResult={selectedResult}
        onSelectResult={handleSelectResult}
      />
    </Command>
  );
}

type ExtendedUserListT = UserListT & {
  title: string;
};

interface SearchResultsProps {
  query: string;
  selectedResult: UserListT;
  onSelectResult: (data: ExtendedUserListT | null) => void;
}

function SearchResults({
  query,
  selectedResult,
  onSelectResult,
}: SearchResultsProps) {
  const [debouncedSearchQuery] = useDebounce(query, 500);

  const {
    data,
    isLoading: isLoadingOrig,
    isError,
  } = useQuery<UserListT[]>({
    queryKey: ["search", debouncedSearchQuery],
    queryFn: () => searchProductsByName(debouncedSearchQuery),
    // Always fetch, even if query is empty
    enabled: true,
  });

  // To get around https://github.com/TanStack/query/issues/3584
  const isLoading = isLoadingOrig;

  return (
    <CommandList className="">
      {isLoading && <div className="p-4 text-sm">Loading...</div>}
      {isError && <div className="p-4 text-sm">Something went wrong</div>}
      {(data || []).map((dt) => (
        <CommandItem
          key={dt.id}
          onSelect={() => onSelectResult({ ...dt, title: dt.user.name })}
          value={dt.id + ""}
          className="cursor-pointer"
        >
          <Check
            className={cn(
              "mr-2 h-4 w-4",
              selectedResult?.id === dt.id ? "opacity-100" : "opacity-0"
            )}
          />
          {dt.user.name}
        </CommandItem>
      ))}
    </CommandList>
  );
}