"use client";

/**
 * 수주 상세 페이지
 *
 * - 문서 모달: 계약서, 거래명세서, 발주서
 * - 기본 정보, 수주/배송 정보, 비고
 * - 제품 내역 테이블
 * - 상태별 버튼 차이
 * - ?mode=edit: 수정 모드 (V2 패턴)
 */

import { useState, useEffect, useCallback } from "react";
import { useRouter, useParams, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Edit,
  PenLine,
  Factory,
  XCircle,
  Eye,
  CheckCircle2,
  RotateCcw,
  Undo2,
  Package,
  ChevronDown,
  ChevronRight,
  ChevronsUpDown,
  Trash2,
} from "lucide-react";
import { toast } from "sonner";
import { IntegratedDetailTemplate } from "@/components/templates/IntegratedDetailTemplate";
import { orderSalesConfig } from "@/components/orders/orderSalesConfig";
import { BadgeSm } from "@/components/atoms/BadgeSm";
import { formatAmount, formatNumber } from "@/lib/utils/amount";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import {
  OrderDocumentModal,
  type OrderDocumentType,
  getOrderById,
  updateOrderStatus,
  revertProductionOrder,
  revertOrderConfirmation,
  deleteOrder,
  createProductionOrder,
  checkBendingStock,
  type Order,
  type OrderStatus,
  type BendingStockItem,
} from "@/components/orders";
import { sendSalesOrderNotification } from "@/lib/actions/fcm";
import { OrderSalesDetailEdit } from "@/components/orders/OrderSalesDetailEdit";

/**
 * 수량 포맷 함수
 * - EA, SET, PCS 등 개수 단위: 정수로 표시
 * - M, M2, KG, L 등 측정 단위: 소수점 이하 불필요한 0 제거
 */
function formatQuantity(quantity: number, unit?: string): string {
  const countableUnits = ["EA", "SET", "PCS", "개", "세트", "BOX", "ROLL"];
  const upperUnit = (unit || "").toUpperCase();

  if (countableUnits.includes(upperUnit)) {
    // 개수 단위는 정수로 반올림
    return formatNumber(Math.round(quantity));
  }

  // 측정 단위는 소수점 4자리까지 반올림 후 불필요한 0 제거
  const rounded = Math.round(quantity * 10000) / 10000;
  return rounded.toLocaleString(undefined, {
    minimumFractionDigits: 0,
    maximumFractionDigits: 4
  });
}

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

// 정보 표시 컴포넌트
function InfoItem({ label, value }: { label: string; value?: string }) {
  return (
    <div>
      <p className="text-sm text-muted-foreground">{label}</p>
      <p className="font-medium">{value || "-"}</p>
    </div>
  );
}

