/**
 * Reference 필드 컴포넌트
 * 다른 테이블의 데이터를 검색하여 선택 (거래처, 품목, 고객 등)
 *
 * API 연동 시: REFERENCE_SOURCES[source]에서 apiUrl 조회 → 검색 API 호출
 * API 연동 전: props로 전달된 options 사용 또는 빈 상태에서 UI 확인
 */

'use client';

import { useState, useCallback } from 'react';
import { Search, X } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { SearchableSelectionModal } from '@/components/organisms/SearchableSelectionModal';
import { REFERENCE_SOURCES } from '../config/reference-sources';
import type { DynamicFieldRendererProps, ReferenceConfig } from '../types';

interface ReferenceItem {
  [key: string]: unknown;
}

export function ReferenceField({
  field,
  value,
  onChange,
  error,
  disabled,
}: DynamicFieldRendererProps) {
  const fieldKey = field.field_key || `field_${field.id}`;
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [displayValue, setDisplayValue] = useState<string>('');

  // properties에서 config 추출
  const config = (field.properties || {}) as ReferenceConfig;
  const source = config.source || '';
  const displayField = config.displayField || 'name';
  const valueField = config.valueField || 'id';
  const displayFormat = config.displayFormat;

  // 소스 프리셋 조회
  const preset = source ? REFERENCE_SOURCES[source] : null;
  const apiUrl = config.searchApiUrl || preset?.apiUrl || '';
  const columns = config.columns || preset?.columns || [
    { key: 'name', label: '이름' },
  ];

  // 표시값 포맷팅
  const formatDisplay = useCallback((item: ReferenceItem): string => {
    if (displayFormat) {
      return displayFormat.replace(/\{(\w+)\}/g, (_, key) =>
        String(item[key] || '')
      );
    }
    return String(item[displayField] || '');
  }, [displayFormat, displayField]);

  // 검색 API 호출
  const fetchData = useCallback(async (query: string): Promise<ReferenceItem[]> => {
    if (!apiUrl) return [];
    try {
      const separator = apiUrl.includes('?') ? '&' : '?';
      const url = `${apiUrl}${separator}search=${encodeURIComponent(query)}&size=20`;
      const response = await fetch(url);
      const result = await response.json();
      // 다양한 응답 구조 대응
      if (Array.isArray(result)) return result;
      if (result.data?.data) return result.data.data;
      if (Array.isArray(result.data)) return result.data;
      return [];
    } catch {
      return [];
    }
  }, [apiUrl]);

  // 선택 핸들러
  const handleSelect = (item: ReferenceItem) => {
    const selectedValue = item[valueField];
    onChange(selectedValue as string | number);
    setDisplayValue(formatDisplay(item));
    setIsModalOpen(false);
  };

  // 선택 해제
  const handleClear = () => {
    onChange(null);
    setDisplayValue('');
  };

  // 현재 표시값
  const currentDisplay = displayValue || (value ? String(value) : '');

  return (
    <div>
      <Label htmlFor={fieldKey}>
        {field.field_name}
        {field.is_required && <span className="text-red-500"> *</span>}
      </Label>
      <div className="flex gap-2">
        <div className="relative flex-1">
          <Input
            id={fieldKey}
            value={currentDisplay}
            placeholder={field.placeholder || `${field.field_name}을(를) 선택하세요`}
            readOnly
            disabled={disabled}
            className={`pr-8 ${error ? 'border-red-500' : ''}`}
          />
          {currentDisplay && !disabled && (
            <button
              type="button"
              onClick={handleClear}
              className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
            >
              <X className="h-4 w-4" />
            </button>
          )}
        </div>
        <Button
          type="button"
          variant="outline"
          size="icon"
          disabled={disabled || !apiUrl}
          onClick={() => setIsModalOpen(true)}
        >
          <Search className="h-4 w-4" />
        </Button>
      </div>
      {error && (
        <p className="text-xs text-red-500 mt-1">{error}</p>
      )}
      {!error && field.description && (
        <p className="text-xs text-muted-foreground mt-1">
          * {field.description}
        </p>
      )}

      {/* 검색 모달 */}
      <SearchableSelectionModal<ReferenceItem>
        mode="single"
        open={isModalOpen}
        onOpenChange={setIsModalOpen}
        title={`${field.field_name} 검색`}
        searchPlaceholder="검색어를 입력하세요"
        fetchData={fetchData}
        keyExtractor={(item) => String(item[valueField])}
        renderItem={(item) => (
          <div className="flex items-center gap-4 px-3 py-2">
            {columns.map((col) => (
              <span
                key={col.key}
                className="text-sm"
                style={col.width ? { width: col.width, flexShrink: 0 } : { flex: 1 }}
              >
                {String(item[col.key] || '')}
              </span>
            ))}
          </div>
        )}
        onSelect={handleSelect}
        searchMode="debounce"
        loadOnOpen
      />
    </div>
  );
}
