"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 { Badge } from "@/components/ui/badge";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Factory,
  ArrowLeft,
  ClipboardList,
  CheckCircle2,
  Circle,
  Activity,
  Play,
} from "lucide-react";
import { PageLayout } from "@/components/organisms/PageLayout";
import { PageHeader } from "@/components/organisms/PageHeader";
import { BadgeSm } from "@/components/atoms/BadgeSm";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { toast } from "sonner";
import { ServerErrorPage } from "@/components/common/ServerErrorPage";
import { formatNumber } from '@/lib/utils/amount';

// 생산지시 상태 타입
type ProductionOrderStatus = "waiting" | "in_progress" | "completed";

// 작업지시 상태 타입
type WorkOrderStatus = "pending" | "in_progress" | "completed";

// 작업지시 데이터 타입
interface WorkOrder {
  id: string;
  workOrderNumber: string;  // KD-WO-XXXXXX-XX
  process: string;          // 공정명
  quantity: number;
  status: WorkOrderStatus;
  assignee: string;
}

// 생산지시 상세 데이터 타입
interface ProductionOrderDetail {
  id: string;
  productionOrderNumber: string;
  orderNumber: string;
  productionOrderDate: string;
  dueDate: string;
  quantity: number;
  status: ProductionOrderStatus;
  client: string;
  siteName: string;
  productType: string;
  pendingWorkOrderCount: number;  // 생성 예정 작업지시 수
  workOrders: WorkOrder[];
}

// 샘플 생산지시 상세 데이터
const SAMPLE_PRODUCTION_ORDER_DETAILS: Record<string, ProductionOrderDetail> = {
  "PO-001": {
    id: "PO-001",
    productionOrderNumber: "PO-KD-TS-251217-07",
    orderNumber: "KD-TS-251217-07",
    productionOrderDate: "2025-12-22",
    dueDate: "2026-02-15",
    quantity: 2,
    status: "completed",  // 생산완료 상태 - 목록 버튼만 표시
    client: "호반건설(주)",
    siteName: "씨밋 광교 센트럴시티",
    productType: "",
    pendingWorkOrderCount: 0,  // 작업지시 이미 생성됨
    workOrders: [
      {
        id: "WO-001",
        workOrderNumber: "KD-WO-251217-07",
        process: "재단",
        quantity: 2,
        status: "completed",
        assignee: "-",
      },
      {
        id: "WO-002",
        workOrderNumber: "KD-WO-251217-08",
        process: "조립",
        quantity: 2,
        status: "completed",
        assignee: "-",
      },
      {
        id: "WO-003",
        workOrderNumber: "KD-WO-251217-09",
        process: "검수",
        quantity: 2,
        status: "completed",
        assignee: "-",
      },
    ],
  },
  "PO-002": {
    id: "PO-002",
    productionOrderNumber: "PO-KD-TS-251217-09",
    orderNumber: "KD-TS-251217-09",
    productionOrderDate: "2025-12-22",
    dueDate: "2026-02-10",
    quantity: 10,
    status: "waiting",
    client: "태영건설(주)",
    siteName: "데시앙 동탄 파크뷰",
    productType: "",
    pendingWorkOrderCount: 5,  // 생성 예정 작업지시 5개 (일괄생성)
    workOrders: [],
  },
  "PO-003": {
    id: "PO-003",
    productionOrderNumber: "PO-KD-TS-251217-06",
    orderNumber: "KD-TS-251217-06",
    productionOrderDate: "2025-12-22",
    dueDate: "2026-02-10",
    quantity: 1,
    status: "waiting",
    client: "롯데건설(주)",
    siteName: "예술 검실 푸르지오",
    productType: "",
    pendingWorkOrderCount: 1,  // 생성 예정 작업지시 1개 (단일 생성)
    workOrders: [],
  },
  "PO-004": {
    id: "PO-004",
    productionOrderNumber: "PO-KD-BD-251220-35",
    orderNumber: "KD-BD-251220-35",
    productionOrderDate: "2025-12-20",
    dueDate: "2026-02-03",
    quantity: 3,
    status: "in_progress",
    client: "현대건설(주)",
    siteName: "[코레타스프] 판교 물류센터 철거현장",
    productType: "",
    pendingWorkOrderCount: 0,
    workOrders: [
      {
        id: "WO-004",
        workOrderNumber: "KD-WO-251220-01",
        process: "재단",
        quantity: 3,
        status: "completed",
        assignee: "-",
      },
      {
        id: "WO-005",
        workOrderNumber: "KD-WO-251220-02",
        process: "조립",
        quantity: 3,
        status: "in_progress",
        assignee: "-",
      },
    ],
  },
};

