'use client';

import React, { useState, useRef, useEffect } from 'react';
import { Icon } from '@iconify/react';

export interface SelectOption {
  value: string | number;
  label: string;
}

interface SelectProps {
  label?: string;
  options: SelectOption[];
  value: any; // string, number, or array of them
  onChange: (value: any) => void;
  multiple?: boolean;
  placeholder?: string;
  error?: string;
  required?: boolean;
  hint?: string;
}

export function Select({
  label,
  options,
  value,
  onChange,
  multiple = false,
  placeholder = 'Select an option...',
  error,
  required,
  hint,
}: SelectProps) {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);

  // Close when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleToggle = () => setIsOpen(!isOpen);

  const handleSelect = (option: SelectOption) => {
    if (multiple) {
      const currentValues = Array.isArray(value) ? value : [];
      if (currentValues.includes(option.value)) {
        onChange(currentValues.filter((v) => v !== option.value));
      } else {
        onChange([...currentValues, option.value]);
      }
    } else {
      onChange(option.value);
      setIsOpen(false);
    }
  };

  const getDisplayValue = () => {
    if (multiple) {
      const currentValues = Array.isArray(value) ? value : [];
      if (currentValues.length === 0) return placeholder;
      if (currentValues.length === 1) {
        return options.find((o) => o.value === currentValues[0])?.label || placeholder;
      }
      return `${currentValues.length} selected`;
    }
    return options.find((o) => o.value === value)?.label || placeholder;
  };

  return (
    <div className="w-full" ref={containerRef}>
      {label && (
        <label className="block text-sm font-semibold text-[var(--text-secondary)] mb-1.5 ml-0.5">
          {label}
          {required && <span className="text-red-500 ml-1">*</span>}
        </label>
      )}

      <div className="relative">
        <button
          type="button"
          onClick={handleToggle}
          className={`
            relative w-full text-left px-4 h-11 bg-[var(--bg-paper)] border rounded-xl transition-all duration-200
            flex items-center justify-between gap-2
            ${isOpen ? 'border-primary ring-2 ring-primary/10' : 'border-[var(--border-default)] hover:border-primary/30'}
            ${error ? 'border-red-500 ring-red-500/10' : ''}
            ${!value || (multiple && value.length === 0) ? 'text-[var(--text-secondary)]' : 'text-[var(--text-primary)]'}
          `}
        >
          <span className="block truncate text-sm">
            {getDisplayValue()}
          </span>
          <Icon
            icon="solar:alt-arrow-down-outline"
            className={`w-4 h-4 text-[var(--text-secondary)] transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`}
          />
        </button>

        {isOpen && (
          <div className="absolute z-[110] w-full mt-2 bg-[var(--bg-paper)] border border-[var(--border-default)] rounded-2xl shadow-2xl py-2 max-h-60 overflow-y-auto animate-in fade-in zoom-in-95 duration-200">
            {options.length === 0 ? (
              <div className="px-4 py-8 text-center text-sm text-[var(--text-secondary)]">
                No options available
              </div>
            ) : (
              options.map((option) => {
                const isSelected = multiple
                  ? Array.isArray(value) && value.includes(option.value)
                  : value === option.value;

                return (
                  <button
                    key={option.value}
                    type="button"
                    onClick={() => handleSelect(option)}
                    className={`
                      w-full text-left px-4 py-2.5 text-sm transition-all flex items-center justify-between
                      ${isSelected ? 'bg-primary/5 text-primary font-semibold' : 'text-[var(--text-secondary)] hover:bg-[var(--bg-default)] hover:text-[var(--text-primary)]'}
                    `}
                  >
                    <span>{option.label}</span>
                    {isSelected && (
                      <Icon icon="solar:check-read-outline" className="w-4 h-4" />
                    )}
                  </button>
                );
              })
            )}
          </div>
        )}
      </div>

      {error && <p className="mt-1.5 ml-0.5 text-xs text-red-500">{error}</p>}
      {!error && hint && <p className="mt-1.5 ml-0.5 text-xs text-[var(--text-secondary)]">{hint}</p>}
    </div>
  );
}
