"use client";

/**
 * 수주관리 - IntegratedListTemplateV2 적용
 *
 * 수주 관리 페이지
 * - 상단 통계 카드: N월 수주(기간 수주), 수주, 생산, 출하
 * - 상태 필터: 셀렉트박스 (전체, 수주등록, N자수정, 수주확정, 생산지시완료)
 * - 날짜 범위 필터: 달력
 * - 완전한 반응형 지원
 * - API 연동 완료 (2025-01-08)
 */

import { useState, useRef, useEffect, useCallback, useTransition, useMemo } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { OrderRegistration, OrderFormData, createOrder } from "@/components/orders";
import {
  FileText,
  Edit,
  Trash2,
  DollarSign,
  SplitSquareVertical,
  ClipboardList,
  Truck,
  Eye,
  Loader2,
  Bell,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { BadgeSm } from "@/components/atoms/BadgeSm";
import {
  UniversalListPage,
  type UniversalListConfig,
  type TableColumn,
  type FilterFieldConfig,
} from "@/components/templates/UniversalListPage";
import { toast } from "sonner";
import {
  TableRow,
  TableCell,
} from "@/components/ui/table";
import { Checkbox } from "@/components/ui/checkbox";
import { formatAmount } from "@/lib/utils/amount";
import { ListMobileCard, InfoField } from "@/components/organisms/MobileCard";
import { ConfirmDialog, DeleteConfirmDialog } from "@/components/ui/confirm-dialog";
import {
  getOrders,
  getOrderStats,
  deleteOrder,
  deleteOrders,
  type Order,
  type OrderStatus,
  type OrderStats,
} from "@/components/orders/actions";
import { sendSalesOrderNotification } from "@/lib/actions/fcm";
import { isNextRedirectError } from "@/lib/utils/redirect-error";


// 상태 뱃지 헬퍼 함수
function getOrderStatusBadge(status: OrderStatus) {
  const statusConfig: Record<OrderStatus, { label: string; variant: string; className: string }> = {
    order_registered: { label: "수주등록", variant: "default", className: "bg-gray-100 text-gray-700 border-gray-200" },
    order_confirmed: { label: "수주확정", variant: "default", className: "bg-gray-100 text-gray-700 border-gray-200" },
    production_ordered: { label: "생산지시완료", variant: "default", className: "bg-blue-100 text-blue-700 border-blue-200" },
    in_production: { label: "생산중", variant: "default", className: "bg-green-100 text-green-700 border-green-200" },
    produced: { label: "생산완료", variant: "default", className: "bg-blue-100 text-blue-700 border-blue-200" },
    rework: { label: "재작업중", variant: "default", className: "bg-orange-100 text-orange-700 border-orange-200" },
    work_completed: { label: "작업완료", variant: "default", className: "bg-blue-600 text-white border-blue-600" },
    shipping: { label: "출하중", variant: "default", className: "bg-purple-100 text-purple-700 border-purple-200" },
    shipped: { label: "출하완료", variant: "default", className: "bg-gray-500 text-white border-gray-500" },
    completed: { label: "완료", variant: "default", className: "bg-gray-500 text-white border-gray-500" },
    cancelled: { label: "취소", variant: "default", className: "bg-red-100 text-red-700 border-red-200" },
  };

  const config = statusConfig[status];
  return (
    <BadgeSm className={config.className}>
      {config.label}
    </BadgeSm>
  );
}

/**
 * 수주 등록 컴포넌트 (mode=new용)
 */
function CreateOrderContent() {
  const router = useRouter();

  const handleBack = () => {
    router.push("/sales/order-management-sales");
  };

  const handleSave = async (formData: OrderFormData) => {
    try {
      const result = await createOrder(formData);
      if (result.success) {
        toast.success("수주가 등록되었습니다.");
        router.push("/sales/order-management-sales");
      } else {
        toast.error(result.error || "수주 등록에 실패했습니다.");
      }
    } catch (_error) {
      toast.error("수주 등록 중 오류가 발생했습니다.");
    }
  };

  return <OrderRegistration onBack={handleBack} onSave={handleSave} />;
}

export default function OrderManagementSalesPage() {
  const searchParams = useSearchParams();
  const mode = searchParams.get('mode');

  // mode=new 처리: 별도 컴포넌트로 분리하여 Hooks 규칙 준수
  if (mode === 'new') {
    return <CreateOrderContent />;
  }

  return <OrderListContent />;
}

/**
 * 수주 목록 컴포넌트 (기본 화면)
 */
function OrderListContent() {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 날짜 범위 필터 상태 (이번달 초기값)
  const [startDate, setStartDate] = useState<string>(() => {
    const d = new Date();
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-01`;
  });
  const [endDate, setEndDate] = useState<string>(() => {
    const d = new Date();
    const last = new Date(d.getFullYear(), d.getMonth() + 1, 0);
    return `${last.getFullYear()}-${String(last.getMonth() + 1).padStart(2, '0')}-${String(last.getDate()).padStart(2, '0')}`;
  });

  // 필터 상태
  const [filterValues, setFilterValues] = useState<Record<string, string | string[]>>({
    status: 'all',
  });

  // 상태 필터 설정 (filterConfig)
  const filterConfig: FilterFieldConfig[] = [
    {
      key: 'status',
      label: '상태',
      type: 'single',
      options: [
        { value: 'order_registered', label: '수주등록' },
        { value: 'order_confirmed', label: '수주확정' },
        { value: 'production_ordered', label: '생산지시완료' },
      ],
      allOptionLabel: '전체',
    },
  ];

  // 취소 확인 다이얼로그 state
  const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false);
  const [cancelTargetId, setCancelTargetId] = useState<string | null>(null);

  // 삭제 확인 다이얼로그 state (다중 선택 삭제 지원)
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [deleteTargetIds, setDeleteTargetIds] = useState<string[]>([]);
  const [isForceDeleteDialogOpen, setIsForceDeleteDialogOpen] = useState(false);
  const [isForceDeleting, setIsForceDeleting] = useState(false);
  const isDev = process.env.NODE_ENV !== 'production';

  // 모바일 인피니티 스크롤 state
  const [mobileDisplayCount, setMobileDisplayCount] = useState(20);
  const sentinelRef = useRef<HTMLDivElement>(null);

  // API 연동 state
  const [orders, setOrders] = useState<Order[]>([]);
  const [apiStats, setApiStats] = useState<OrderStats | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isDeleting, setIsDeleting] = useState(false);

  // 데이터 로드 함수
  const loadData = useCallback(async () => {
    try {
      setIsLoading(true);
      const [ordersResult, statsResult] = await Promise.all([
        getOrders({ order_type: 'ORDER' }),
        getOrderStats(),
      ]);

      if (ordersResult.success && ordersResult.data) {
        setOrders(ordersResult.data.items);
      } else {
        toast.error(ordersResult.error || "수주 목록을 불러오는데 실패했습니다.");
      }

      if (statsResult.success && statsResult.data) {
        setApiStats(statsResult.data);
      }
    } catch (error) {
      console.error("Error loading orders:", error);
      toast.error("데이터를 불러오는 중 오류가 발생했습니다.");
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 초기 데이터 로드
  useEffect(() => {
    loadData();
  }, [loadData]);

  // 필터링 및 정렬
  const filteredOrders = orders
    .filter((order) => {
      const searchLower = searchTerm.toLowerCase();
      const matchesSearch =
        !searchTerm ||
        order.lotNumber.toLowerCase().includes(searchLower) ||
        order.client.toLowerCase().includes(searchLower) ||
        order.siteName.toLowerCase().includes(searchLower);

      // 상태 필터 (filterValues 사용)
      const statusFilter = filterValues.status as string;
      let matchesFilter = true;
      if (statusFilter && statusFilter !== "all") {
        matchesFilter = order.status === statusFilter;
      }

      return matchesSearch && matchesFilter;
    })
    .sort((a, b) => {
      return new Date(b.orderDate).getTime() - new Date(a.orderDate).getTime();
    });

  // 페이지네이션
  const _totalPages = Math.ceil(filteredOrders.length / itemsPerPage);
  const paginatedOrders = filteredOrders.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  // 모바일용 인피니티 스크롤 데이터
  const _mobileOrders = filteredOrders.slice(0, mobileDisplayCount);

  // Intersection Observer를 이용한 인피니티 스크롤
  useEffect(() => {
    if (typeof window === "undefined") return;
    if (window.innerWidth >= 1280) return;

    const observer = new IntersectionObserver(
      (entries) => {
        if (
          entries[0].isIntersecting &&
          mobileDisplayCount < filteredOrders.length
        ) {
          setMobileDisplayCount((prev) =>
            Math.min(prev + 20, filteredOrders.length)
          );
        }
      },
      {
        threshold: 0.1,
        rootMargin: "100px",
      }
    );

    if (sentinelRef.current) {
      observer.observe(sentinelRef.current);
    }

    return () => {
      observer.disconnect();
    };
  }, [mobileDisplayCount, filteredOrders.length]);

  // 필터나 검색어 변경 시 모바일 표시 개수 초기화
  useEffect(() => {
    setMobileDisplayCount(20);
  }, [searchTerm, filterValues]);

  // 통계 계산 — 날짜 범위 내 데이터 기준
  const periodLabel = useMemo(() => {
    if (!startDate || !endDate) return '전체 수주';
    const sm = startDate.slice(0, 7); // YYYY-MM
    const em = endDate.slice(0, 7);
    if (sm === em) {
      return `${parseInt(startDate.slice(5, 7))}월 수주`;
    }
    return '기간 수주';
  }, [startDate, endDate]);

  // 날짜 범위 내 수주 건수 (취소 제외)
  const periodOrderCount = orders.filter((o) => o.status !== "cancelled").length;

  // 수주: 생산에 넘어가지 않은 건 (DRAFT + CONFIRMED)
  const orderCount = orders.filter(
    (o) => o.status === "order_registered" || o.status === "order_confirmed"
  ).length;

  // 생산: 생산지시대기 + 생산중 (IN_PROGRESS + IN_PRODUCTION)
  const productionCount = orders.filter(
    (o) => o.status === "production_ordered" || o.status === "in_production"
  ).length;

  // 출하: 출하대기 ~ 출고중 (PRODUCED + SHIPPING)
  const shipCount = orders.filter(
    (o) => o.status === "produced" || o.status === "shipping"
  ).length;

  const stats = [
    {
      label: periodLabel,
      value: `${periodOrderCount}건`,
      icon: DollarSign,
      iconColor: "text-blue-600",
    },
    {
      label: "수주",
      value: `${orderCount}건`,
      icon: ClipboardList,
      iconColor: "text-orange-600",
    },
    {
      label: "생산",
      value: `${productionCount}건`,
      icon: SplitSquareVertical,
      iconColor: "text-green-600",
    },
    {
      label: "출하",
      value: `${shipCount}건`,
      icon: Truck,
      iconColor: "text-purple-600",
    },
  ];

  // 핸들러
  const handleView = (order: Order) => {
    router.push(`/sales/order-management-sales/${order.id}?mode=view`);
  };

  const handleEdit = (order: Order) => {
    router.push(`/sales/order-management-sales/${order.id}?mode=edit`);
  };

  // 개별 취소 기능은 상세 페이지에서 처리
  const _handleCancel = (orderId: string) => {
    setCancelTargetId(orderId);
    setIsCancelDialogOpen(true);
  };

  const handleConfirmCancel = () => {
    if (cancelTargetId) {
      const order = orders.find((o) => o.id === cancelTargetId);
      setOrders(
        orders.map((o) =>
          o.id === cancelTargetId ? { ...o, status: "cancelled" as OrderStatus } : o
        )
      );
      toast.success(
        `수주가 취소되었습니다${order ? `: ${order.lotNumber}` : ""}`
      );
      setIsCancelDialogOpen(false);
      setCancelTargetId(null);
    }
  };

  // 개별 삭제 (row에서 휴지통 아이콘 클릭)
  const handleDelete = (orderId: string) => {
    setDeleteTargetIds([orderId]);
    setIsDeleteDialogOpen(true);
  };

  // 다중 선택 삭제 (IntegratedListTemplateV2에서 확인 후 호출됨)
  // 템플릿 내부에서 이미 확인 팝업을 처리하므로 바로 삭제 실행
  const _handleBulkDelete = async () => {
    const selectedIds = Array.from(selectedItems);
    if (selectedIds.length > 0) {
      setIsDeleting(true);
      try {
        const result = await deleteOrders(selectedIds);
        if (result.success) {
          const deletedCount = result.deletedCount ?? 0;
          const skippedCount = result.skippedCount ?? 0;
          const skippedSet = new Set((result.skippedIds ?? []).map(String));
          // 실제 삭제된 항목만 리스트에서 제거
          setOrders(orders.filter((o) => skippedSet.has(o.id) || !selectedIds.includes(o.id)));
          setSelectedItems(new Set());
          if (deletedCount > 0) {
            toast.success(`${deletedCount}개의 수주가 삭제되었습니다.`);
          }
          if (skippedCount > 0) {
            toast.warning(`${skippedCount}개의 수주는 상태/작업지시로 인해 삭제할 수 없습니다.`);
          }
          const statsResult = await getOrderStats();
          if (statsResult.success && statsResult.data) {
            setApiStats(statsResult.data);
          }
        } else {
          toast.error(result.error || "삭제에 실패했습니다.");
        }
      } catch (error) {
        console.error("Error deleting orders:", error);
        toast.error("삭제 중 오류가 발생했습니다.");
      } finally {
        setIsDeleting(false);
      }
    }
  };

  // 삭제 확정 (단일/다중 모두 처리)
  const handleConfirmDelete = async () => {
    if (deleteTargetIds.length > 0) {
      const count = deleteTargetIds.length;
      setIsDeleting(true);
      try {
        if (count === 1) {
          const result = await deleteOrder(deleteTargetIds[0]);
          if (result.success) {
            setOrders(orders.filter((o) => o.id !== deleteTargetIds[0]));
            setSelectedItems(new Set());
            toast.success("수주가 삭제되었습니다.");
            const statsResult = await getOrderStats();
            if (statsResult.success && statsResult.data) {
              setApiStats(statsResult.data);
            }
          } else {
            toast.error(result.error || "삭제에 실패했습니다.");
          }
        } else {
          const result = await deleteOrders(deleteTargetIds);
          if (result.success) {
            const deletedCount = result.deletedCount ?? 0;
            const skippedCount = result.skippedCount ?? 0;
            const skippedSet = new Set((result.skippedIds ?? []).map(String));
            setOrders(orders.filter((o) => skippedSet.has(o.id) || !deleteTargetIds.includes(o.id)));
            setSelectedItems(new Set());
            if (deletedCount > 0) {
              toast.success(`${deletedCount}개의 수주가 삭제되었습니다.`);
            }
            if (skippedCount > 0) {
              toast.warning(`${skippedCount}개의 수주는 상태/작업지시로 인해 삭제할 수 없습니다.`);
            }
            const statsResult = await getOrderStats();
            if (statsResult.success && statsResult.data) {
              setApiStats(statsResult.data);
            }
          } else {
            toast.error(result.error || "삭제에 실패했습니다.");
          }
        }
      } catch (error) {
        console.error("Error deleting orders:", error);
        toast.error("삭제 중 오류가 발생했습니다.");
      } finally {
        setIsDeleting(false);
        setIsDeleteDialogOpen(false);
        setDeleteTargetIds([]);
      }
    }
  };

  // 완전삭제 (force=true, 개발환경 전용)
  const handleForceDelete = async () => {
    const selectedIds = Array.from(selectedItems);
    if (selectedIds.length === 0) return;
    setIsForceDeleting(true);
    try {
      const result = await deleteOrders(selectedIds, { force: true });
      if (result.success) {
        const deletedCount = result.deletedCount ?? 0;
        const skippedCount = result.skippedCount ?? 0;
        const skippedSet = new Set((result.skippedIds ?? []).map(String));
        // 실제 삭제된 항목만 리스트에서 제거
        setOrders(orders.filter((o) => skippedSet.has(o.id) || !selectedIds.includes(o.id)));
        setSelectedItems(new Set());
        if (deletedCount > 0) {
          toast.success(`${deletedCount}개의 수주가 완전삭제되었습니다.`);
        }
        if (skippedCount > 0) {
          toast.warning(`${skippedCount}개의 수주는 삭제할 수 없습니다.`);
        }
        const statsResult = await getOrderStats();
        if (statsResult.success && statsResult.data) {
          setApiStats(statsResult.data);
        }
      } else {
        toast.error(result.error || "완전삭제에 실패했습니다.");
      }
    } catch (error) {
      console.error("Error force deleting orders:", error);
      toast.error("완전삭제 중 오류가 발생했습니다.");
    } finally {
      setIsForceDeleting(false);
      setIsForceDeleteDialogOpen(false);
    }
  };

  // 체크박스 선택
  const toggleSelection = (id: string) => {
    const newSelection = new Set(selectedItems);
    if (newSelection.has(id)) {
      newSelection.delete(id);
    } else {
      newSelection.add(id);
    }
    setSelectedItems(newSelection);
  };

  const toggleSelectAll = () => {
    if (
      selectedItems.size === paginatedOrders.length &&
      paginatedOrders.length > 0
    ) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(paginatedOrders.map((o) => o.id)));
    }
  };

  // FCM 알림 발송 핸들러
  const handleSendNotification = useCallback(async () => {
    startTransition(async () => {
      try {
        const result = await sendSalesOrderNotification();
        if (result.success) {
          toast.success(`수주완료 알림을 발송했습니다. (${result.sentCount || 0}건)`);
        } else {
          toast.error(result.error || "알림 발송에 실패했습니다.");
        }
      } catch (error) {
        if (isNextRedirectError(error)) throw error;
        toast.error("알림 발송 중 오류가 발생했습니다.");
      }
    });
  }, []);

  // 테이블 컬럼 정의 (16개: 체크박스, 번호, 로트번호, 현장명, 출고예정일, 접수일, 수주처, 제품명, 수신자, 수신주소, 수신처, 배송, 담당자, 틀수, 상태, 비고)
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: "rowNumber", label: "번호", className: "px-2 text-center" },
    { key: "lotNumber", label: "로트번호", className: "px-2", sortable: true, copyable: true },
    { key: "siteName", label: "현장명", className: "px-2", sortable: true, copyable: true },
    { key: "expectedShipDate", label: "출고예정일", className: "px-2", sortable: true, copyable: true },
    { key: "orderDate", label: "수주일", className: "px-2", sortable: true, copyable: true },
    { key: "client", label: "수주처", className: "px-2", sortable: true, copyable: true },
    { key: "productName", label: "제품명", className: "px-2", sortable: true, copyable: true },
    { key: "receiver", label: "수신자", className: "px-2", sortable: true, copyable: true },
    { key: "receiverAddress", label: "수신주소", className: "px-2", sortable: true, copyable: true },
    { key: "receiverPlace", label: "수신처", className: "px-2", sortable: true, copyable: true },
    { key: "deliveryMethod", label: "배송", className: "px-2", sortable: true, copyable: true },
    { key: "manager", label: "담당자", className: "px-2", sortable: true, copyable: true },
    { key: "frameCount", label: "틀수", className: "px-2 text-center", sortable: true, copyable: true },
    { key: "status", label: "상태", className: "px-2", sortable: true },
    { key: "remarks", label: "비고", className: "px-2", copyable: true },
  ], []);

  // 테이블 행 렌더링 (16개 컬럼: 체크박스, 번호, 로트번호, 현장명, 출고예정일, 접수일, 수주처, 제품명, 수신자, 수신주소, 수신처, 배송, 담당자, 틀수, 상태, 비고)
  const renderTableRow = (
    order: Order,
    index: number,
    globalIndex: number,
    handlers: { isSelected: boolean; onToggle: () => void; onRowClick?: () => void }
  ) => {
    const { isSelected, onToggle } = handlers;

    return (
      <TableRow
        key={order.id}
        className={`cursor-pointer hover:bg-muted/50 ${isSelected ? "bg-blue-50" : ""}`}
        onClick={() => handleView(order)}
      >
        <TableCell onClick={(e) => e.stopPropagation()} className="text-center">
          <Checkbox
            checked={isSelected}
            onCheckedChange={onToggle}
          />
        </TableCell>
        <TableCell className="text-center">{globalIndex}</TableCell>
        <TableCell>
          <code className="text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded font-mono">
            {order.lotNumber}
          </code>
        </TableCell>
        <TableCell>{order.siteName || "-"}</TableCell>
        <TableCell>{order.expectedShipDate || "-"}</TableCell>
        <TableCell>{order.orderDate || "-"}</TableCell>
        <TableCell>{order.client || "-"}</TableCell>
        <TableCell>{order.productName || "-"}</TableCell>
        <TableCell>{order.receiver || "-"}</TableCell>
        <TableCell className="max-w-[150px] truncate">{order.receiverAddress || "-"}</TableCell>
        <TableCell>{order.receiverPlace || "-"}</TableCell>
        <TableCell>{order.deliveryMethodLabel || "-"}</TableCell>
        <TableCell>{order.manager || "-"}</TableCell>
        <TableCell className="text-center">{order.frameCount || "-"}</TableCell>
        <TableCell>{getOrderStatusBadge(order.status)}</TableCell>
        <TableCell className="max-w-[100px] truncate">{order.remarks || "-"}</TableCell>
      </TableRow>
    );
  };

  // 모바일 카드 렌더링
  const renderMobileCard = (
    order: Order,
    index: number,
    globalIndex: number,
    handlers: { isSelected: boolean; onToggle: () => void; onRowClick?: () => void }
  ) => {
    const { isSelected, onToggle } = handlers;
    return (
      <ListMobileCard
        key={order.id}
        id={order.id}
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onCardClick={() => handleView(order)}
        headerBadges={
          <>
            <Badge
              variant="outline"
              className="bg-gray-100 text-gray-700 font-mono text-xs"
            >
              {globalIndex}
            </Badge>
            <code className="inline-block text-xs bg-gray-100 text-gray-700 px-2.5 py-0.5 rounded-md font-mono whitespace-nowrap">
              {order.lotNumber}
            </code>
          </>
        }
        title={order.client}
        statusBadge={getOrderStatusBadge(order.status)}
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="현장명" value={order.siteName} />
            <InfoField label="견적번호" value={order.quoteNumber} />
            <InfoField label="출고예정일" value={order.expectedShipDate || "-"} />
            <InfoField label="배송방식" value={order.deliveryMethodLabel || "-"} />
            <InfoField
              label="금액"
              value={formatAmount(order.amount)}
              valueClassName="text-green-600"
            />
            <InfoField label="품목 수" value={`${order.itemCount}개`} />
          </div>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 flex-wrap">
              <Button
                variant="outline"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => {
                  e.stopPropagation();
                  handleView(order);
                }}
              >
                <Eye className="h-4 w-4 mr-2" />
                상세
              </Button>
              <Button
                variant="default"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => {
                  e.stopPropagation();
                  handleEdit(order);
                }}
              >
                <Edit className="h-4 w-4 mr-2" />
                수정
              </Button>
              {/* 삭제 버튼 - 수주등록/수주확정 상태에서만 표시 (생산지시 이후 삭제 불가) */}
              {(order.status === "order_registered" || order.status === "order_confirmed") && (
                <Button
                  variant="outline"
                  size="default"
                  className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleDelete(order.id);
                  }}
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  삭제
                </Button>
              )}
            </div>
          ) : undefined
        }
      />
    );
  };

  // ===== UniversalListPage 설정 =====
  const orderConfig: UniversalListConfig<Order> = {
    title: "수주 목록",
    description: "수주 관리 및 생산지시 연동",
    icon: FileText,
    basePath: "/sales/order-management-sales",

    idField: "id",

    actions: {
      getList: async () => ({
        success: true,
        data: filteredOrders,
        totalCount: filteredOrders.length,
      }),
      deleteItem: async (id) => {
        const result = await deleteOrder(id);
        if (result.success) {
          setOrders((prev) => prev.filter((o) => o.id !== id));
          const statsResult = await getOrderStats();
          if (statsResult.success && statsResult.data) {
            setApiStats(statsResult.data);
          }
        }
        return result;
      },
      deleteBulk: async (ids) => {
        const result = await deleteOrders(ids);
        if (result.success) {
          const skippedSet = new Set((result.skippedIds ?? []).map(String));
          setOrders((prev) => prev.filter((o) => skippedSet.has(o.id) || !ids.includes(o.id)));
          const statsResult = await getOrderStats();
          if (statsResult.success && statsResult.data) {
            setApiStats(statsResult.data);
          }
        }
        return result;
      },
    },

    columns: tableColumns,

    // 탭 제거 - 상태 필터는 headerActions의 셀렉트박스로 대체
    // tabs: undefined,
    // defaultTab: undefined,

    computeStats: () => stats,

    searchPlaceholder: "로트번호, 현장명, 수주처 검색...",

    // 날짜 범위 필터
    dateRangeSelector: {
      enabled: true,
      showPresets: true,
      presetsPosition: 'inline',
      startDate,
      endDate,
      onStartDateChange: setStartDate,
      onEndDateChange: setEndDate,
      dateField: "orderDate", // 접수일 기준 필터링
    },

    itemsPerPage: itemsPerPage,

    clientSideFiltering: true,

    searchFilter: (order, searchValue) => {
      const searchLower = searchValue.toLowerCase();
      return (
        order.lotNumber.toLowerCase().includes(searchLower) ||
        order.quoteNumber.toLowerCase().includes(searchLower) ||
        order.client.toLowerCase().includes(searchLower) ||
        order.siteName.toLowerCase().includes(searchLower)
      );
    },

    // 커스텀 필터 함수 (filterConfig 사용)
    customFilterFn: (items, fv) => {
      if (!items || items.length === 0) return items;
      return items.filter((item) => {
        const statusVal = fv.status as string;
        // 상태 필터
        if (statusVal && statusVal !== 'all' && item.status !== statusVal) {
          return false;
        }
        return true;
      });
    },

    selectionActions: isDev ? () => (
      <Button
        variant="outline"
        size="sm"
        className="border-red-300 text-red-600 hover:bg-red-50"
        onClick={() => setIsForceDeleteDialogOpen(true)}
      >
        <Trash2 className="h-4 w-4 mr-1" />
        완전삭제 (DEV)
      </Button>
    ) : undefined,

    headerActions: () => (
      <div className="flex items-center gap-2 ml-auto">
        <Button variant="outline" onClick={handleSendNotification} disabled={isPending}>
          <Bell className="w-4 h-4 mr-2" />
          수주완료
        </Button>
        <Button onClick={() => router.push("/sales/order-management-sales?mode=new")}>
          <FileText className="w-4 h-4 mr-2" />
          수주 등록
        </Button>
      </div>
    ),

    // 필터 설정 (filterConfig 사용 - PC 인라인, 모바일 바텀시트)
    filterConfig,
    initialFilters: filterValues,
    filterTitle: '수주 필터',

    renderTableRow: renderTableRow,

    renderMobileCard: renderMobileCard,

    renderDialogs: () => (
      <>
        {/* 수주 취소 확인 다이얼로그 */}
        <ConfirmDialog
          open={isCancelDialogOpen}
          onOpenChange={setIsCancelDialogOpen}
          onConfirm={handleConfirmCancel}
          variant="warning"
          title="수주 취소 확인"
          description={
            <>
              {cancelTargetId
                ? `수주번호: ${orders.find((o) => o.id === cancelTargetId)?.lotNumber || cancelTargetId}`
                : ""}
              <br />
              이 수주를 취소하시겠습니까? 취소된 수주는 복구할 수 없습니다.
            </>
          }
          confirmText="취소 확정"
        />

        {/* 수주 삭제 확인 다이얼로그 */}
        <DeleteConfirmDialog
          open={isDeleteDialogOpen}
          onOpenChange={setIsDeleteDialogOpen}
          onConfirm={handleConfirmDelete}
          title="삭제 확인"
          description={
            <>
              선택한 <strong>{deleteTargetIds.length}개</strong>의 수주를 삭제하시겠습니까?
              <br />
              <span className="text-muted-foreground text-sm">
                삭제된 수주는 복구할 수 없습니다. 관련된 작업지시, 출하정보도 함께 삭제될 수 있습니다.
              </span>
            </>
          }
          loading={isDeleting}
        />

        {/* 완전삭제 확인 다이얼로그 (개발환경 전용) */}
        {isDev && (
          <DeleteConfirmDialog
            open={isForceDeleteDialogOpen}
            onOpenChange={setIsForceDeleteDialogOpen}
            onConfirm={handleForceDelete}
            title="⚠️ 완전삭제 (개발 전용)"
            description={
              <>
                선택한 <strong>{Array.from(selectedItems).length}개</strong>의 수주를 <strong className="text-red-600">물리 삭제</strong>합니다.
                <br />
                <span className="text-red-500 text-sm font-medium">
                  이 작업은 DB에서 완전히 제거되며 복구가 불가능합니다.
                </span>
              </>
            }
            loading={isForceDeleting}
          />
        )}
      </>
    ),
  };

  // 로딩 상태 표시
  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
          <p className="text-muted-foreground">수주 목록을 불러오는 중...</p>
        </div>
      </div>
    );
  }

  return (
    <UniversalListPage<Order>
      config={orderConfig}
      initialData={filteredOrders}
      initialTotalCount={filteredOrders.length}
      externalSelection={{
        selectedItems,
        onToggleSelection: toggleSelection,
        onToggleSelectAll: toggleSelectAll,
        setSelectedItems,
        getItemId: (item: Order) => item.id,
      }}
      onFilterChange={(newFilters) => {
        setFilterValues(newFilters);
        setCurrentPage(1);
      }}
      onSearchChange={setSearchTerm}
    />
  );
}