// 공정 진행 현황 컴포넌트
function ProcessProgress({ workOrders }: { workOrders: WorkOrder[] }) {
  if (workOrders.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <Activity className="h-4 w-4" />
            공정 진행 현황
          </CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground text-sm text-center py-4">
            아직 작업지시가 생성되지 않았습니다.
          </p>
        </CardContent>
      </Card>
    );
  }

  const completedCount = workOrders.filter((w) => w.status === "completed").length;
  const totalCount = workOrders.length;
  const progressPercent = Math.round((completedCount / totalCount) * 100);

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base flex items-center gap-2">
          <Activity className="h-4 w-4" />
          공정 진행 현황
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-4">
          {/* 진행률 바 */}
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">진행률</span>
              <span className="font-medium">{progressPercent}%</span>
            </div>
            <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
              <div
                className="h-full bg-primary transition-all"
                style={{ width: `${progressPercent}%` }}
              />
            </div>
          </div>

          {/* 공정 단계 */}
          <div className="flex items-center justify-center gap-2 pt-2">
            {workOrders.map((wo, index) => (
              <div key={wo.id} className="flex items-center">
                <div className="flex flex-col items-center gap-1">
                  <div
                    className={`flex items-center justify-center w-8 h-8 rounded-full ${
                      wo.status === "completed"
                        ? "bg-green-500 text-white"
                        : wo.status === "in_progress"
                        ? "bg-blue-500 text-white"
                        : "bg-gray-100 text-gray-400"
                    }`}
                  >
                    {wo.status === "completed" ? (
                      <CheckCircle2 className="h-4 w-4" />
                    ) : (
                      <Circle className="h-4 w-4" />
                    )}
                  </div>
                  <span className="text-xs text-muted-foreground">{wo.process}</span>
                </div>
                {index < workOrders.length - 1 && (
                  <div
                    className={`w-12 h-0.5 mx-1 ${
                      wo.status === "completed" ? "bg-green-500" : "bg-gray-200"
                    }`}
                  />
                )}
              </div>
            ))}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

// 상태 배지 헬퍼
function getStatusBadge(status: ProductionOrderStatus) {
  const config: Record<ProductionOrderStatus, { label: string; className: string }> = {
    waiting: {
      label: "생산대기",
      className: "bg-yellow-100 text-yellow-700 border-yellow-200",
    },
    in_progress: {
      label: "생산중",
      className: "bg-green-100 text-green-700 border-green-200",
    },
    completed: {
      label: "생산완료",
      className: "bg-gray-100 text-gray-700 border-gray-200",
    },
  };
  const c = config[status];
  return <BadgeSm className={c.className}>{c.label}</BadgeSm>;
}

// 작업지시 상태 배지 헬퍼
function getWorkOrderStatusBadge(status: WorkOrderStatus) {
  const config: Record<WorkOrderStatus, { label: string; className: string }> = {
    pending: {
      label: "대기",
      className: "bg-gray-100 text-gray-700 border-gray-200",
    },
    in_progress: {
      label: "작업중",
      className: "bg-blue-100 text-blue-700 border-blue-200",
    },
    completed: {
      label: "완료",
      className: "bg-green-100 text-green-700 border-green-200",
    },
  };
  const c = config[status];
  return <BadgeSm className={c.className}>{c.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>
  );
}

