/**
 * 발주처(매입 거래처) 검색 모달
 *
 * SearchableSelectionModal 공통 컴포넌트 기반
 * - 매입 가능 거래처만 표시 (client_type: PURCHASE, BOTH)
 * - 최소 입력 조건: 한글 완성형 1자 또는 영문 2자 이상
 */

'use client';

import { useCallback } from 'react';
import { SearchableSelectionModal } from '@/components/organisms/SearchableSelectionModal';

// =============================================================================
// 타입
// =============================================================================

interface SupplierItem {
  id: number | string;
  name: string;
  clientCode?: string;
  clientType?: string;
  contactPerson?: string;
  phone?: string;
}

interface SupplierSearchModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSelectSupplier: (supplier: { id: number | string; name: string; code?: string }) => void;
}

// =============================================================================
// API
// =============================================================================

interface ApiClientResponse {
  id?: number | string;
  name?: string;
  client_code?: string;
  client_type?: string;
  contact_person?: string;
  phone?: string;
}

function transformClientFromApi(apiClient: ApiClientResponse): SupplierItem {
  return {
    id: String(apiClient.id || ''),
    name: apiClient.name || '',
    clientCode: apiClient.client_code || '',
    clientType: apiClient.client_type || '',
    contactPerson: apiClient.contact_person || '',
    phone: apiClient.phone || '',
  };
}

async function fetchPurchaseClients(search?: string): Promise<SupplierItem[]> {
  const params = new URLSearchParams();
  if (search) params.set('q', search);
  params.set('size', '50');
  params.set('client_type', 'PURCHASE,BOTH');

  const response = await fetch(`/api/proxy/clients?${params.toString()}`, {
    method: 'GET',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'include',
  });

  if (!response.ok) {
    throw new Error(`거래처 조회 실패: ${response.status}`);
  }

  const result = await response.json();
  let rawItems: ApiClientResponse[] = [];

  if (result.success && result.data) {
    if (result.data.data && Array.isArray(result.data.data)) {
      rawItems = result.data.data;
    } else if (Array.isArray(result.data)) {
      rawItems = result.data;
    }
  } else if (Array.isArray(result)) {
    rawItems = result;
  }

  return rawItems.map(transformClientFromApi);
}

// =============================================================================
// 유효성 검사
// =============================================================================

function isValidSearchQuery(query: string): boolean {
  if (!query || !query.trim()) return false;
  const trimmed = query.trim();
  if (/[가-힣]/.test(trimmed)) return true;
  const englishChars = trimmed.replace(/[^a-zA-Z]/g, '');
  if (englishChars.length >= 2) return true;
  const alphanumeric = trimmed.replace(/[^a-zA-Z0-9]/g, '');
  if (alphanumeric.length >= 2) return true;
  return false;
}

// =============================================================================
// 컴포넌트
// =============================================================================

export function SupplierSearchModal({
  open,
  onOpenChange,
  onSelectSupplier,
}: SupplierSearchModalProps) {
  const handleFetchData = useCallback(async (query: string) => {
    return fetchPurchaseClients(query || undefined);
  }, []);

  const handleSelect = useCallback((supplier: SupplierItem) => {
    onSelectSupplier({ id: supplier.id, name: supplier.name, code: supplier.clientCode });
  }, [onSelectSupplier]);

  return (
    <SearchableSelectionModal<SupplierItem>
      open={open}
      onOpenChange={onOpenChange}
      title="발주처 검색"
      searchPlaceholder="거래처명 검색..."
      fetchData={handleFetchData}
      keyExtractor={(s) => `${s.id}`}
      validateSearch={isValidSearchQuery}
      invalidSearchMessage="한글 1자(완성형) 또는 영문 2자 이상 입력하세요"
      emptyQueryMessage="한글 1자(완성형) 또는 영문 2자 이상 입력하세요"
      loadingMessage="거래처 검색 중..."
      dialogClassName="sm:max-w-[500px]"
      infoText={(items, isLoading) =>
        !isLoading ? (
          <span className="text-xs text-gray-400 text-right block">
            총 {items.length}개 거래처
          </span>
        ) : null
      }
      mode="single"
      onSelect={handleSelect}
      renderItem={(supplier) => (
        <div className="p-3 hover:bg-blue-50 transition-colors">
          <div className="flex items-center justify-between">
            <span className="font-medium text-gray-900">{supplier.name}</span>
            {supplier.clientCode && (
              <span className="text-xs text-gray-400 bg-gray-100 px-2 py-0.5 rounded">
                {supplier.clientCode}
              </span>
            )}
          </div>
          {supplier.contactPerson && (
            <p className="text-xs text-gray-400 mt-1">담당: {supplier.contactPerson}</p>
          )}
        </div>
      )}
    />
  );
}
