/**
 * 수주 선택 모달 (다중선택)
 *
 * SearchableSelectionModal 공통 컴포넌트 기반
 * - 체크박스 테이블 (수주번호, 현장명, 납품일, 개소)
 * - 전체선택/개별선택
 */

'use client';

import { useCallback } from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { toast } from 'sonner';
import { SearchableSelectionModal } from '@/components/organisms/SearchableSelectionModal';
import { getOrderSelectList } from './actions';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import type { OrderSelectItem } from './types';

interface OrderSelectModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSelect: (items: OrderSelectItem[]) => void;
  /** 이미 선택된 항목 ID 목록 (중복 선택 방지) */
  excludeIds?: string[];
  /** 같은 거래처만 필터 (이미 선택된 수주의 client_id) */
  filterClientId?: number | null;
  /** 같은 모델만 필터 (이미 선택된 수주의 item_id) */
  filterItemId?: number | null;
  /** 필터 안내 텍스트 (예: "발주처A / 방화셔터") */
  filterLabel?: string;
}

export function OrderSelectModal({
  open,
  onOpenChange,
  onSelect,
  excludeIds = [],
  filterClientId,
  filterItemId,
  filterLabel,
}: OrderSelectModalProps) {
  const handleFetchData = useCallback(async (query: string) => {
    try {
      const result = await getOrderSelectList({
        q: query || undefined,
        clientId: filterClientId,
        itemId: filterItemId,
      });
      if (result.success) {
        return result.data.filter((item) => !excludeIds.includes(item.id));
      }
      toast.error(result.error || '수주 목록을 불러오는데 실패했습니다.');
      return [];
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[OrderSelectModal] loadItems error:', error);
      toast.error('수주 목록 로드 중 오류가 발생했습니다.');
      return [];
    }
  }, [excludeIds, filterClientId, filterItemId]);

  return (
    <SearchableSelectionModal<OrderSelectItem>
      open={open}
      onOpenChange={onOpenChange}
      title={filterLabel ? `수주 선택 — ${filterLabel}` : '수주 선택'}
      searchPlaceholder="수주번호, 현장명 검색..."
      fetchData={handleFetchData}
      keyExtractor={(item) => item.id}
      searchMode="enter"
      loadOnOpen
      dialogClassName="sm:max-w-3xl"
      listContainerClassName="max-h-[400px] overflow-y-auto border rounded-md"
      mode="multiple"
      onSelect={onSelect}
      confirmLabel="선택"
      allowSelectAll
      isItemDisabled={(item, selectedItems) => {
        // 서버 필터가 이미 적용된 경우 모달 내 추가 제한 불필요
        if (filterClientId || filterItemId) return false;
        // 서버 필터 없이 첫 선택 시 모달 내에서 같은 거래처+모델만 선택 가능
        if (selectedItems.length === 0) return false;
        const first = selectedItems[0];
        return item.clientId !== first.clientId || item.itemId !== first.itemId;
      }}
      listWrapper={(children, selectState) => (
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-10">
                {selectState && (
                  <Checkbox
                    checked={selectState.isAllSelected}
                    onCheckedChange={selectState.onToggleAll}
                  />
                )}
              </TableHead>
              <TableHead>수주번호</TableHead>
              <TableHead>현장명</TableHead>
              <TableHead>발주처</TableHead>
              <TableHead>모델</TableHead>
              <TableHead className="text-center">납품일</TableHead>
              <TableHead className="text-center">개소</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {children}
          </TableBody>
        </Table>
      )}
      renderItem={(item, isSelected, isDisabled) => (
        <TableRow className={isDisabled ? 'opacity-40' : 'hover:bg-muted/50'}>
          <TableCell onClick={(e) => e.stopPropagation()}>
            <Checkbox checked={isSelected} disabled={isDisabled} />
          </TableCell>
          <TableCell>{item.orderNumber}</TableCell>
          <TableCell>{item.siteName}</TableCell>
          <TableCell>{item.clientName}</TableCell>
          <TableCell>{item.itemName}</TableCell>
          <TableCell className="text-center">{item.deliveryDate}</TableCell>
          <TableCell className="text-center">{item.locationCount}</TableCell>
        </TableRow>
      )}
    />
  );
}
