"use client";

/**
 * 생산지시 생성 페이지
 *
 * - 수주 정보 (읽기전용)
 * - 생산지시 옵션 (우선순위 탭, 메모)
 * - 생성될 작업지시 (카드 형태)
 * - 자재 소요량 및 재고 현황
 * - 스크린 품목 상세
 * - 모터/전장품 사양 (읽기전용)
 * - 절곡물 BOM
 */

import { useState, useEffect } from "react";
import { useRouter, useParams } 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 { Textarea } from "@/components/ui/textarea";
import { Factory, ArrowLeft, BarChart3, CheckCircle2 } from "lucide-react";
import { PageLayout } from "@/components/organisms/PageLayout";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { PageHeader } from "@/components/organisms/PageHeader";
import { BadgeSm } from "@/components/atoms/BadgeSm";
import { cn } from "@/lib/utils";

// 수주 정보 타입
interface OrderInfo {
  orderNumber: string;
  client: string;
  siteName: string;
  dueDate: string;
  itemCount: number;
  totalQuantity: string;
  creditGrade: string;
  status: string;
}

// 우선순위 설정 타입
type PriorityLevel = "urgent" | "high" | "normal" | "low";

interface PriorityConfig {
  key: PriorityLevel;
  label: string;
  productionOrder: string;
  workOrderPriority: string;
  note: string;
}

// 작업지시 카드 타입
interface WorkOrderCard {
  id: string;
  type: string;
  orderNumber: string;
  itemCount: number;
  totalQuantity: string;
  processes: string[];
}

// 자재 소요량 타입
interface MaterialRequirement {
  materialCode: string;
  materialName: string;
  unit: string;
  required: number;
  currentStock: number;
  status: "sufficient" | "insufficient";
}

// 스크린 품목 상세 타입
interface ScreenItemDetail {
  no: number;
  itemName: string;
  location: string;
  openWidth: number;
  openHeight: number;
  productWidth: number;
  productHeight: number;
  guideRail: string;
  shaft: string;
  capacity: string;
  finish: string;
  quantity: number;
}

// 가이드레일 BOM 타입
interface GuideRailBom {
  type: string;
  spec: string;
  code: string;
  length: number;
  quantity: number;
}

// 케이스 BOM 타입
interface CaseBom {
  item: string;
  length: string;
  quantity: number;
}

// 하단 마감재 BOM 타입
interface BottomFinishBom {
  item: string;
  spec: string;
  length: string;
  quantity: number;
}

// 우선순위별 색상 설정
const PRIORITY_COLORS: Record<PriorityLevel, { bg: string; text: string; border: string; button: string; buttonActive: string }> = {
  urgent: {
    bg: "bg-red-50",
    text: "text-red-700",
    border: "border-red-200",
    button: "bg-red-100 text-red-700 hover:bg-red-200",
    buttonActive: "bg-red-600 text-white",
  },
  high: {
    bg: "bg-orange-50",
    text: "text-orange-700",
    border: "border-orange-200",
    button: "bg-orange-100 text-orange-700 hover:bg-orange-200",
    buttonActive: "bg-orange-500 text-white",
  },
  normal: {
    bg: "bg-blue-50",
    text: "text-blue-700",
    border: "border-blue-200",
    button: "bg-blue-100 text-blue-700 hover:bg-blue-200",
    buttonActive: "bg-blue-600 text-white",
  },
  low: {
    bg: "bg-gray-50",
    text: "text-gray-700",
    border: "border-gray-200",
    button: "bg-gray-100 text-gray-700 hover:bg-gray-200",
    buttonActive: "bg-gray-600 text-white",
  },
};

// 우선순위 설정 데이터
const PRIORITY_CONFIGS: PriorityConfig[] = [
  {
    key: "urgent",
    label: "긴급",
    productionOrder: "긴급",
    workOrderPriority: "1순위",
    note: "무조건 제일 먼저",
  },
  {
    key: "high",
    label: "높음",
    productionOrder: "높음",
    workOrderPriority: "3순위",
    note: "(2순위는 현장에서 '새치기' 할 때 쓰도록 비워둠)",
  },
  {
    key: "normal",
    label: "일반",
    productionOrder: "일반",
    workOrderPriority: "5순위",
    note: "(4순위 비워둠)",
  },
  {
    key: "low",
    label: "낮음",
    productionOrder: "낮음",
    workOrderPriority: "9순위",
    note: "뒤로 쪽 밀어둠",
  },
];

