import React, { useState } from "react"
import { useFormContext, Controller } from "react-hook-form"
import { Check, ChevronsUpDown, X } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command"
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover"
import { FormDescription, FormItem, FormLabel, FormMessage } from "@/components/ui/form"

interface Option {
  label: string
  value: string
}

interface MultiSelectSearchDropdownProps {
  name: string
  label: string
  placeholder?: string
  description?: string
  options: Option[]
  required?: boolean
}

export const MultiSelectSearchDropdown: React.FC<MultiSelectSearchDropdownProps> = ({
  name,
  label,
  placeholder = "Select options...",
  description,
  options,
  required = false,
}) => {
  const {
    control,
    formState: { errors },
  } = useFormContext()
  const [open, setOpen] = useState(false)

  const error = errors[name]

  return (
    <Controller
      name={name}
      control={control}
      render={({ field }) => {
        const selectedValues = field.value || []

        const toggleOption = (value: string) => {
          const newValues = selectedValues.includes(value)
            ? selectedValues.filter((v: string) => v !== value)
            : [...selectedValues, value]
          field.onChange(newValues)
        }

        const removeOption = (value: string) => {
          field.onChange(selectedValues.filter((v: string) => v !== value))
        }

        const getOptionLabel = (value: string) => {
          return options.find((opt) => opt.value === value)?.label || value
        }

        return (
          <FormItem>
            <FormLabel>
              {label}
              {required && <span className="text-destructive ml-1">*</span>}
            </FormLabel>
            
            {/* Selected values display - only show when there are selections */}
            {selectedValues.length > 0 && (
              <div className="flex flex-wrap gap-2 mb-2 p-2 border rounded-md">
                {selectedValues.map((value: string) => (
                  <Badge
                    key={value}
                    variant="secondary"
                    className="flex items-center gap-1 px-2 py-1"
                  >
                    {getOptionLabel(value)}
                    <button
                      type="button"
                      className="ml-1 ring-offset-background rounded-full outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          removeOption(value)
                        }
                      }}
                      onMouseDown={(e) => {
                        e.preventDefault()
                        e.stopPropagation()
                      }}
                      onClick={() => removeOption(value)}
                    >
                      <X className="h-3 w-3 text-muted-foreground hover:text-foreground" />
                    </button>
                  </Badge>
                ))}
              </div>
            )}

            {/* Dropdown */}
            <Popover open={open} onOpenChange={setOpen}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  aria-expanded={open}
                  className="w-full justify-between"
                >
                  {placeholder}
                  <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-full p-0" align="start">
                <Command>
                  <CommandInput placeholder="Search..." />
                  <CommandList>
                    <CommandEmpty>No option found.</CommandEmpty>
                    <CommandGroup>
                      {options.map((option) => {
                        const isSelected = selectedValues.includes(option.value)
                        return (
                          <CommandItem
                            key={option.value}
                            value={option.value}
                            onSelect={() => {
                              toggleOption(option.value)
                            }}
                          >
                            <Check
                              className={cn(
                                "mr-2 h-4 w-4",
                                isSelected ? "opacity-100" : "opacity-0"
                              )}
                            />
                            {option.label}
                          </CommandItem>
                        )
                      })}
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>

            {description && <FormDescription>{description}</FormDescription>}
            {error && <FormMessage>{error.message as string}</FormMessage>}
          </FormItem>
        )
      }}
    />
  )
}
