"use client";

import * as React from "react";
import { ChevronsUpDown } from "lucide-react";

import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";

import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";

const POPOVER_WIDTH = "w-full";

type ComboboxT<T> = {
  children: React.ReactElement;
  onSelect: (dt: T) => void;
  placeholder?: string;
};

export function Combobox<T = any>({
  onSelect,
  placeholder,
  children,
}: ComboboxT<T>) {
  const [open, setOpen] = React.useState(false);
  const [selected, setSelected] = React.useState<any | undefined>();

  const handleSetActive = React.useCallback((data: T) => {
    setSelected(data);
    // console.log(data);
    onSelect(data);
    // OPTIONAL: close the combobox upon selection
    // setOpen(false);
  }, []);

  const displayName = selected ? selected.title : placeholder;

  const childWithProps = React.cloneElement(children, {
    selectedResult: selected,
    onSelectResult: handleSetActive,
  });

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          className={cn("justify-between font-normal", "w-full text-gray-500")}
        >
          {displayName}

          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>

      <PopoverContent side="bottom" className={cn("p-0", "w-96")}>
        {/* <Search selectedResult={selected} onSelectResult={handleSetActive} /> */}
        {childWithProps}
      </PopoverContent>
    </Popover>
  );
}