// 샘플 수주 정보
const SAMPLE_ORDER_INFO: OrderInfo = {
  orderNumber: "KD-TS-251217-09",
  client: "태영건설(주)",
  siteName: "데시앙 동탄 파크뷰",
  dueDate: "2026-02-25",
  itemCount: 3,
  totalQuantity: "3EA",
  creditGrade: "A (우량)",
  status: "재작업중",
};

// 샘플 작업지시 카드
const SAMPLE_WORK_ORDER_CARDS: WorkOrderCard[] = [
  {
    id: "1",
    type: "스크린",
    orderNumber: "KD-PL-251223-01",
    itemCount: 3,
    totalQuantity: "3EA",
    processes: ["1. 원단절단", "2. 미싱", "3. 앤드락작업", "4. 중간검사", "5. 포장"],
  },
  {
    id: "2",
    type: "절곡",
    orderNumber: "KD-PL-251223-02",
    itemCount: 3,
    totalQuantity: "3EA",
    processes: ["1. 절단", "2. 절곡", "3. 중간검사", "4. 포장"],
  },
];

// 샘플 자재 소요량
const SAMPLE_MATERIALS: MaterialRequirement[] = [
  {
    materialCode: "SCR-MAT-001",
    materialName: "스크린 원단",
    unit: "㎡",
    required: 45,
    currentStock: 500,
    status: "sufficient",
  },
  {
    materialCode: "SCR-MAT-002",
    materialName: "앤드락",
    unit: "EA",
    required: 6,
    currentStock: 800,
    status: "sufficient",
  },
  {
    materialCode: "BND-MAT-001",
    materialName: "철판",
    unit: "KG",
    required: 90,
    currentStock: 2000,
    status: "sufficient",
  },
  {
    materialCode: "BND-MAT-002",
    materialName: "가이드레일",
    unit: "M",
    required: 18,
    currentStock: 300,
    status: "sufficient",
  },
  {
    materialCode: "BND-MAT-003",
    materialName: "케이스",
    unit: "EA",
    required: 3,
    currentStock: 100,
    status: "sufficient",
  },
];

// 샘플 스크린 품목 상세
const SAMPLE_SCREEN_ITEMS: ScreenItemDetail[] = [
  {
    no: 1,
    itemName: "스크린 셔터 (프리미엄)",
    location: "로비 I-01",
    openWidth: 4500,
    openHeight: 3500,
    productWidth: 4640,
    productHeight: 3900,
    guideRail: "백면형 120-70",
    shaft: '4"',
    capacity: "160kg",
    finish: "SUS마감",
    quantity: 1,
  },
  {
    no: 2,
    itemName: "스크린 셔터 (프리미엄)",
    location: "카페 I-02",
    openWidth: 4500,
    openHeight: 3500,
    productWidth: 4640,
    productHeight: 3900,
    guideRail: "백면형 120-70",
    shaft: '4"',
    capacity: "160kg",
    finish: "SUS마감",
    quantity: 1,
  },
  {
    no: 3,
    itemName: "스크린 셔터 (프리미엄)",
    location: "헬스장 I-03",
    openWidth: 4500,
    openHeight: 3500,
    productWidth: 4640,
    productHeight: 3900,
    guideRail: "백면형 120-70",
    shaft: '4"',
    capacity: "160kg",
    finish: "SUS마감",
    quantity: 1,
  },
];

// 샘플 가이드레일 BOM
const SAMPLE_GUIDE_RAIL_BOM: GuideRailBom[] = [
  {
    type: "백면형",
    spec: "120-70",
    code: "KSE01/KWE01",
    length: 3000,
    quantity: 6,
  },
];

