'use client'

import { useState } from 'react'

export interface SelectFieldProps {
  label: string
  value?: string | string[]
  onChange: (value: string | string[]) => void
  options?: string[]
  multi?: boolean
  required?: boolean
  helpText?: string
}

export function SelectField({
  label,
  value,
  onChange,
  options = [],
  multi = false,
  required,
  helpText,
}: SelectFieldProps) {
  const [searchTerm, setSearchTerm] = useState('')
  const [open, setOpen] = useState(false)

  const selectedValues = multi ? (Array.isArray(value) ? value : []) : []
  const singleValue = multi ? '' : typeof value === 'string' ? value : ''

  const filtered = options.filter((opt) => opt.toLowerCase().includes(searchTerm.toLowerCase()))

  function handleSelect(opt: string) {
    if (multi) {
      const next = selectedValues.includes(opt)
        ? selectedValues.filter((v) => v !== opt)
        : [...selectedValues, opt]
      onChange(next)
    } else {
      onChange(opt)
      setOpen(false)
    }
  }

  return (
    <div className="relative">
      <label className="mb-1 block text-sm font-medium">
        {label}
        {required && <span className="ml-0.5 text-[var(--destructive)]">*</span>}
      </label>

      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        className="flex w-full items-center justify-between rounded-md border border-[var(--border)] bg-[var(--input-background)] px-3 py-2 text-sm"
      >
        <span
          className={singleValue || selectedValues.length ? '' : 'text-[var(--muted-foreground)]'}
        >
          {multi
            ? selectedValues.length
              ? `${selectedValues.length} selected`
              : 'Select...'
            : singleValue || 'Select...'}
        </span>
        <svg
          className="h-4 w-4 text-[var(--muted-foreground)]"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={2}
        >
          <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {open && (
        <div className="absolute z-50 mt-1 w-full rounded-md border border-[var(--border)] bg-[var(--popover)] shadow-lg">
          <div className="border-b border-[var(--border)] p-2">
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="Search..."
              className="w-full rounded bg-[var(--input-background)] px-2 py-1 text-sm outline-none"
            />
          </div>
          <ul className="max-h-48 overflow-y-auto py-1">
            {filtered.map((opt) => {
              const isSelected = multi ? selectedValues.includes(opt) : singleValue === opt
              return (
                <li key={opt}>
                  <button
                    type="button"
                    onClick={() => handleSelect(opt)}
                    className={`flex w-full items-center gap-2 px-3 py-1.5 text-sm hover:bg-[var(--accent)] ${
                      isSelected ? 'font-medium' : ''
                    }`}
                  >
                    {multi && (
                      <span
                        className={`flex h-4 w-4 items-center justify-center rounded border ${
                          isSelected
                            ? 'border-[var(--primary)] bg-[var(--primary)] text-[var(--primary-foreground)]'
                            : 'border-[var(--border)]'
                        }`}
                      >
                        {isSelected && '✓'}
                      </span>
                    )}
                    {opt}
                  </button>
                </li>
              )
            })}
            {filtered.length === 0 && (
              <li className="px-3 py-2 text-sm text-[var(--muted-foreground)]">No options found</li>
            )}
          </ul>
        </div>
      )}

      {helpText && <p className="mt-1 text-xs text-[var(--muted-foreground)]">{helpText}</p>}
    </div>
  )
}