// 샘플 공정 목록 (작업지시 생성 팝업에 표시용)
const SAMPLE_PROCESSES = [
  { id: "P1", name: "1.1 백판필름", quantity: 10 },
  { id: "P2", name: "2. 하안마감재", quantity: 10 },
  { id: "P3", name: "3.1 케이스", quantity: 10 },
  { id: "P4", name: "4. 연기단자", quantity: 10 },
  { id: "P5", name: "5. 가이드레일 하부브라켓", quantity: 10 },
];

// BOM 품목 타입
interface BomItem {
  id: string;
  itemCode: string;
  itemName: string;
  spec: string;
  lotNo: string;
  requiredQty: number;
  qty: number;
}

// BOM 공정 분류 타입
interface BomProcessGroup {
  processName: string;
  sizeSpec?: string;
  items: BomItem[];
}

// BOM 품목별 공정 분류 목데이터
const SAMPLE_BOM_PROCESS_GROUPS: BomProcessGroup[] = [
  {
    processName: "1.1 백판필름",
    sizeSpec: "[20-70]",
    items: [
      { id: "B1", itemCode: "①", itemName: "아연판", spec: "EGI.6T", lotNo: "LOT-M-2024-001", requiredQty: 4300, qty: 8 },
      { id: "B2", itemCode: "②", itemName: "가이드레일", spec: "EGI.6T", lotNo: "LOT-M-2024-002", requiredQty: 3000, qty: 4 },
      { id: "B3", itemCode: "③", itemName: "C형", spec: "EGI.6ST", lotNo: "LOT-M-2024-003", requiredQty: 4300, qty: 4 },
      { id: "B4", itemCode: "④", itemName: "D형", spec: "EGI.6T", lotNo: "LOT-M-2024-004", requiredQty: 4300, qty: 4 },
      { id: "B5", itemCode: "⑤", itemName: "행거마감재", spec: "SUS1.2T", lotNo: "LOT-M-2024-005", requiredQty: 4300, qty: 2 },
      { id: "B6", itemCode: "⑥", itemName: "R/RBASE", spec: "EGI.5ST", lotNo: "LOT-M-2024-006", requiredQty: 0, qty: 4 },
    ],
  },
  {
    processName: "2. 하안마감재",
    sizeSpec: "[60-40]",
    items: [
      { id: "B7", itemCode: "①", itemName: "하안마감재", spec: "EGI.5T", lotNo: "LOT-M-2024-007", requiredQty: 3000, qty: 4 },
      { id: "B8", itemCode: "②", itemName: "하안보강재판", spec: "EGI.5T", lotNo: "LOT-M-2024-009", requiredQty: 3000, qty: 4 },
      { id: "B9", itemCode: "③", itemName: "하안보강멈틀", spec: "EGI.1T", lotNo: "LOT-M-2024-010", requiredQty: 0, qty: 2 },
      { id: "B10", itemCode: "④", itemName: "행거마감재", spec: "SUS1.2T", lotNo: "LOT-M-2024-008", requiredQty: 3000, qty: 2 },
    ],
  },
  {
    processName: "3.1 케이스",
    sizeSpec: "[500*330]",
    items: [
      { id: "B11", itemCode: "①", itemName: "전판", spec: "EGI.5ST", lotNo: "LOT-M-2024-011", requiredQty: 0, qty: 2 },
      { id: "B12", itemCode: "②", itemName: "전멈틀", spec: "EGI.5T", lotNo: "LOT-M-2024-012", requiredQty: 0, qty: 4 },
      { id: "B13", itemCode: "③⑤", itemName: "타부멈틀", spec: "", lotNo: "LOT-M-2024-013", requiredQty: 0, qty: 2 },
      { id: "B14", itemCode: "④", itemName: "좌우판-HW", spec: "", lotNo: "LOT-M-2024-014", requiredQty: 0, qty: 2 },
      { id: "B15", itemCode: "⑥", itemName: "상부판", spec: "", lotNo: "LOT-M-2024-015", requiredQty: 1220, qty: 5 },
      { id: "B16", itemCode: "⑦", itemName: "측판(전산판)", spec: "", lotNo: "LOT-M-2024-016", requiredQty: 0, qty: 2 },
    ],
  },
  {
    processName: "4. 연기단자",
    sizeSpec: "",
    items: [
      { id: "B17", itemCode: "-", itemName: "레일홀 (W50)", spec: "EGI.8T + 화이버 금사", lotNo: "LOT-M-2024-017", requiredQty: 0, qty: 4 },
      { id: "B18", itemCode: "-", itemName: "카이드홀 (W60)", spec: "EGI.8T + 화이버 금사", lotNo: "LOT-M-2024-018", requiredQty: 0, qty: 4 },
    ],
  },
];

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

  const [productionOrder, setProductionOrder] = useState<ProductionOrderDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [isCreateWorkOrderDialogOpen, setIsCreateWorkOrderDialogOpen] = useState(false);
  const [isSuccessDialogOpen, setIsSuccessDialogOpen] = useState(false);
  const [createdWorkOrders, setCreatedWorkOrders] = useState<string[]>([]);
  const [isCreating, setIsCreating] = useState(false);

  // 데이터 로드
  useEffect(() => {
    setTimeout(() => {
      const found = SAMPLE_PRODUCTION_ORDER_DETAILS[productionOrderId];
      setProductionOrder(found || null);
      setLoading(false);
    }, 300);
  }, [productionOrderId]);

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

  const handleCreateWorkOrder = () => {
    setIsCreateWorkOrderDialogOpen(true);
  };

  const handleConfirmCreateWorkOrder = async () => {
    setIsCreating(true);
    try {
      // API 호출 시뮬레이션
      await new Promise((resolve) => setTimeout(resolve, 500));

      // 생성된 작업지시서 목록 (실제로는 API 응답에서 받음)
      const workOrderCount = productionOrder?.pendingWorkOrderCount || 0;
      const created = Array.from({ length: workOrderCount }, (_, i) =>
        `KD-WO-251223-${String(i + 1).padStart(2, "0")}`
      );
      setCreatedWorkOrders(created);

      // 확인 팝업 닫고 성공 팝업 열기
      setIsCreateWorkOrderDialogOpen(false);
      setIsSuccessDialogOpen(true);
    } finally {
      setIsCreating(false);
    }
  };

  const handleSuccessDialogClose = () => {
    setIsSuccessDialogOpen(false);
    // 작업지시 관리 페이지로 이동
    router.push("/production/work-orders");
  };

  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 (!productionOrder) {
    return (
      <ServerErrorPage
        title="생산지시 정보를 불러올 수 없습니다"
        message="생산지시 정보를 찾을 수 없습니다."
        showBackButton={true}
        showHomeButton={true}
      />
    );
  }

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader
        title={
          <div className="flex items-center gap-3">
            <span>생산지시 상세</span>
            <code className="text-sm font-mono bg-blue-50 text-blue-700 px-2 py-1 rounded">
              {productionOrder.productionOrderNumber}
            </code>
            {getStatusBadge(productionOrder.status)}
          </div>
        }
        icon={Factory}
        actions={
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={handleBack}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              목록
            </Button>
            {/* 작업지시 생성 버튼 - 완료 아님 + 작업지시 없음 + 생성 예정 있음 */}
            {productionOrder.status !== "completed" &&
              productionOrder.workOrders.length === 0 &&
              productionOrder.pendingWorkOrderCount > 0 && (
              <Button onClick={handleCreateWorkOrder}>
                <ClipboardList className="h-4 w-4 mr-2" />
                작업지시 생성
              </Button>
            )}
          </div>
        }
      />

      <div className="space-y-6">
        {/* 공정 진행 현황 */}
        <ProcessProgress workOrders={productionOrder.workOrders} />

        {/* 기본 정보 & 거래처/현장 정보 */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* 기본 정보 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base">기본 정보</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                <InfoItem label="생산지시번호" value={productionOrder.productionOrderNumber} />
                <InfoItem label="수주번호" value={productionOrder.orderNumber} />
                <InfoItem label="생산지시일" value={productionOrder.productionOrderDate} />
                <InfoItem label="납기일" value={productionOrder.dueDate} />
                <InfoItem label="수량" value={`${productionOrder.quantity}개`} />
              </div>
            </CardContent>
          </Card>

          {/* 거래처/현장 정보 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-base">거래처/현장 정보</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                <InfoItem label="거래처" value={productionOrder.client} />
                <InfoItem label="현장명" value={productionOrder.siteName} />
                <InfoItem label="제품유형" value={productionOrder.productType} />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* BOM 품목별 공정 분류 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">BOM 품목별 공정 분류</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 절곡 부품 전개도 정보 헤더 */}
            <p className="text-sm font-medium text-muted-foreground border-b pb-2">
              절곡 부품 전개도 정보
            </p>

            {/* 공정별 테이블 */}
            {SAMPLE_BOM_PROCESS_GROUPS.map((group) => (
              <div key={group.processName} className="space-y-2">
                {/* 공정명 헤더 */}
                <h4 className="text-sm font-semibold">
                  {group.processName}
                  {group.sizeSpec && (
                    <span className="ml-2 text-muted-foreground font-normal">
                      {group.sizeSpec}
                    </span>
                  )}
                </h4>

                {/* BOM 품목 테이블 */}
                <div className="border rounded-lg overflow-hidden">
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-gray-50">
                        <TableHead className="w-[60px] text-center">항목코드</TableHead>
                        <TableHead>세부품명</TableHead>
                        <TableHead>규격</TableHead>
                        <TableHead>LOT NO</TableHead>
                        <TableHead className="text-right">필요수량</TableHead>
                        <TableHead className="text-center w-[60px]">수량</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {group.items.map((item) => (
                        <TableRow key={item.id}>
                          <TableCell className="text-center font-medium">
                            {item.itemCode}
                          </TableCell>
                          <TableCell>{item.itemName}</TableCell>
                          <TableCell className="text-muted-foreground">
                            {item.spec || "-"}
                          </TableCell>
                          <TableCell>
                            <code className="text-xs bg-gray-100 px-1.5 py-0.5 rounded">
                              {item.lotNo}
                            </code>
                          </TableCell>
                          <TableCell className="text-right">
                            {item.requiredQty > 0 ? formatNumber(item.requiredQty) : "-"}
                          </TableCell>
                          <TableCell className="text-center">{item.qty}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </div>
            ))}

            {/* 합계 정보 */}
            <div className="flex justify-between items-center pt-4 border-t text-sm">
              <span className="text-muted-foreground">총 부품 종류: 18개</span>
              <span className="text-muted-foreground">총 중량: 25.8 kg</span>
              <span className="text-muted-foreground">비고: VT칼 작업 완료 후 절곡 진행</span>
            </div>
          </CardContent>
        </Card>

        {/* 작업지시서 목록 */}
        <Card>
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-base">작업지시서 목록</CardTitle>
            {/* 버튼 조건: 완료 아님 + 작업지시 없음 + 생성 예정 있음 */}
            {productionOrder.status !== "completed" &&
             productionOrder.workOrders.length === 0 &&
             productionOrder.pendingWorkOrderCount > 0 && (
              <Button onClick={handleCreateWorkOrder}>
                <Play className="h-4 w-4 mr-2" />
                {productionOrder.pendingWorkOrderCount > 1
                  ? "작업지시 일괄생성"
                  : "작업지시 생성"}
              </Button>
            )}
          </CardHeader>
          <CardContent>
            {productionOrder.workOrders.length === 0 ? (
              <div className="text-center py-8">
                <div className="flex flex-col items-center gap-2">
                  <ClipboardList className="h-12 w-12 text-gray-300" />
                  <p className="text-muted-foreground text-sm">
                    아직 작업지시서가 생성되지 않았습니다.
                  </p>
                  {productionOrder.pendingWorkOrderCount > 0 && (
                    <p className="text-sm text-muted-foreground">
                      위 버튼을 클릭하여 BOM 기반 작업지시서를 자동 생성하세요.
                    </p>
                  )}
                </div>
              </div>
            ) : (
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>작업지시번호</TableHead>
                      <TableHead>공정</TableHead>
                      <TableHead className="text-center">수량</TableHead>
                      <TableHead>상태</TableHead>
                      <TableHead>담당자</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {productionOrder.workOrders.map((wo) => (
                      <TableRow key={wo.id}>
                        <TableCell>
                          <code className="text-xs bg-gray-100 px-1.5 py-0.5 rounded">
                            {wo.workOrderNumber}
                          </code>
                        </TableCell>
                        <TableCell>{wo.process}</TableCell>
                        <TableCell className="text-center">{wo.quantity}개</TableCell>
                        <TableCell>{getWorkOrderStatusBadge(wo.status)}</TableCell>
                        <TableCell>{wo.assignee}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 팝업1: 작업지시 생성 확인 다이얼로그 */}
      <ConfirmDialog
        open={isCreateWorkOrderDialogOpen}
        onOpenChange={setIsCreateWorkOrderDialogOpen}
        onConfirm={handleConfirmCreateWorkOrder}
        title="작업지시서 자동 생성"
        description={
          <div className="space-y-4 pt-2">
            <p className="font-medium text-foreground">
              다음 공정에 대한 작업지시서가 생성됩니다:
            </p>
            {productionOrder?.pendingWorkOrderCount && productionOrder.pendingWorkOrderCount > 0 && (
              <ul className="space-y-1 text-sm text-muted-foreground pl-4">
                {SAMPLE_PROCESSES.slice(0, productionOrder.pendingWorkOrderCount).map((process) => (
                  <li key={process.id} className="flex items-center gap-2">
                    <span className="w-1.5 h-1.5 bg-gray-400 rounded-full" />
                    {process.name} ({process.quantity}개)
                  </li>
                ))}
              </ul>
            )}
            <p className="text-muted-foreground">
              생성된 작업지시서는 생산팀에서 확인하고 작업을 진행할 수 있습니다.
            </p>
          </div>
        }
        confirmText="작업지시 생성"
        loading={isCreating}
      />

      {/* 팝업2: 작업지시 생성 성공 다이얼로그 */}
      <AlertDialog open={isSuccessDialogOpen} onOpenChange={setIsSuccessDialogOpen}>
        <AlertDialogContent className="max-w-md">
          <AlertDialogHeader>
            <AlertDialogTitle className="sr-only">작업지시 생성 완료</AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div className="space-y-4 pt-2">
                <div className="flex items-center gap-2">
                  <CheckCircle2 className="h-5 w-5 text-green-600" />
                  <span className="font-medium text-foreground">
                    {createdWorkOrders.length}개의 작업지시서가 공정별로 자동 생성되었습니다.
                  </span>
                </div>
                <div>
                  <p className="text-sm font-medium text-foreground mb-2">생성된 작업지시서:</p>
                  {createdWorkOrders.length > 0 ? (
                    <ul className="space-y-1 text-sm text-muted-foreground pl-4">
                      {createdWorkOrders.map((wo, idx) => (
                        <li key={wo} className="flex items-center gap-2">
                          <span className="w-1.5 h-1.5 bg-green-500 rounded-full" />
                          {wo}
                        </li>
                      ))}
                    </ul>
                  ) : (
                    <p className="text-sm text-muted-foreground">-</p>
                  )}
                </div>
                <p className="text-muted-foreground">
                  작업지시 관리 페이지로 이동합니다.
                </p>
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogAction onClick={handleSuccessDialogClose}>
              확인
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}