// 샘플 케이스(셔터박스) BOM
const SAMPLE_CASE_BOM: CaseBom[] = [
  { item: "케이스 본체", length: "L: 4000", quantity: 2 },
  { item: "측면 덮개", length: "500-355", quantity: 6 },
];

// 샘플 하단 마감재 BOM
const SAMPLE_BOTTOM_FINISH_BOM: BottomFinishBom[] = [
  { item: "하단마감재", spec: "50-40", length: "L: 4000", quantity: 3 },
];

export default function ProductionOrderCreatePage() {
  const router = useRouter();
  const params = useParams();
  const orderId = params.id as string;

  const [loading, setLoading] = useState(true);
  const [orderInfo, setOrderInfo] = useState<OrderInfo | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 우선순위 상태
  const [selectedPriority, setSelectedPriority] = useState<PriorityLevel>("normal");
  const [memo, setMemo] = useState("");

  // 성공 다이얼로그 상태
  const [showSuccessDialog, setShowSuccessDialog] = useState(false);
  const [generatedOrderNumber, setGeneratedOrderNumber] = useState("");

  // 데이터 로드
  useEffect(() => {
    setTimeout(() => {
      setOrderInfo(SAMPLE_ORDER_INFO);
      setLoading(false);
    }, 300);
  }, [orderId]);

  const handleCancel = () => {
    router.push(`/sales/order-management-sales/${orderId}`);
  };

  const handleBackToDetail = () => {
    router.push(`/sales/order-management-sales/${orderId}`);
  };

  const handleConfirm = async () => {
    setIsSubmitting(true);
    try {
      // TODO: API 호출
      await new Promise((resolve) => setTimeout(resolve, 500));

      // 생산지시번호 생성 (실제로는 API 응답에서 받아옴)
      const today = new Date();
      const dateStr = `${String(today.getFullYear()).slice(2)}${String(today.getMonth() + 1).padStart(2, "0")}${String(today.getDate()).padStart(2, "0")}`;
      const newOrderNumber = `PO-${orderInfo?.orderNumber.replace("KD-TS-", "KD-") || "KD-000000"}-${dateStr}`;

      setGeneratedOrderNumber(newOrderNumber);
      setShowSuccessDialog(true);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleSuccessDialogClose = () => {
    setShowSuccessDialog(false);
    // 생산지시 상세 페이지로 이동 (실제로는 API 응답에서 받은 생산지시 ID 사용)
    // 임시로 PO-002 사용 (샘플 데이터와 매칭)
    router.push("/sales/order-management-sales/production-orders/PO-002");
  };

  // 선택된 우선순위 설정 가져오기
  const getSelectedPriorityConfig = () => {
    return PRIORITY_CONFIGS.find((p) => p.key === selectedPriority);
  };

  if (loading) {
    return (
      <PageLayout>
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
        </div>
      </PageLayout>
    );
  }

  if (!orderInfo) {
    return (
      <PageLayout>
        <div className="text-center py-12">
          <p className="text-muted-foreground">수주 정보를 찾을 수 없습니다.</p>
          <Button variant="outline" onClick={handleCancel} className="mt-4">
            <ArrowLeft className="h-4 w-4 mr-2" />
            돌아가기
          </Button>
        </div>
      </PageLayout>
    );
  }

  const selectedConfig = getSelectedPriorityConfig();
  const workOrderCount = SAMPLE_WORK_ORDER_CARDS.length;

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader
        title={
          <div className="flex items-center gap-3">
            <span>생산지시 생성</span>
            <BadgeSm className="bg-gray-100 text-gray-700 border-gray-200">
              {workOrderCount}개 작업지시 생성 예정
            </BadgeSm>
          </div>
        }
        icon={Factory}
        actions={
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={handleCancel}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              취소
            </Button>
            <Button onClick={handleConfirm} disabled={isSubmitting}>
              <BarChart3 className="h-4 w-4 mr-2" />
              생산지시 확정
            </Button>
          </div>
        }
      />

      <div className="space-y-6">
        {/* 수주 정보 */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">수주 정보</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
              <div>
                <p className="text-sm text-muted-foreground mb-1">수주번호</p>
                <p className="font-semibold">{orderInfo.orderNumber}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">거래처</p>
                <p className="font-medium">{orderInfo.client}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">현장명</p>
                <p className="font-medium">{orderInfo.siteName}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">납기일</p>
                <p className="font-semibold">{orderInfo.dueDate}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">품목 수</p>
                <p className="font-medium">{orderInfo.itemCount}건</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">총수량</p>
                <p className="font-medium">{orderInfo.totalQuantity}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">신용등급</p>
                <BadgeSm className="bg-green-100 text-green-700 border-green-200">
                  {orderInfo.creditGrade}
                </BadgeSm>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">상태</p>
                <p className="font-semibold">{orderInfo.status}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 생산지시 옵션 */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">생산지시 옵션</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 우선순위 (영업) */}
            <div>
              <p className="text-sm font-medium mb-3">우선순위 (영업)</p>
              <div className="flex gap-2 mb-4">
                {PRIORITY_CONFIGS.map((config) => {
                  const colors = PRIORITY_COLORS[config.key];
                  return (
                    <button
                      key={config.key}
                      onClick={() => setSelectedPriority(config.key)}
                      className={cn(
                        "px-4 py-2 rounded-md text-sm font-medium transition-colors",
                        selectedPriority === config.key
                          ? colors.buttonActive
                          : colors.button
                      )}
                    >
                      {config.label}
                    </button>
                  );
                })}
              </div>

              {/* 우선순위 테이블 */}
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[200px]">생산지시 (영업)</TableHead>
                      <TableHead className="w-[200px]">작업지시 기본값 (공장)</TableHead>
                      <TableHead>비고 (현장의 여유 공간)</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {PRIORITY_CONFIGS.map((config) => {
                      const colors = PRIORITY_COLORS[config.key];
                      const isSelected = selectedPriority === config.key;
                      return (
                        <TableRow
                          key={config.key}
                          className={cn(isSelected && colors.bg)}
                        >
                          <TableCell className={cn("font-medium", isSelected && colors.text)}>
                            {config.productionOrder}
                          </TableCell>
                          <TableCell>
                            <BadgeSm className={cn(colors.bg, colors.text, colors.border)}>
                              {config.workOrderPriority}
                            </BadgeSm>
                          </TableCell>
                          <TableCell className="text-muted-foreground">{config.note}</TableCell>
                        </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              </div>

              {/* 선택된 설정 표시 */}
              {selectedConfig && (
                <div className="flex items-center gap-2 mt-4">
                  <span className="text-sm text-muted-foreground">선택된 설정:</span>
                  <BadgeSm className={cn(
                    PRIORITY_COLORS[selectedPriority].bg,
                    PRIORITY_COLORS[selectedPriority].text,
                    PRIORITY_COLORS[selectedPriority].border
                  )}>
                    생산지시: {selectedConfig.productionOrder}
                  </BadgeSm>
                  <span className="text-muted-foreground">→</span>
                  <BadgeSm className={cn(
                    PRIORITY_COLORS[selectedPriority].bg,
                    PRIORITY_COLORS[selectedPriority].text,
                    PRIORITY_COLORS[selectedPriority].border
                  )}>
                    작업지시: {selectedConfig.workOrderPriority}
                  </BadgeSm>
                </div>
              )}
            </div>

            {/* 메모 */}
            <div>
              <p className="text-sm font-medium mb-2">메모</p>
              <Textarea
                value={memo}
                onChange={(e) => setMemo(e.target.value)}
                placeholder="생산지시 관련 특이사항..."
                rows={3}
              />
            </div>
          </CardContent>
        </Card>

        {/* 생성될 작업지시 */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">생성될 작업지시 ({workOrderCount}건)</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {SAMPLE_WORK_ORDER_CARDS.map((card) => (
                <div
                  key={card.id}
                  className={cn(
                    "border rounded-lg p-4",
                    card.type === "스크린" ? "bg-blue-50/50 border-blue-200" : "bg-orange-50/50 border-orange-200"
                  )}
                >
                  <div className="flex items-center justify-between mb-3">
                    <BadgeSm className={cn(
                      card.type === "스크린"
                        ? "bg-blue-100 text-blue-700 border-blue-200"
                        : "bg-orange-100 text-orange-700 border-orange-200"
                    )}>
                      {card.type}
                    </BadgeSm>
                    <span className="font-mono text-sm font-medium">{card.orderNumber}</span>
                  </div>
                  <div className="grid grid-cols-2 gap-4 mb-3">
                    <div>
                      <p className="text-sm text-muted-foreground">품목 수</p>
                      <p className="font-medium">{card.itemCount}건</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">총 수량</p>
                      <p className="font-medium">{card.totalQuantity}</p>
                    </div>
                  </div>
                  <div>
                    <p className="text-sm text-muted-foreground mb-2">공정 순서</p>
                    <div className="flex flex-wrap gap-2">
                      {card.processes.map((process, idx) => (
                        <BadgeSm
                          key={idx}
                          className="bg-gray-50 text-gray-600 border-gray-200"
                        >
                          {process}
                        </BadgeSm>
                      ))}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* 자재 소요량 및 재고 현황 */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">자재 소요량 및 재고 현황</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="border rounded-lg overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>자재코드</TableHead>
                    <TableHead>자재명</TableHead>
                    <TableHead className="text-center">단위</TableHead>
                    <TableHead className="text-right">소요량</TableHead>
                    <TableHead className="text-right">현재고</TableHead>
                    <TableHead className="text-center">상태</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {SAMPLE_MATERIALS.map((item) => (
                    <TableRow key={item.materialCode}>
                      <TableCell>
                        <code className="text-xs bg-gray-100 px-1.5 py-0.5 rounded">
                          {item.materialCode}
                        </code>
                      </TableCell>
                      <TableCell>{item.materialName}</TableCell>
                      <TableCell className="text-center">{item.unit}</TableCell>
                      <TableCell className="text-right font-medium">{item.required}</TableCell>
                      <TableCell className="text-right">{item.currentStock.toLocaleString()}</TableCell>
                      <TableCell className="text-center">
                        <BadgeSm
                          className={cn(
                            item.status === "sufficient"
                              ? "bg-green-100 text-green-700 border-green-200"
                              : "bg-red-100 text-red-700 border-red-200"
                          )}
                        >
                          {item.status === "sufficient" ? "충분" : "부족"}
                        </BadgeSm>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>

        {/* 스크린 품목 상세 */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">스크린 품목 상세 ({SAMPLE_SCREEN_ITEMS.length}건)</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="border rounded-lg overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[50px] text-center">No</TableHead>
                    <TableHead>품목명</TableHead>
                    <TableHead>도면위치</TableHead>
                    <TableHead className="text-right">개구폭</TableHead>
                    <TableHead className="text-right">개구높이</TableHead>
                    <TableHead className="text-right">제작폭</TableHead>
                    <TableHead className="text-right">제작높이</TableHead>
                    <TableHead>가이드레일</TableHead>
                    <TableHead className="text-center">샤프트</TableHead>
                    <TableHead className="text-center">용량</TableHead>
                    <TableHead>마감</TableHead>
                    <TableHead className="text-center">수량</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {SAMPLE_SCREEN_ITEMS.map((item) => (
                    <TableRow key={item.no}>
                      <TableCell className="text-center font-medium">
                        {String(item.no).padStart(2, "0")}
                      </TableCell>
                      <TableCell>{item.itemName}</TableCell>
                      <TableCell>{item.location}</TableCell>
                      <TableCell className="text-right">{item.openWidth.toLocaleString()}</TableCell>
                      <TableCell className="text-right">{item.openHeight.toLocaleString()}</TableCell>
                      <TableCell className="text-right">{item.productWidth.toLocaleString()}</TableCell>
                      <TableCell className="text-right">{item.productHeight.toLocaleString()}</TableCell>
                      <TableCell>{item.guideRail}</TableCell>
                      <TableCell className="text-center">{item.shaft}</TableCell>
                      <TableCell className="text-center">{item.capacity}</TableCell>
                      <TableCell>{item.finish}</TableCell>
                      <TableCell className="text-center">{item.quantity}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>

        {/* 모터/전장품 사양 */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">모터/전장품 사양</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <p className="text-sm text-muted-foreground mb-1">모터 사양 (380V)</p>
                <div className="flex items-center gap-4">
                  <span className="font-medium">KD-150K</span>
                  <span className="text-muted-foreground">3대</span>
                </div>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">모터 브라켓</p>
                <div className="flex items-center gap-4">
                  <span className="font-medium">380-180 [2-4"]</span>
                  <span className="text-muted-foreground">3개</span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 절곡물 BOM */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">절곡물 BOM</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 가이드레일 */}
            <div>
              <h4 className="text-sm font-medium mb-2">가이드레일</h4>
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>형태</TableHead>
                      <TableHead>규격</TableHead>
                      <TableHead>코드</TableHead>
                      <TableHead className="text-right">길이</TableHead>
                      <TableHead className="text-center">수량</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {SAMPLE_GUIDE_RAIL_BOM.map((item, index) => (
                      <TableRow key={index}>
                        <TableCell>{item.type}</TableCell>
                        <TableCell>{item.spec}</TableCell>
                        <TableCell>{item.code}</TableCell>
                        <TableCell className="text-right">{item.length.toLocaleString()}</TableCell>
                        <TableCell className="text-center">{item.quantity}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>

            {/* 케이스(셔터박스) */}
            <div>
              <h4 className="text-sm font-medium mb-2">케이스(셔터박스) - 메인 규격: 500-330</h4>
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>품목</TableHead>
                      <TableHead>길이</TableHead>
                      <TableHead className="text-center">수량</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {SAMPLE_CASE_BOM.map((item, index) => (
                      <TableRow key={index}>
                        <TableCell>{item.item}</TableCell>
                        <TableCell>{item.length}</TableCell>
                        <TableCell className="text-center">{item.quantity}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>

            {/* 하단 마감재 */}
            <div>
              <h4 className="text-sm font-medium mb-2">하단 마감재</h4>
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>품목</TableHead>
                      <TableHead>규격</TableHead>
                      <TableHead>길이</TableHead>
                      <TableHead className="text-center">수량</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {SAMPLE_BOTTOM_FINISH_BOM.map((item, index) => (
                      <TableRow key={index}>
                        <TableCell>{item.item}</TableCell>
                        <TableCell>{item.spec}</TableCell>
                        <TableCell>{item.length}</TableCell>
                        <TableCell className="text-center">{item.quantity}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 하단 버튼 영역 */}
      <div className="sticky bottom-0 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 border-t pt-4 pb-4 -mx-3 md:-mx-6 px-3 md:px-6 mt-6">
        <div className="flex items-center justify-between">
          {/* 우선순위 뱃지 */}
          <div className="flex items-center gap-4">
            {selectedConfig && (
              <BadgeSm className={cn(
                PRIORITY_COLORS[selectedPriority].buttonActive,
                "border-0"
              )}>
                우선순위: {selectedConfig.productionOrder}
              </BadgeSm>
            )}
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={handleBackToDetail}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              수주상세로
            </Button>
            <Button onClick={handleConfirm} disabled={isSubmitting}>
              <BarChart3 className="h-4 w-4 mr-2" />
              생산지시 확정 ({SAMPLE_SCREEN_ITEMS.length}건)
            </Button>
          </div>
        </div>
      </div>

      {/* 생산지시 생성 성공 다이얼로그 */}
      <AlertDialog open={showSuccessDialog} onOpenChange={setShowSuccessDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2">
              <CheckCircle2 className="h-5 w-5 text-green-600" />
              생산지시가 생성되었습니다.
            </AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div className="space-y-4 pt-2">
                <div>
                  <p className="text-sm text-muted-foreground">생산지시번호:</p>
                  <p className="font-mono font-semibold text-foreground">{generatedOrderNumber}</p>
                </div>
                <p className="text-sm text-muted-foreground">
                  생산관리 &gt; 생산지시 관리에서 작업지시서를 생성하세요.
                </p>
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogAction onClick={handleSuccessDialogClose}>
              확인
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}