/**
 * 수주 선택 모달
 *
 * SearchableSelectionModal 공통 컴포넌트 기반
 */

'use client';

import { useCallback } from 'react';
import { Badge } from '@/components/ui/badge';
import { toast } from 'sonner';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { SearchableSelectionModal } from '@/components/organisms/SearchableSelectionModal';
import { getSalesOrdersForWorkOrder } from './actions';
import type { SalesOrder } from './types';

interface SalesOrderSelectModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSelect: (order: SalesOrder) => void;
}

export function SalesOrderSelectModal({
  open,
  onOpenChange,
  onSelect,
}: SalesOrderSelectModalProps) {
  const handleFetchData = useCallback(async (query: string) => {
    try {
      const result = await getSalesOrdersForWorkOrder({
        q: query || undefined,
      });
      if (result.success) {
        return result.data.map((item) => ({
          id: String(item.id),
          orderNo: item.orderNo,
          client: item.client,
          projectName: item.projectName,
          dueDate: item.dueDate,
          status: item.status,
          itemCount: item.itemCount,
          splitCount: item.splitCount,
        }));
      }
      toast.error(result.error || '수주 목록 조회에 실패했습니다.');
      return [];
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[SalesOrderSelectModal] loadSalesOrders error:', error);
      toast.error('수주 목록 로드 중 오류가 발생했습니다.');
      return [];
    }
  }, []);

  return (
    <SearchableSelectionModal<SalesOrder>
      open={open}
      onOpenChange={onOpenChange}
      title="수주 선택"
      searchPlaceholder="수주번호, 거래처, 현장명 검색..."
      fetchData={handleFetchData}
      keyExtractor={(order) => order.id}
      loadOnOpen
      dialogClassName="sm:max-w-lg"
      listContainerClassName="max-h-[400px] overflow-y-auto space-y-2"
      noResultMessage=""
      infoText={(items, isLoading) =>
        !isLoading ? (
          <span>작업지시 가능한 수주 {items.length}건 (등록 상태 &amp; 생산지시 미생성)</span>
        ) : null
      }
      mode="single"
      onSelect={onSelect}
      renderItem={(order) => (
        <div className="p-4 border rounded-lg hover:bg-muted/50 transition-colors">
          <div className="flex items-start justify-between mb-2">
            <div className="flex items-center gap-2">
              <span className="font-semibold">{order.orderNo}</span>
              <Badge variant="secondary" className="text-xs">
                {order.status}
              </Badge>
            </div>
            <div className="text-sm text-right">
              <span className="text-muted-foreground">납기: </span>
              <span>{order.dueDate}</span>
            </div>
          </div>
          <div className="text-sm text-muted-foreground mb-1">
            {order.client}
          </div>
          <div className="text-sm mb-2">{order.projectName}</div>
          <div className="flex items-center gap-4 text-xs text-muted-foreground">
            <span>{order.itemCount}개 품목</span>
            <span>분할 {order.splitCount}건</span>
          </div>
        </div>
      )}
      listWrapper={undefined}
    />
  );
}
