import * as React from "react"
import { Check, ChevronsUpDown, Search } from "lucide-react"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { ScrollArea } from "@/components/ui/scroll-area"
import { SettingInput } from "./settings-ui"
import { Label } from "./label"
import { cn } from "@/lib/utils"

interface Option {
  label: string
  value: string
  icon?: React.ReactNode
}

interface SearchableSelectProps {
  options: Option[]
  value: string
  onChange: (value: string) => void
  placeholder?: string
  className?: string
  onSearch?: (query: string) => void
  searchPlaceholder?: string
  label?: string
}

export function SearchableSelect({
  options,
  value,
  onChange,
  placeholder = "Select an option...",
  className,
  onSearch,
  searchPlaceholder = "Search...",
  label,
}: SearchableSelectProps) {
  const [open, setOpen] = React.useState(false)
  const [search, setSearch] = React.useState("")

  const handleSearchChange = (val: string) => {
    setSearch(val)
    if (onSearch) {
      onSearch(val)
    }
  }

  const filteredOptions = onSearch 
    ? options 
    : options.filter((option) =>
        (option.label || "").toLowerCase().includes(search.toLowerCase())
      )

  const handleSelect = (val: string) => {
    onChange(val)
    setOpen(false)
  }

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

  const isFlex1 = className?.includes('flex-1')

  return (
    <div className={cn("space-y-2 w-full", isFlex1 && "flex-1")}>
      {label && <Label className="text-sm font-semibold">{label}</Label>}
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <div
            role="button"
            tabIndex={0}
            className={cn(
              "flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer",
              className?.replace('flex-1', '')
            )}
            onPointerDown={(e) => e.stopPropagation()}
            onClick={() => setOpen(!open)}
          >
            <div className="flex items-center truncate flex-1">
              {selectedOption?.icon && <span className="mr-2 shrink-0">{selectedOption.icon}</span>}
              <span className={cn("truncate", !selectedOption && "text-muted-foreground")}>
                {selectedOption ? selectedOption.label : placeholder}
              </span>
            </div>
            <ChevronsUpDown className="h-4 w-4 shrink-0 opacity-50 ml-2" />
          </div>
        </PopoverTrigger>
        <PopoverContent 
          className="p-0 z-[999999]" 
          align="start" 
          side="bottom"
          sideOffset={4}
          style={{ width: "var(--radix-popover-trigger-width)" }}
        >
          <div className="flex flex-col bg-white border rounded-md shadow-xl overflow-hidden">
            <div className="w-full">
              <SettingInput
                label="Search"
                placeholder={searchPlaceholder}
                value={search}
                onChange={handleSearchChange}
                icon={Search}
                className="bg-transparent border-none focus-visible:ring-0"
                labelHidden
              />
            </div>
            <ScrollArea className="max-h-60 overflow-y-auto p-1">
              {filteredOptions.length === 0 ? (
                <div className="p-4 text-center text-sm text-muted-foreground">
                  No results found.
                </div>
              ) : (
                <div className="space-y-1">
                  {filteredOptions.map((option) => (
                    <div
                      key={option.value}
                      className={cn(
                        "flex items-center space-x-2 rounded-sm px-2 py-2 hover:bg-accent hover:text-accent-foreground cursor-pointer transition-colors text-sm font-medium",
                        value === option.value && "bg-accent/50 text-primary"
                      )}
                      onClick={() => handleSelect(option.value)}
                    >
                      <div className="flex items-center flex-1 truncate">
                        {option.icon && <span className="mr-2 shrink-0">{option.icon}</span>}
                        <span className="truncate">
                          {option.label}
                        </span>
                      </div>
                      {value === option.value && (
                        <Check className="h-4 w-4 shrink-0" />
                      )}
                    </div>
                  ))}
                </div>
              )}
            </ScrollArea>
          </div>
        </PopoverContent>
      </Popover>
    </div>
  )
}
