import * as React from "react"
import { cn } from "../../../lib/utils"
import { ChevronDown } from "lucide-react"

const SelectContext = React.createContext<any>(null);

export const Select = ({ value, onValueChange, children }: any) => {
  const [open, setOpen] = React.useState(false);
  const containerRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  return (
    <SelectContext.Provider value={{ value, onValueChange, open, setOpen }}>
      <div className="relative" ref={containerRef}>{children}</div>
    </SelectContext.Provider>
  )
}

export const SelectTrigger = ({ className, children, leadingIcon, trailingIcon }: any) => {
  const { open, setOpen } = React.useContext(SelectContext);
  return (
    <button
      type="button"
      onClick={() => setOpen(!open)}
      className={cn(
        "flex h-12 w-full capitalize items-center gap-3 rounded-xl border border-input bg-background/50 px-4 py-3 text-sm transition-all duration-300 focus:outline-none focus:border-primary focus:bg-background disabled:cursor-not-allowed disabled:opacity-50 group",
        className
      )}
    >
      {leadingIcon && (
        <div className="w-4 h-4 flex items-center justify-center text-muted-foreground/60 group-focus:text-primary transition-colors shrink-0">
          {leadingIcon}
        </div>
      )}
      <div className="flex-1 text-left overflow-hidden whitespace-nowrap">
        {children}
      </div>
      <div className="flex items-center gap-2 shrink-0">
        {trailingIcon && (
          <div className="w-4 h-4 flex items-center justify-center text-muted-foreground/60 group-focus:text-primary transition-colors">
            {trailingIcon}
          </div>
        )}
        <ChevronDown className={cn("h-4 w-4 opacity-50 transition-transform duration-200", open && "rotate-180")} />
      </div>
    </button>
  )
}

export const SelectValue = ({ placeholder }: any) => {
  const { value } = React.useContext(SelectContext);
  return <span className="block truncate">{value || placeholder}</span>
}

export const SelectContent = ({ children, className }: any) => {
  const { open } = React.useContext(SelectContext);
  if (!open) return null;
  return (
    <div className={cn("absolute z-50 min-w-[8rem] overflow-hidden rounded-md border bg-white text-popover-foreground animate-in fade-in-80 mt-1 w-full max-h-60 overflow-y-auto", className)}>
      <div className="p-1">{children}</div>
    </div>
  )
}

export const SelectItem = ({ value, children, className }: any) => {
  const { onValueChange, setOpen } = React.useContext(SelectContext);
  return (
    <div
      onClick={() => { onValueChange(value); setOpen(false); }}
      className={cn("relative capitalize flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-2 text-sm outline-none hover:bg-slate-100 cursor-pointer", className)}
    >
      {children}
    </div>
  )
}