export default function OrderDetailPage() {
  const router = useRouter();
  const params = useParams();
  const searchParams = useSearchParams();
  const orderId = params.id as string;
  const mode = searchParams.get('mode');

  // V2 패턴: mode 파라미터로 모드 결정
  const isEditMode = mode === 'edit';

  const [order, setOrder] = useState<Order | null>(null);
  const [loading, setLoading] = useState(true);
  const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false);
  const [isCancelling, setIsCancelling] = useState(false);
  const [isConfirmDialogOpen, setIsConfirmDialogOpen] = useState(false);
  const [isConfirming, setIsConfirming] = useState(false);
  const [isRevertDialogOpen, setIsRevertDialogOpen] = useState(false);
  const [isReverting, setIsReverting] = useState(false);
  const [revertReason, setRevertReason] = useState("");
  const [isForceReverting, setIsForceReverting] = useState(false);
  const isDev = process.env.NODE_ENV !== 'production';
  const [isRevertConfirmDialogOpen, setIsRevertConfirmDialogOpen] = useState(false);
  const [isRevertingConfirm, setIsRevertingConfirm] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

  // 생산지시 생성 모달 상태
  const [isProductionDialogOpen, setIsProductionDialogOpen] = useState(false);
  const [isCreatingProduction, setIsCreatingProduction] = useState(false);
  const [productionPriority, setProductionPriority] = useState<"normal" | "high" | "urgent">("normal");
  const [productionMemo, setProductionMemo] = useState("");
  // 생산지시 완료 알림 모달 상태
  const [isProductionSuccessDialogOpen, setIsProductionSuccessDialogOpen] = useState(false);

  // 취소 폼 상태
  const [cancelReason, setCancelReason] = useState("");
  const [cancelDetail, setCancelDetail] = useState("");

  // 문서 모달 상태
  const [documentModalOpen, setDocumentModalOpen] = useState(false);
  const [documentType, setDocumentType] = useState<OrderDocumentType>("contract");

  // 절곡 재고 현황
  const [bendingStock, setBendingStock] = useState<BendingStockItem[]>([]);
  const [bendingStockLoading, setBendingStockLoading] = useState(false);

  // 제품-부품 트리 확장 상태 (key: "floor-symbol")
  const [expandedProducts, setExpandedProducts] = useState<Set<string>>(new Set());

  // 데이터 로드 (API 호출)
  useEffect(() => {
    async function loadOrder() {
      try {
        setLoading(true);
        const result = await getOrderById(orderId);
        if (result.success && result.data) {
          setOrder(result.data);
        } else {
          toast.error(result.error || "수주 정보를 불러오는데 실패했습니다.");
          setOrder(null);
        }
      } catch (error) {
        console.error("Error loading order:", error);
        toast.error("수주 정보를 불러오는 중 오류가 발생했습니다.");
        setOrder(null);
      } finally {
        setLoading(false);
      }
    }
    loadOrder();
  }, [orderId]);

  // 절곡 재고 현황 로드 (수주확정 이후 상태에서만)
  useEffect(() => {
    if (!order) return;
    const confirmableStatuses: OrderStatus[] = ["order_confirmed", "production_ordered", "in_production"];
    if (!confirmableStatuses.includes(order.status)) return;

    async function loadBendingStock() {
      setBendingStockLoading(true);
      try {
        const result = await checkBendingStock(orderId);
        if (result.success && result.data) {
          setBendingStock(result.data);
        }
      } catch {
        // 조용히 실패 (필수 기능 아님)
      } finally {
        setBendingStockLoading(false);
      }
    }
    loadBendingStock();
  }, [order?.status, orderId]);

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

  const handleEdit = () => {
    // V2 패턴: ?mode=edit로 이동
    router.push(`/sales/order-management-sales/${orderId}?mode=edit`);
  };

  const handleProductionOrder = () => {
    // 생산지시 생성 모달 열기
    setProductionPriority("normal");
    setProductionMemo("");
    setIsProductionDialogOpen(true);
  };

  // 생산지시 확정 처리
  const handleProductionOrderSubmit = async () => {
    if (order) {
      setIsCreatingProduction(true);
      try {
        const result = await createProductionOrder(order.id, {
          priority: productionPriority,
          memo: productionMemo || undefined,
        });
        if (result.success && result.data) {
          // 주문 상태 업데이트
          setOrder({ ...order, status: "production_ordered" as OrderStatus });
          setIsProductionDialogOpen(false);
          // 성공 알림 모달 표시
          setIsProductionSuccessDialogOpen(true);
        } else {
          toast.error(result.error || "생산지시 생성에 실패했습니다.");
        }
      } catch (error) {
        console.error("Error creating production order:", error);
        toast.error("생산지시 생성 중 오류가 발생했습니다.");
      } finally {
        setIsCreatingProduction(false);
      }
    }
  };

  // 생산지시 완료 알림 확인
  const handleProductionSuccessConfirm = () => {
    setIsProductionSuccessDialogOpen(false);
  };

  const _handleViewProductionOrder = () => {
    // 생산지시 목록 페이지로 이동 (수주관리 내부)
    router.push(`/sales/order-management-sales/production-orders`);
  };

  const _handleCancel = () => {
    setCancelReason("");
    setCancelDetail("");
    setIsCancelDialogOpen(true);
  };

  const handleConfirmCancel = async () => {
    if (!cancelReason) {
      toast.error("취소 사유를 선택해주세요.");
      return;
    }
    if (order) {
      setIsCancelling(true);
      try {
        const result = await updateOrderStatus(order.id, "cancelled");
        if (result.success) {
          setOrder({ ...order, status: "cancelled" });
          toast.success("수주가 취소되었습니다.");
          setIsCancelDialogOpen(false);
          setCancelReason("");
          setCancelDetail("");
        } else {
          toast.error(result.error || "수주 취소에 실패했습니다.");
        }
      } catch (error) {
        console.error("Error cancelling order:", error);
        toast.error("수주 취소 중 오류가 발생했습니다.");
      } finally {
        setIsCancelling(false);
      }
    }
  };

  // 수주 확정 처리
  const handleConfirmOrder = () => {
    setIsConfirmDialogOpen(true);
  };

  const handleConfirmOrderSubmit = async () => {
    if (order) {
      setIsConfirming(true);
      try {
        const result = await updateOrderStatus(order.id, "order_confirmed");
        if (result.success && result.data) {
          setOrder(result.data);
          toast.success("수주가 확정되었습니다.");
          setIsConfirmDialogOpen(false);

          // FCM 푸시 알림 발송
          try {
            const fcmResult = await sendSalesOrderNotification({
              body: `${order.client} - ${order.siteName} 수주가 확정되었습니다.`,
            });
            if (!fcmResult.success) {
              console.warn('[FCM] 수주확정 알림 발송 실패:', fcmResult.error);
            }
          } catch (fcmError) {
            console.error('[FCM] 수주확정 알림 발송 오류:', fcmError);
          }
        } else {
          toast.error(result.error || "수주 확정에 실패했습니다.");
        }
      } catch (error) {
        console.error("Error confirming order:", error);
        toast.error("수주 확정 중 오류가 발생했습니다.");
      } finally {
        setIsConfirming(false);
      }
    }
  };

  // 생산지시 되돌리기
  const handleRevertProduction = () => {
    setRevertReason("");
    setIsRevertDialogOpen(true);
  };

  const handleRevertProductionSubmit = async () => {
    if (order) {
      setIsReverting(true);
      try {
        const result = await revertProductionOrder(order.id, {
          reason: revertReason || undefined,
        });
        if (result.success && result.data) {
          const { order: updatedOrder, deletedCounts, cancelledCount } = result.data;
          setOrder(updatedOrder);
          if (deletedCounts) {
            // force 모드 (개발): 물리 삭제 건수
            toast.success(
              `생산지시가 되돌려졌습니다. (작업지시 ${deletedCounts.workOrders}건, 품목 ${deletedCounts.workOrderItems}건, 결과 ${deletedCounts.workResults}건 삭제)`
            );
          } else {
            // cancel 모드 (운영): 취소 처리 건수
            const msg = cancelledCount
              ? `생산지시가 취소되었습니다. (${cancelledCount}건 취소)`
              : '생산지시가 되돌려졌습니다.';
            toast.success(msg);
          }
          setIsRevertDialogOpen(false);
          setRevertReason("");
        } else {
          toast.error(result.error || "생산지시 되돌리기에 실패했습니다.");
        }
      } catch (error) {
        console.error("Error reverting production order:", error);
        toast.error("생산지시 되돌리기 중 오류가 발생했습니다.");
      } finally {
        setIsReverting(false);
      }
    }
  };

  // 생산지시 완전삭제 (force=true, 개발환경 전용)
  const handleForceRevertProduction = async () => {
    if (order) {
      setIsForceReverting(true);
      try {
        const result = await revertProductionOrder(order.id, { force: true });
        if (result.success && result.data) {
          setOrder(result.data.order);
          toast.success("생산지시가 완전삭제되었습니다. (물리 삭제)");
          setIsRevertDialogOpen(false);
        } else {
          toast.error(result.error || "완전삭제에 실패했습니다.");
        }
      } catch (error) {
        console.error("Error force reverting production order:", error);
        toast.error("완전삭제 중 오류가 발생했습니다.");
      } finally {
        setIsForceReverting(false);
      }
    }
  };

  // 수주확정 되돌리기
  const handleRevertConfirmation = () => {
    setIsRevertConfirmDialogOpen(true);
  };

  const handleRevertConfirmationSubmit = async () => {
    if (order) {
      setIsRevertingConfirm(true);
      try {
        const result = await revertOrderConfirmation(order.id);
        if (result.success && result.data) {
          setOrder(result.data.order);
          toast.success("수주확정이 취소되었습니다.");
          setIsRevertConfirmDialogOpen(false);
        } else {
          toast.error(result.error || "수주확정 되돌리기에 실패했습니다.");
        }
      } catch (error) {
        console.error("Error reverting order confirmation:", error);
        toast.error("수주확정 되돌리기 중 오류가 발생했습니다.");
      } finally {
        setIsRevertingConfirm(false);
      }
    }
  };

  // 수주 삭제
  const _handleDelete = () => {
    setIsDeleteDialogOpen(true);
  };

  const handleDeleteSubmit = async () => {
    if (order) {
      setIsDeleting(true);
      try {
        const result = await deleteOrder(order.id);
        if (result.success) {
          toast.success("수주가 삭제되었습니다.");
          router.push("/sales/order-management-sales");
        } else {
          toast.error(result.error || "수주 삭제에 실패했습니다.");
        }
      } catch (error) {
        console.error("Error deleting order:", error);
        toast.error("수주 삭제 중 오류가 발생했습니다.");
      } finally {
        setIsDeleting(false);
      }
    }
  };

  // 문서 모달 열기
  const openDocumentModal = (type: OrderDocumentType) => {
    setDocumentType(type);
    setDocumentModalOpen(true);
  };

  // 제품-부품 트리 토글
  const toggleProduct = (key: string) => {
    setExpandedProducts((prev) => {
      const next = new Set(prev);
      if (next.has(key)) {
        next.delete(key);
      } else {
        next.add(key);
      }
      return next;
    });
  };

  // 모든 제품 확장
  const expandAllProducts = () => {
    const keys: string[] = [];
    if (order?.nodes && order.nodes.length > 0 && order.nodes.some(n => n.items && n.items.length > 0)) {
      order.nodes.forEach((n) => keys.push(`node-${n.id}`));
    } else if (order?.products) {
      order.products.forEach((p) => keys.push(`${p.floor || ""}-${p.code || ""}`));
    }
    setExpandedProducts(new Set(keys));
  };

  // 모든 제품 축소
  const collapseAllProducts = () => {
    setExpandedProducts(new Set());
  };

  // 제품별로 부품 그룹화 (floor_code, symbol_code 매칭)
  const getItemsForProduct = (floor: string | undefined, code: string | undefined) => {
    if (!order?.items) return [];
    return order.items.filter((item) => {
      // type = floor_code, symbol = symbol_code
      const itemFloor = item.type || "";
      const itemSymbol = item.symbol || "";
      const productFloor = floor || "";
      const productCode = code || "";
      return itemFloor === productFloor && itemSymbol === productCode;
    });
  };

  // 매칭되지 않은 부품 (orphan items)
  const getUnmatchedItems = () => {
    if (!order?.items || !order?.products) return order?.items || [];
    const matchedIds = new Set<string>();
    order.products.forEach((product) => {
      const items = getItemsForProduct(product.floor, product.code);
      items.forEach((item) => matchedIds.add(item.id));
    });
    return order.items.filter((item) => !matchedIds.has(item.id));
  };

  // 상세 컨텐츠 렌더링
  const renderViewContent = useCallback(() => {
    if (!order) return null;

    return (
      <div className="space-y-6">
        {/* 기본 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">기본 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <InfoItem label="로트번호" value={order.lotNumber} />
              <InfoItem label="수주일" value={order.orderDate} />
              <InfoItem label="수주처" value={order.client} />
              <InfoItem label="현장명" value={order.siteName} />
              <InfoItem label="담당자" value={order.manager} />
              <InfoItem label="연락처" value={order.contact} />
              <div>
                <p className="text-sm text-muted-foreground">상태</p>
                <div className="mt-1">{getOrderStatusBadge(order.status)}</div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 수주/배송 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">수주/배송 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
              <InfoItem label="납품요청일" value={order.deliveryRequestDate} />
              <InfoItem label="출고예정일" value={order.expectedShipDate || "미정"} />
              <InfoItem label="배송방식" value={order.deliveryMethodLabel || order.deliveryMethod} />
              <InfoItem label="운임비용" value={order.shippingCostLabel || order.shippingCost} />
              <InfoItem label="수신자" value={order.receiver} />
              <InfoItem label="수신처 연락처" value={order.receiverContact} />
              <div className="col-span-2 md:col-span-4">
                <p className="text-sm text-muted-foreground">주소</p>
                <p className="font-medium">{order.address || "-"}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 비고 */}
        {order.remarks && (
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">비고</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="whitespace-pre-wrap">{order.remarks}</p>
            </CardContent>
          </Card>
        )}

        {/* 제품내용 (아코디언) */}
        <Card>
          <CardHeader>
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
              <CardTitle className="text-lg shrink-0">제품내용</CardTitle>
              {((order.nodes && order.nodes.length > 0) || (order.products && order.products.length > 0)) && (
                <div className="flex items-center gap-2 shrink-0">
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={expandAllProducts}
                    className="text-xs"
                  >
                    <ChevronsUpDown className="h-3 w-3 mr-1" />
                    모두 펼치기
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={collapseAllProducts}
                    className="text-xs"
                  >
                    모두 접기
                  </Button>
                </div>
              )}
            </div>
          </CardHeader>
          <CardContent>
            {/* 노드 기반 렌더링 (개소별 items가 정확히 분배된 경우) */}
            {order.nodes && order.nodes.length > 0 && order.nodes.some(n => n.items && n.items.length > 0) ? (
              <div className="space-y-3">
                {order.nodes.map((node, nodeIndex) => {
                  const productKey = `node-${node.id}`;
                  const isExpanded = expandedProducts.has(productKey);
                  const product = order.products?.[nodeIndex];
                  const nodeWidth = (node.options?.width as number) || product?.openWidth;
                  const nodeHeight = (node.options?.height as number) || product?.openHeight;
                  const nodeProductName = (node.options as Record<string, unknown>)?.product_name as string || product?.productName || '';
                  const nodeFloor = (node.options as Record<string, unknown>)?.floor as string || '';
                  const nodeSymbol = (node.options as Record<string, unknown>)?.symbol as string || '';
                  const locLabel = [nodeFloor, nodeSymbol].filter(Boolean).join(' / ');
                  const productName = nodeProductName
                    ? `${nodeProductName}${locLabel ? ` (${locLabel})` : ''}`
                    : node.name || `개소 ${nodeIndex + 1}`;
                  const nodeItems = node.items || [];

                  return (
                    <div
                      key={node.id}
                      className="border border-gray-200 rounded-lg overflow-hidden"
                    >
                      {/* 제품 헤더 (클릭하면 확장/축소) */}
                      <button
                        type="button"
                        onClick={() => toggleProduct(productKey)}
                        className="w-full flex items-center p-3 sm:p-4 bg-gray-50 hover:bg-gray-100 transition-colors text-left gap-2"
                      >
                        <div className="shrink-0 w-7 h-7 flex items-center justify-center">
                          {isExpanded ? (
                            <ChevronDown className="h-5 w-5 text-gray-500" />
                          ) : (
                            <ChevronRight className="h-5 w-5 text-gray-500" />
                          )}
                        </div>
                        <Package className="h-5 w-5 text-blue-600 shrink-0" />
                        <div className="min-w-0 flex-1">
                          <div className="font-medium break-words">{productName}</div>
                          <div className="flex flex-wrap items-center gap-x-2 text-sm text-gray-500">
                            {nodeWidth && nodeHeight && (
                              <span className="whitespace-nowrap">({nodeWidth} × {nodeHeight})</span>
                            )}
                            <span className="whitespace-nowrap">부품 {nodeItems.length}개</span>
                          </div>
                        </div>
                      </button>

                      {/* 부품 목록 (확장 시 표시) */}
                      {isExpanded && (
                        <div className="border-t">
                          {nodeItems.length > 0 ? (
                            <Table>
                              <TableHeader>
                                <TableRow>
                                  <TableHead className="w-[60px] text-center">순번</TableHead>
                                  <TableHead>품목명</TableHead>
                                  <TableHead>규격</TableHead>
                                  <TableHead className="text-center">수량</TableHead>
                                  <TableHead className="text-center">단위</TableHead>
                                </TableRow>
                              </TableHeader>
                              <TableBody>
                                {nodeItems.map((item, index) => (
                                  <TableRow key={item.id}>
                                    <TableCell className="text-center">{index + 1}</TableCell>
                                    <TableCell>{item.itemName}</TableCell>
                                    <TableCell>{item.spec || "-"}</TableCell>
                                    <TableCell className="text-center">{formatQuantity(item.quantity, item.unit)}</TableCell>
                                    <TableCell className="text-center">{item.unit || "-"}</TableCell>
                                  </TableRow>
                                ))}
                              </TableBody>
                            </Table>
                          ) : (
                            <div className="p-4 text-center text-gray-400 text-sm">
                              연결된 부품이 없습니다
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            ) : order.products && order.products.length > 0 ? (
              <div className="space-y-3">
                {order.products.map((product, productIndex) => {
                  const productKey = `${product.floor || ""}-${product.code || ""}`;
                  const isExpanded = expandedProducts.has(productKey);
                  const productItems = getItemsForProduct(product.floor, product.code);

                  return (
                    <div
                      key={productIndex}
                      className="border border-gray-200 rounded-lg overflow-hidden"
                    >
                      {/* 제품 헤더 (클릭하면 확장/축소) */}
                      <button
                        type="button"
                        onClick={() => toggleProduct(productKey)}
                        className="w-full flex items-center p-3 sm:p-4 bg-gray-50 hover:bg-gray-100 transition-colors text-left gap-2"
                      >
                        <div className="shrink-0 w-7 h-7 flex items-center justify-center">
                          {isExpanded ? (
                            <ChevronDown className="h-5 w-5 text-gray-500" />
                          ) : (
                            <ChevronRight className="h-5 w-5 text-gray-500" />
                          )}
                        </div>
                        <Package className="h-5 w-5 text-blue-600 shrink-0" />
                        <div className="min-w-0 flex-1">
                          <div className="font-medium break-words">{product.productName}</div>
                          <div className="flex flex-wrap items-center gap-x-2 text-sm text-gray-500">
                            {product.openWidth && product.openHeight && (
                              <span className="whitespace-nowrap">({product.openWidth} × {product.openHeight})</span>
                            )}
                            <span className="whitespace-nowrap">부품 {productItems.length}개</span>
                          </div>
                        </div>
                      </button>

                      {/* 부품 목록 (확장 시 표시) */}
                      {isExpanded && (
                        <div className="border-t">
                          {productItems.length > 0 ? (
                            <Table>
                              <TableHeader>
                                <TableRow>
                                  <TableHead className="w-[60px] text-center">순번</TableHead>
                                  <TableHead>품목명</TableHead>
                                  <TableHead>규격</TableHead>
                                  <TableHead className="text-center">수량</TableHead>
                                  <TableHead className="text-center">단위</TableHead>
                                </TableRow>
                              </TableHeader>
                              <TableBody>
                                {productItems.map((item, index) => (
                                  <TableRow key={item.id}>
                                    <TableCell className="text-center">{index + 1}</TableCell>
                                    <TableCell>{item.itemName}</TableCell>
                                    <TableCell>{item.spec || "-"}</TableCell>
                                    <TableCell className="text-center">{formatQuantity(item.quantity, item.unit)}</TableCell>
                                    <TableCell className="text-center">{item.unit || "-"}</TableCell>
                                  </TableRow>
                                ))}
                              </TableBody>
                            </Table>
                          ) : (
                            <div className="p-4 text-center text-gray-400 text-sm">
                              연결된 부품이 없습니다
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            ) : null}
          </CardContent>
        </Card>

        {/* 기타부품 (아코디언) - 노드 기반이 아닌 경우만 표시 */}
        {(() => {
          // 노드 기반 렌더링인 경우 기타부품 불필요
          if (order.nodes && order.nodes.length > 0 && order.nodes.some(n => n.items && n.items.length > 0)) return null;
          const unmatchedItems = getUnmatchedItems();
          if (unmatchedItems.length === 0) return null;
          return (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">기타부품</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="border border-gray-200 rounded-lg overflow-hidden">
                  <button
                    type="button"
                    onClick={() => toggleProduct("other-parts")}
                    className="w-full flex items-center justify-between p-4 bg-gray-50 hover:bg-gray-100 transition-colors text-left"
                  >
                    <div className="flex items-center gap-3">
                      {expandedProducts.has("other-parts") ? (
                        <ChevronDown className="h-5 w-5 text-gray-500" />
                      ) : (
                        <ChevronRight className="h-5 w-5 text-gray-500" />
                      )}
                      <Package className="h-5 w-5 text-gray-400" />
                      <span className="font-medium text-gray-600">기타부품</span>
                    </div>
                    <span className="text-sm text-gray-500">
                      {unmatchedItems.length}개
                    </span>
                  </button>
                  {expandedProducts.has("other-parts") && (
                    <div className="border-t">
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="w-[60px] text-center">순번</TableHead>
                            <TableHead>품목명</TableHead>
                            <TableHead>규격</TableHead>
                            <TableHead className="text-center">수량</TableHead>
                            <TableHead className="text-center">단위</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {unmatchedItems.map((item, index) => (
                            <TableRow key={item.id}>
                              <TableCell className="text-center">{index + 1}</TableCell>
                              <TableCell>{item.itemName}</TableCell>
                              <TableCell>{item.spec || "-"}</TableCell>
                              <TableCell className="text-center">{formatQuantity(item.quantity, item.unit)}</TableCell>
                              <TableCell className="text-center">{item.unit || "-"}</TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          );
        })()}

        {/* 합계 - 제거됨 (소계/할인율/총금액은 수주 상세에서 불필요) */}
        {/* 절곡 재고 현황 */}
        {bendingStock.length > 0 && (
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-lg flex items-center gap-2">
                <Package className="h-5 w-5" />
                절곡품 재고 현황
                {bendingStock.some(s => s.status === 'insufficient') && (
                  <BadgeSm className="bg-red-100 text-red-700 border-red-200">부족</BadgeSm>
                )}
                {bendingStock.every(s => s.status === 'sufficient') && (
                  <BadgeSm className="bg-green-100 text-green-700 border-green-200">충족</BadgeSm>
                )}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>품목코드</TableHead>
                    <TableHead>품목명</TableHead>
                    <TableHead className="text-center">필요수량</TableHead>
                    <TableHead className="text-center">가용재고</TableHead>
                    <TableHead className="text-center">부족수량</TableHead>
                    <TableHead className="text-center">상태</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {bendingStock.map((item) => (
                    <TableRow key={item.itemId}>
                      <TableCell className="font-mono text-sm">{item.itemCode}</TableCell>
                      <TableCell>{item.itemName}</TableCell>
                      <TableCell className="text-center">{formatQuantity(item.neededQty, item.unit)}</TableCell>
                      <TableCell className="text-center">{formatQuantity(item.availableQty, item.unit)}</TableCell>
                      <TableCell className={`text-center ${item.shortfallQty > 0 ? 'text-red-600 font-semibold' : ''}`}>
                        {item.shortfallQty > 0 ? formatQuantity(item.shortfallQty, item.unit) : '-'}
                      </TableCell>
                      <TableCell className="text-center">
                        {item.status === 'sufficient' ? (
                          <BadgeSm className="bg-green-100 text-green-700 border-green-200">충족</BadgeSm>
                        ) : (
                          <BadgeSm className="bg-red-100 text-red-700 border-red-200">부족</BadgeSm>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        )}
        {bendingStockLoading && (
          <Card>
            <CardContent className="py-4 text-center text-muted-foreground text-sm">
              절곡품 재고 확인 중...
            </CardContent>
          </Card>
        )}
      </div>
    );
  }, [order, expandedProducts, expandAllProducts, collapseAllProducts, toggleProduct, getItemsForProduct, getUnmatchedItems, bendingStock, bendingStockLoading]);

  // 견적 수정 핸들러
  const handleEditQuote = () => {
    if (order?.quoteId) {
      router.push(`/sales/quote-management/${order.quoteId}?mode=edit`);
    }
  };

  // 수주서 보기 핸들러
  const handleViewOrderDocument = () => {
    openDocumentModal("salesOrder");
  };

  // 커스텀 헤더 액션 (상태별 버튼)
  const renderHeaderActions = useCallback(() => {
    if (!order) return null;

    // 상태별 버튼 표시 여부
    const showEditQuoteButton = !!order.quoteId; // 연결된 견적이 있을 때
    const showEditButton = order.status !== "shipped" && order.status !== "cancelled";
    const showConfirmButton = order.status === "order_registered";
    const showProductionCreateButton = order.status === "order_confirmed";
    const showRevertButton = order.status === "production_ordered";
    const showRevertConfirmButton = order.status === "order_confirmed";

    return (
      <>
        {/* 견적 수정 */}
        {showEditQuoteButton && (
          <Button variant="outline" size="sm" onClick={handleEditQuote}>
            <PenLine className="h-4 w-4 md:mr-2" />
            <span className="hidden md:inline">견적 수정</span>
          </Button>
        )}
        {/* 수주서 보기 */}
        <Button variant="outline" size="sm" onClick={handleViewOrderDocument}>
          <Eye className="h-4 w-4 md:mr-2" />
          <span className="hidden md:inline">수주서 보기</span>
        </Button>
        {/* 수주 확정 */}
        {showConfirmButton && (
          <Button size="sm" onClick={handleConfirmOrder} className="bg-green-600 hover:bg-green-700">
            <CheckCircle2 className="h-4 w-4 md:mr-2" />
            <span className="hidden md:inline">수주 확정</span>
          </Button>
        )}
        {/* 수주확정 되돌리기 */}
        {showRevertConfirmButton && (
          <Button variant="outline" size="sm" onClick={handleRevertConfirmation} className="border-slate-300 text-slate-600 hover:border-slate-400 hover:bg-slate-50">
            <RotateCcw className="h-4 w-4 md:mr-2" />
            <span className="hidden md:inline">수주확정 되돌리기</span>
          </Button>
        )}
        {/* 생산지시 생성 */}
        {showProductionCreateButton && (
          <Button size="sm" onClick={handleProductionOrder}>
            <Factory className="h-4 w-4 md:mr-2" />
            <span className="hidden md:inline">생산지시 생성</span>
          </Button>
        )}
        {/* 생산지시 되돌리기 */}
        {showRevertButton && (
          <Button variant="outline" size="sm" onClick={handleRevertProduction} className="border-amber-200 text-amber-600 hover:border-amber-300 hover:bg-amber-50">
            <Undo2 className="h-4 w-4 md:mr-2" />
            <span className="hidden md:inline">생산지시 되돌리기</span>
          </Button>
        )}
        {/* 수정 */}
        {showEditButton && (
          <Button variant="outline" size="sm" onClick={handleEdit}>
            <Edit className="h-4 w-4 md:mr-2" />
            <span className="hidden md:inline">수정</span>
          </Button>
        )}
      </>
    );
  }, [order, handleEditQuote, handleViewOrderDocument, handleConfirmOrder, handleRevertConfirmation, handleProductionOrder, handleRevertProduction, handleEdit]);

  // V2 패턴: ?mode=edit일 때 수정 컴포넌트 렌더링
  if (isEditMode) {
    return <OrderSalesDetailEdit orderId={orderId} />;
  }

  return (
    <>
      <IntegratedDetailTemplate
        config={orderSalesConfig}
        mode="view"
        initialData={(order ?? undefined) as Record<string, unknown> | undefined}
        itemId={orderId}
        isLoading={loading}
        onCancel={handleBack}
        renderView={renderViewContent}
        headerActions={renderHeaderActions()}
      />

      {/* 문서 모달 */}
      {order && (
        <OrderDocumentModal
          open={documentModalOpen}
          onOpenChange={setDocumentModalOpen}
          documentType={documentType}
          data={{
            lotNumber: order.lotNumber,
            orderDate: order.orderDate,
            client: order.client,
            siteName: order.siteName,
            manager: order.manager,
            managerContact: order.contact,
            deliveryRequestDate: order.deliveryRequestDate,
            expectedShipDate: order.expectedShipDate,
            deliveryMethod: order.deliveryMethod,
            address: order.address,
            items: order.items,
            products: order.products,
            subtotal: order.subtotal,
            discountRate: order.discountRate,
            totalAmount: order.totalAmount,
            remarks: order.remarks,
            // 수주서 전용 필드
            documentNumber: order.lotNumber,
            certificationNumber: order.lotNumber,
            recipientName: order.receiver,
            recipientContact: order.receiverContact,
            shutterCount: order.products?.length || 0,
            orderId: Number(order.id),
          }}
        />
      )}

      {/* 다이얼로그들 */}
      {order && (
      <>
      <Dialog open={isCancelDialogOpen} onOpenChange={setIsCancelDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <XCircle className="h-5 w-5" />
              수주 취소
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4">
            {/* 수주 정보 박스 */}
            <div className="border rounded-lg p-4 space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-muted-foreground">수주번호</span>
                <span className="font-medium">{order.lotNumber}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">발주처</span>
                <span>{order.client}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">현장명</span>
                <span>{order.siteName}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-muted-foreground">현재 상태</span>
                {getOrderStatusBadge(order.status)}
              </div>
            </div>

            {/* 취소 사유 선택 */}
            <div className="space-y-2">
              <Label htmlFor="cancelReason">
                취소 사유 <span className="text-red-500">*</span>
              </Label>
              <Select value={cancelReason} onValueChange={setCancelReason}>
                <SelectTrigger id="cancelReason">
                  <SelectValue placeholder="취소 사유를 선택하세요" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="customer_request">고객 요청</SelectItem>
                  <SelectItem value="spec_change">사양 변경</SelectItem>
                  <SelectItem value="price_issue">가격 문제</SelectItem>
                  <SelectItem value="delivery_issue">납기 문제</SelectItem>
                  <SelectItem value="duplicate_order">중복 수주</SelectItem>
                  <SelectItem value="other">기타</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 상세 사유 입력 */}
            <div className="space-y-2">
              <Label htmlFor="cancelDetail">상세 사유</Label>
              <Textarea
                id="cancelDetail"
                placeholder="취소 사유에 대한 상세 내용을 입력하세요"
                value={cancelDetail}
                onChange={(e) => setCancelDetail(e.target.value)}
                rows={3}
              />
            </div>

            {/* 취소 시 유의사항 */}
            <div className="bg-gray-50 border rounded-lg p-4 text-sm space-y-1">
              <p className="font-medium mb-2">취소 시 유의사항</p>
              <ul className="space-y-1 text-muted-foreground">
                <li>• 취소된 수주는 목록에서 '취소' 상태로 표시됩니다</li>
                <li>• 취소 후에는 수정이 불가능합니다</li>
                <li>• 관련된 생산지시가 있는 경우 먼저 생산지시를 취소해야 합니다</li>
              </ul>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsCancelDialogOpen(false)}
            >
              닫기
            </Button>
            <Button
              variant="outline"
              onClick={handleConfirmCancel}
              className="border-gray-300"
              disabled={isCancelling}
            >
              <XCircle className="h-4 w-4 mr-1" />
              {isCancelling ? "취소 중..." : "취소 확정"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 수주 확정 다이얼로그 */}
      <Dialog open={isConfirmDialogOpen} onOpenChange={setIsConfirmDialogOpen}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CheckCircle2 className="h-5 w-5 text-green-600" />
              수주 확정
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4">
            {/* 수주 정보 박스 */}
            <div className="border rounded-lg p-4 space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-muted-foreground">수주번호</span>
                <span className="font-medium">{order.lotNumber}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">발주처</span>
                <span>{order.client}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">현장명</span>
                <span>{order.siteName}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-muted-foreground">현재 상태</span>
                {getOrderStatusBadge(order.status)}
              </div>
            </div>

            {/* 수주 품목 정보 */}
            {((order.nodes && order.nodes.length > 0) || (order.products && order.products.length > 0)) && (
              <div className="border rounded-lg overflow-hidden">
                <div className="bg-gray-50 px-4 py-2 text-sm font-medium text-gray-700">
                  수주 품목 ({order.nodes?.length || order.products?.length || 0}건)
                </div>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="text-center w-[50px]">No</TableHead>
                      <TableHead>품목</TableHead>
                      <TableHead className="text-center">층</TableHead>
                      <TableHead className="text-center">부호</TableHead>
                      <TableHead className="text-center">사이즈</TableHead>
                      <TableHead className="text-center">수량</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {order.nodes && order.nodes.length > 0 ? (
                      order.nodes.map((node, idx) => {
                        const opts = node.options as Record<string, unknown> || {};
                        const product = order.products?.[idx];
                        const width = (opts.width as number) || product?.openWidth;
                        const height = (opts.height as number) || product?.openHeight;
                        const productName = (opts.product_name as string) || product?.productName || node.name || '-';
                        const floor = (opts.floor as string) || product?.floor || '-';
                        const code = (opts.symbol as string) || product?.code || '-';
                        return (
                          <TableRow key={node.id}>
                            <TableCell className="text-center text-xs">{idx + 1}</TableCell>
                            <TableCell className="text-xs">{productName}</TableCell>
                            <TableCell className="text-center text-xs">{floor}</TableCell>
                            <TableCell className="text-center text-xs">{code}</TableCell>
                            <TableCell className="text-center text-xs whitespace-nowrap">
                              {width && height ? `${width} × ${height}` : '-'}
                            </TableCell>
                            <TableCell className="text-center text-xs">{node.quantity}</TableCell>
                          </TableRow>
                        );
                      })
                    ) : order.products?.map((product, idx) => (
                      <TableRow key={idx}>
                        <TableCell className="text-center text-xs">{idx + 1}</TableCell>
                        <TableCell className="text-xs">{product.productName || '-'}</TableCell>
                        <TableCell className="text-center text-xs">{product.floor || '-'}</TableCell>
                        <TableCell className="text-center text-xs">{product.code || '-'}</TableCell>
                        <TableCell className="text-center text-xs whitespace-nowrap">
                          {product.openWidth && product.openHeight
                            ? `${product.openWidth} × ${product.openHeight}`
                            : '-'}
                        </TableCell>
                        <TableCell className="text-center text-xs">{product.quantity}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}

            {/* 확정 안내 */}
            <div className="bg-green-50 border border-green-200 rounded-lg p-4 text-sm space-y-1">
              <p className="font-medium mb-2 text-green-700">확정 후 변경사항</p>
              <ul className="space-y-1 text-green-600">
                <li>• 수주 상태가 '수주확정'으로 변경됩니다</li>
                <li>• 생산지시를 생성할 수 있습니다</li>
                <li>• 확정 후에도 수정이 가능합니다</li>
              </ul>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsConfirmDialogOpen(false)}
            >
              닫기
            </Button>
            <Button
              onClick={handleConfirmOrderSubmit}
              className="bg-green-600 hover:bg-green-700"
              disabled={isConfirming}
            >
              <CheckCircle2 className="h-4 w-4 mr-1" />
              {isConfirming ? "확정 중..." : "확정"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 생산지시 되돌리기 다이얼로그 */}
      <Dialog open={isRevertDialogOpen} onOpenChange={setIsRevertDialogOpen}>
        <DialogContent className="max-w-md max-h-[85vh] flex flex-col">
          <DialogHeader className="shrink-0">
            <DialogTitle className="flex items-center gap-2">
              <RotateCcw className="h-5 w-5 text-amber-600" />
              생산지시 되돌리기
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4 overflow-y-auto flex-1 min-h-0">
            {/* 수주 정보 박스 */}
            <div className="border rounded-lg p-3 space-y-2 text-sm">
              <div className="flex items-center gap-2">
                <span className="text-muted-foreground whitespace-nowrap shrink-0">수주번호</span>
                <span className="font-medium truncate">{order.lotNumber}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-muted-foreground whitespace-nowrap shrink-0">발주처</span>
                <span className="truncate">{order.client}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-muted-foreground whitespace-nowrap shrink-0">현장명</span>
                <span className="truncate">{order.siteName}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-muted-foreground whitespace-nowrap shrink-0">현재 상태</span>
                {getOrderStatusBadge(order.status)}
              </div>
            </div>

            {/* 경고 메시지 */}
            <div className="bg-amber-50 border border-amber-200 rounded-lg p-3 text-sm space-y-1">
              <p className="font-medium mb-2 text-amber-700">⚠️ 되돌리기 시 삭제되는 데이터</p>
              <ul className="space-y-1 text-amber-600">
                <li>• 이 수주에 연결된 모든 작업지시가 삭제됩니다</li>
                <li>• 작업지시 품목 정보가 삭제됩니다</li>
                <li>• 작업 결과(실적) 데이터가 삭제됩니다</li>
                <li>• 수주 상태가 '수주확정'으로 변경됩니다</li>
              </ul>
            </div>

            {/* 되돌리기 사유 */}
            <div className="space-y-2">
              <label className="text-sm font-medium">되돌리기 사유</label>
              <Textarea
                placeholder="되돌리기 사유를 입력해주세요 (선택)"
                value={revertReason}
                onChange={(e) => setRevertReason(e.target.value)}
                rows={2}
              />
            </div>

            {/* 확인 안내 */}
            <div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm">
              <p className="text-red-700 font-medium">
                이 작업은 되돌릴 수 없습니다. 정말로 생산지시를 되돌리시겠습니까?
              </p>
            </div>
          </div>

          <DialogFooter className="shrink-0 flex-col gap-2 pt-2">
            <Button
              variant="outline"
              onClick={() => setIsRevertDialogOpen(false)}
              className="w-full"
            >
              취소
            </Button>
            <div className="flex flex-col sm:flex-row gap-2 w-full">
              {isDev && (
                <Button
                  onClick={handleForceRevertProduction}
                  variant="destructive"
                  disabled={isForceReverting || isReverting}
                  className="w-full sm:w-auto"
                >
                  {isForceReverting ? "처리 중..." : "완전삭제 (DEV)"}
                </Button>
              )}
              <Button
                onClick={handleRevertProductionSubmit}
                className="bg-amber-600 hover:bg-amber-700 w-full sm:w-auto"
                disabled={isReverting || isForceReverting}
              >
                <RotateCcw className="h-4 w-4 mr-1" />
                {isReverting ? "처리 중..." : "되돌리기 확정"}
              </Button>
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 수주확정 되돌리기 다이얼로그 */}
      <Dialog open={isRevertConfirmDialogOpen} onOpenChange={setIsRevertConfirmDialogOpen}>
        <DialogContent className="max-w-md max-h-[90vh] flex flex-col">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <RotateCcw className="h-5 w-5 text-slate-600" />
              수주확정 되돌리기
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4 overflow-y-auto flex-1">
            {/* 수주 정보 박스 */}
            <div className="border rounded-lg p-4 space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-muted-foreground">수주번호</span>
                <span className="font-medium">{order.lotNumber}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">발주처</span>
                <span>{order.client}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">현장명</span>
                <span>{order.siteName}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-muted-foreground">현재 상태</span>
                {getOrderStatusBadge(order.status)}
              </div>
            </div>

            {/* 안내 메시지 */}
            <div className="bg-slate-50 border border-slate-200 rounded-lg p-4 text-sm space-y-1">
              <p className="font-medium mb-2 text-slate-700">되돌리기 후 변경사항</p>
              <ul className="space-y-1 text-slate-600">
                <li>• 수주 상태가 '수주등록'으로 변경됩니다</li>
                <li>• 생산지시 생성이 불가능해집니다</li>
                <li>• 다시 수주 확정을 해야 진행할 수 있습니다</li>
              </ul>
            </div>

            {/* 확인 안내 */}
            <div className="bg-gray-100 border border-gray-200 rounded-lg p-4 text-sm">
              <p className="text-gray-700 font-medium">
                수주확정을 취소하시겠습니까?
              </p>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsRevertConfirmDialogOpen(false)}
            >
              닫기
            </Button>
            <Button
              onClick={handleRevertConfirmationSubmit}
              variant="outline"
              className="border-slate-300"
              disabled={isRevertingConfirm}
            >
              <RotateCcw className="h-4 w-4 mr-1" />
              {isRevertingConfirm ? "처리 중..." : "되돌리기 확정"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 수주 삭제 다이얼로그 */}
      <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Trash2 className="h-5 w-5 text-red-600" />
              수주 삭제
            </DialogTitle>
          </DialogHeader>

          <div className="space-y-4">
            {/* 수주 정보 박스 */}
            <div className="border rounded-lg p-4 space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-muted-foreground">수주번호</span>
                <span className="font-medium">{order.lotNumber}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">발주처</span>
                <span>{order.client}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">현장명</span>
                <span>{order.siteName}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">총금액</span>
                <span className="font-medium text-green-600">
                  {formatAmount(order.totalAmount || 0)}
                </span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-muted-foreground">현재 상태</span>
                {getOrderStatusBadge(order.status)}
              </div>
            </div>

            {/* 경고 메시지 */}
            <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-sm space-y-1">
              <p className="font-medium mb-2 text-red-700">⚠️ 삭제 시 주의사항</p>
              <ul className="space-y-1 text-red-600">
                <li>• 삭제된 수주는 복구할 수 없습니다</li>
                <li>• 관련된 모든 품목 정보가 함께 삭제됩니다</li>
                <li>• 이 작업은 되돌릴 수 없습니다</li>
              </ul>
            </div>

            {/* 확인 안내 */}
            <div className="bg-gray-100 border border-gray-200 rounded-lg p-4 text-sm">
              <p className="text-gray-700 font-medium">
                정말로 이 수주를 삭제하시겠습니까?
              </p>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsDeleteDialogOpen(false)}
            >
              취소
            </Button>
            <Button
              onClick={handleDeleteSubmit}
              className="bg-red-600 hover:bg-red-700"
              disabled={isDeleting}
            >
              <Trash2 className="h-4 w-4 mr-1" />
              {isDeleting ? "삭제 중..." : "삭제 확정"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 생산지시 생성 모달 */}
      <Dialog open={isProductionDialogOpen} onOpenChange={setIsProductionDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>생산지시 생성</DialogTitle>
          </DialogHeader>

          <div className="space-y-6 py-4">
            {/* 우선순위 */}
            <div className="space-y-3">
              <Label className="text-base font-medium">우선순위</Label>
              <div className="flex gap-2">
                <Button
                  type="button"
                  variant={productionPriority === "urgent" ? "default" : "outline"}
                  className={productionPriority === "urgent" ? "bg-gray-900 hover:bg-gray-800" : ""}
                  onClick={() => setProductionPriority("urgent")}
                >
                  긴급
                </Button>
                <Button
                  type="button"
                  variant={productionPriority === "high" ? "default" : "outline"}
                  className={productionPriority === "high" ? "bg-gray-900 hover:bg-gray-800" : ""}
                  onClick={() => setProductionPriority("high")}
                >
                  우선
                </Button>
                <Button
                  type="button"
                  variant={productionPriority === "normal" ? "default" : "outline"}
                  className={productionPriority === "normal" ? "bg-orange-500 hover:bg-orange-600" : ""}
                  onClick={() => setProductionPriority("normal")}
                >
                  일반
                </Button>
              </div>
            </div>

            {/* 비고 */}
            <div className="space-y-2">
              <Label htmlFor="productionMemo">비고</Label>
              <Textarea
                id="productionMemo"
                placeholder="비고 사항을 입력하세요"
                value={productionMemo}
                onChange={(e) => setProductionMemo(e.target.value)}
                rows={3}
              />
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsProductionDialogOpen(false)}
              className="bg-gray-900 text-white hover:bg-gray-800"
            >
              취소
            </Button>
            <Button
              onClick={handleProductionOrderSubmit}
              className="bg-gray-900 hover:bg-gray-800"
              disabled={isCreatingProduction}
            >
              {isCreatingProduction ? "처리 중..." : "생산지시 확정"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 생산지시 완료 알림 모달 */}
      <Dialog open={isProductionSuccessDialogOpen} onOpenChange={setIsProductionSuccessDialogOpen}>
        <DialogContent className="max-w-sm">
          <DialogHeader>
            <DialogTitle className="text-center">알림</DialogTitle>
          </DialogHeader>

          <div className="py-6 text-center space-y-2">
            <p className="font-medium text-lg">작업지시가 생성되었습니다.</p>
            <p className="text-sm text-muted-foreground">
              생산관리 &gt; 작업지시 관리에서 확인하세요
            </p>
          </div>

          <DialogFooter className="justify-center">
            <Button
              onClick={handleProductionSuccessConfirm}
              className="bg-gray-900 hover:bg-gray-800 min-w-[120px]"
            >
              확인
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      </>
      )}
    </>
  );
}