'use client';

/**
 * SearchableSelect - 검색 가능한 단일 선택 컴포넌트
 *
 * Popover + Command 패턴으로 구현
 * - 검색 가능하지만 직접 입력은 불가 (선택만 허용)
 * - 선택 후 Popover 자동 닫힘
 * - 서버 검색 모드: onSearch 콜백으로 API 연동 (디바운스 300ms)
 * - 최소 입력 조건: 한글 1자(완성형) / 영문 2자
 */

import * as React from 'react';
import { Check, ChevronsUpDown, Loader2, Plus } from 'lucide-react';
import { cn } from './utils';
import { Button } from './button';
import { Popover, PopoverContent, PopoverTrigger } from './popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from './command';

export interface SearchableSelectOption {
  value: string;
  label: string;
  description?: string;
}

interface SearchableSelectProps {
  options: SearchableSelectOption[];
  value: string;
  onChange: (value: string, option: SearchableSelectOption) => void;
  placeholder?: string;
  searchPlaceholder?: string;
  emptyText?: string;
  disabled?: boolean;
  className?: string;
  /** 서버 검색 모드: 검색어 변경 시 호출 (디바운스 적용) */
  onSearch?: (query: string) => void;
  /** 로딩 상태 */
  isLoading?: boolean;
  /** 최소 입력 안내 메시지 */
  minInputText?: string;
  /** 직접 입력 허용 (목록에 없는 값 생성 가능) */
  creatable?: boolean;
  /** 직접 입력 시 안내 텍스트 */
  creatableText?: string;
}

/**
 * 검색어가 최소 입력 조건을 만족하는지 확인
 * - 한글 완성형 1자 이상 또는 영문 2자 이상
 */
function isValidSearchQuery(query: string): boolean {
  if (!query || !query.trim()) return false;
  const trimmed = query.trim();
  // 한글 완성형 1자 이상
  const hasCompleteKorean = /[가-힣]/.test(trimmed);
  if (hasCompleteKorean) return true;
  // 영문 2자 이상
  const englishChars = trimmed.replace(/[^a-zA-Z]/g, '');
  if (englishChars.length >= 2) return true;
  // 숫자+영문 조합 2자 이상
  const alphanumeric = trimmed.replace(/[^a-zA-Z0-9]/g, '');
  if (alphanumeric.length >= 2) return true;
  return false;
}

export function SearchableSelect({
  options,
  value,
  onChange,
  placeholder = '선택하세요',
  searchPlaceholder = '검색...',
  emptyText = '결과가 없습니다',
  disabled = false,
  className,
  onSearch,
  isLoading = false,
  minInputText = '한글 1자 또는 영문 2자 이상 입력하세요',
  creatable = false,
  creatableText = '직접 입력',
}: SearchableSelectProps) {
  const [open, setOpen] = React.useState(false);
  const [searchQuery, setSearchQuery] = React.useState('');
  const debounceRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);

  const selectedOption = options.find((opt) => opt.value === value)
    || (creatable && value ? { value, label: value } : undefined);
  const isServerSearch = !!onSearch;
  const queryValid = isValidSearchQuery(searchQuery);

  const handleSelect = (selectedValue: string) => {
    const option = options.find((opt) => opt.value === selectedValue);
    if (option) {
      onChange(selectedValue, option);
      setOpen(false);
      setSearchQuery('');
    }
  };

  const handleSearchChange = (query: string) => {
    setSearchQuery(query);

    if (!isServerSearch) return;

    // 디바운스 취소
    if (debounceRef.current) {
      clearTimeout(debounceRef.current);
    }

    // 최소 입력 조건 미충족 시 검색하지 않음
    if (!isValidSearchQuery(query)) return;

    // 디바운스 300ms
    debounceRef.current = setTimeout(() => {
      onSearch(query);
    }, 300);
  };

  // Popover 닫힐 때 검색어 초기화
  const handleOpenChange = (isOpen: boolean) => {
    setOpen(isOpen);
    if (!isOpen) {
      setSearchQuery('');
      if (debounceRef.current) {
        clearTimeout(debounceRef.current);
      }
    }
  };

  // 클린업
  React.useEffect(() => {
    return () => {
      if (debounceRef.current) {
        clearTimeout(debounceRef.current);
      }
    };
  }, []);

  // 서버 검색 모드에서 안내 메시지 결정
  const getEmptyMessage = () => {
    if (isServerSearch) {
      if (!searchQuery) return minInputText;
      if (!queryValid) return minInputText;
    }
    return emptyText;
  };

  // 서버 검색 모드에서 검색어 미입력/미충족 시 옵션 숨김
  const displayOptions = isServerSearch && !queryValid ? [] : options;

  // creatable: 검색어가 기존 옵션에 정확히 매칭되지 않으면 생성 옵션 표시
  const showCreateOption =
    creatable &&
    searchQuery.trim() &&
    !options.some((opt) => opt.label === searchQuery.trim());

  const handleCreate = () => {
    const trimmed = searchQuery.trim();
    const newOption: SearchableSelectOption = { value: trimmed, label: trimmed };
    onChange(trimmed, newOption);
    setOpen(false);
    setSearchQuery('');
  };

  return (
    <Popover open={open} onOpenChange={handleOpenChange}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          disabled={disabled}
          className={cn(
            'w-full justify-between font-normal',
            !selectedOption && 'text-muted-foreground',
            className
          )}
        >
          <span className="truncate">
            {selectedOption ? selectedOption.label : placeholder}
          </span>
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent
        className="w-[--radix-popover-trigger-width] p-0"
        align="start"
        onPointerDownOutside={(e) => {
          // Dialog cascade 방지 (Portal 렌더링으로 인한 모달 닫힘 방지)
          // 단, Popover는 수동으로 닫기
          e.preventDefault();
          handleOpenChange(false);
        }}
        onInteractOutside={(e) => {
          e.preventDefault();
          handleOpenChange(false);
        }}
      >
        <Command shouldFilter={!isServerSearch}>
          <CommandInput
            placeholder={searchPlaceholder}
            value={searchQuery}
            onValueChange={handleSearchChange}
          />
          <CommandList>
            {isLoading ? (
              <div className="flex items-center justify-center py-6 text-sm text-muted-foreground">
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                검색 중...
              </div>
            ) : (
              <>
                {!showCreateOption && <CommandEmpty>{getEmptyMessage()}</CommandEmpty>}
                <CommandGroup>
                  {displayOptions.map((option) => (
                    <CommandItem
                      key={option.value}
                      value={option.label}
                      onSelect={() => handleSelect(option.value)}
                      className="cursor-pointer"
                    >
                      <Check
                        className={cn(
                          'mr-2 h-4 w-4',
                          value === option.value ? 'opacity-100' : 'opacity-0'
                        )}
                      />
                      <div className="flex flex-col">
                        <span>{option.label}</span>
                        {option.description && (
                          <span className="text-xs text-muted-foreground">
                            {option.description}
                          </span>
                        )}
                      </div>
                    </CommandItem>
                  ))}
                </CommandGroup>
                {showCreateOption && (
                  <CommandGroup>
                    <CommandItem
                      value={`__create__${searchQuery.trim()}`}
                      onSelect={handleCreate}
                      className="cursor-pointer"
                    >
                      <Plus className="mr-2 h-4 w-4" />
                      <span>{creatableText}: <strong>{searchQuery.trim()}</strong></span>
                    </CommandItem>
                  </CommandGroup>
                )}
              </>
            )}
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
