"use client";

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

import { useState, useEffect, useCallback } from "react";
import { useRouter, useParams } from "next/navigation";
import { useModules } from "@/hooks/useModules";
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 { Label } from "@/components/ui/label";
import { Factory, ArrowLeft, BarChart3, CheckCircle2, AlertCircle, User } from "lucide-react";
import { AssigneeSelectModal } from "@/components/document-system/modals";
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";
import {
  getOrderById,
  createProductionOrder,
  type Order,
  type CreateProductionOrderData,
} from "@/components/orders/actions";
import { getProcessList } from "@/components/process-management/actions";
import type { Process } from "@/types/process";
import { formatAmount } from "@/lib/utils/amount";

// 수주 정보 타입
interface _OrderInfo {
  orderNumber: string;
  client: string;
  siteName: string;
  dueDate: string;
  itemCount: number;
  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";
}

// 스크린 품목 상세 타입 (order.items에서 변환)
interface ScreenItemDetail {
  no: number;
  itemName: string;
  specification: string;
  quantity: number;
  unit: string;
  unitPrice: number;
  supplyAmount: number;
  taxAmount: number;
  totalAmount: 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 STATUS_LABELS: Record<string, string> = {
  order_registered: "수주등록",
  order_confirmed: "수주확정",
  production_ordered: "생산지시",
  in_production: "생산중",
  rework: "재작업중",
  work_completed: "작업완료",
  shipped: "출고완료",
  cancelled: "취소",
};

// 품목과 공정 매칭 함수
function matchItemToProcess(
  itemName: string,
  itemCode: string | undefined,
  processes: Process[]
): Process | null {
  for (const process of processes) {
    for (const rule of process.classificationRules) {
      if (!rule.isActive) continue;

      // 개별품목 규칙 (process_items에서 변환된 규칙)
      if (rule.registrationType === "individual" && rule.items) {
        const matched = rule.items.some((item) => {
          // 1. 정확한 이름 매칭
          if (item.name === itemName) return true;
          // 2. 정확한 코드 매칭
          if (itemCode && item.code === itemCode) return true;
          // 3. 부분 매칭: 등록된 품목명이 주문 품목명을 포함 (예: "상부 케이스 1219mm" contains "상부 케이스")
          if (item.name.includes(itemName)) return true;
          // 4. 역 부분 매칭: 주문 품목명이 등록된 품목명을 포함
          if (itemName.includes(item.name)) return true;
          return false;
        });
        if (matched) return process;
      }

      // 패턴 매칭 규칙
      if (rule.registrationType === "pattern") {
        let targetValue = "";
        if (rule.ruleType === "품목명") {
          targetValue = itemName;
        } else if (rule.ruleType === "품목코드" && itemCode) {
          targetValue = itemCode;
        }

        if (!targetValue) continue;

        let matched = false;
        switch (rule.matchingType) {
          case "startsWith":
            matched = targetValue.startsWith(rule.conditionValue);
            break;
          case "endsWith":
            matched = targetValue.endsWith(rule.conditionValue);
            break;
          case "contains":
            matched = targetValue.includes(rule.conditionValue);
            break;
          case "equals":
            matched = targetValue === rule.conditionValue;
            break;
        }

        if (matched) return process;
      }
    }
  }

  // 매칭되는 공정이 없으면 공정명으로 단순 매칭 시도
  // (예: 품목명에 "스크린"이 포함되면 "스크린" 공정 반환)
  for (const process of processes) {
    if (itemName.toLowerCase().includes(process.processName.toLowerCase())) {
      return process;
    }
  }

  return null;
}

// 공정별 작업지시 그룹 타입
interface ProcessWorkOrderGroup {
  process: Process;
  items: Array<{ itemName: string; itemCode?: string; quantity: number }>;
}

// 수주 품목들을 공정별로 그룹핑
function groupItemsByProcess(
  items: Array<{ itemName: string; itemCode?: string; quantity: number }>,
  processes: Process[]
): ProcessWorkOrderGroup[] {
  if (items.length === 0 || processes.length === 0) {
    return [];
  }

  // 공정별 품목 그룹 맵
  const processGroupMap = new Map<string, ProcessWorkOrderGroup>();
  // 매칭되지 않은 품목들
  const unmatchedItems: Array<{ itemName: string; itemCode?: string; quantity: number }> = [];

  for (const item of items) {
    const matchedProcess = matchItemToProcess(
      item.itemName,
      item.itemCode,
      processes
    );

    if (matchedProcess) {
      if (!processGroupMap.has(matchedProcess.id)) {
        processGroupMap.set(matchedProcess.id, {
          process: matchedProcess,
          items: [],
        });
      }
      processGroupMap.get(matchedProcess.id)!.items.push(item);
    } else {
      unmatchedItems.push(item);
    }
  }

  // 매칭되지 않은 품목이 있으면 "기타" 그룹 생성
  const groups = Array.from(processGroupMap.values());

  if (unmatchedItems.length > 0) {
    // 기타 품목용 가상 공정 생성
    groups.push({
      process: {
        id: "unmatched",
        processName: "기타",
        processCode: "ETC",
        status: "사용중",
        description: "",
        classificationRules: [],
        workSteps: [],
        createdAt: "",
        updatedAt: "",
      } as unknown as Process,
      items: unmatchedItems,
    });
  }

  return groups;
}

export default function ProductionOrderCreatePage() {
  const router = useRouter();
  const params = useParams();
  const orderId = params.id as string;
  const { isEnabled, tenantIndustry } = useModules();

  // 생산 모듈 비활성 시 접근 차단 (tenantIndustry 미설정 시 전부 허용)
  if (tenantIndustry && !isEnabled('production')) {
    return (
      <PageLayout>
        <div className="flex flex-col items-center justify-center min-h-[40vh]">
          <p className="text-muted-foreground">생산관리 모듈이 활성화되어 있지 않습니다.</p>
          <button
            className="mt-4 text-sm text-blue-600 hover:underline"
            onClick={() => router.push('/sales/order-management-sales')}
          >
            ← 수주 목록으로
          </button>
        </div>
      </PageLayout>
    );
  }

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [order, setOrder] = useState<Order | null>(null);
  const [processes, setProcesses] = useState<Process[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 우선순위 상태
  const [selectedPriority, setSelectedPriority] = useState<PriorityLevel>("normal");
  const [selectedAssignees, setSelectedAssignees] = useState<string[]>([]);
  const [assigneeNames, setAssigneeNames] = useState<string[]>([]);
  const [isAssigneeModalOpen, setIsAssigneeModalOpen] = useState(false);
  const [memo, setMemo] = useState("");

  // 성공 다이얼로그 상태
  const [showSuccessDialog, setShowSuccessDialog] = useState(false);
  const [generatedWorkOrders, setGeneratedWorkOrders] = useState<Array<{ workOrderNo: string; processName?: string }>>([]);

  // 수주 데이터, 공정 목록 로드
  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      // 수주 정보, 공정 목록을 병렬로 로드
      const [orderResult, processResult] = await Promise.all([
        getOrderById(orderId),
        getProcessList({ status: "사용중" }),
      ]);

      if (orderResult.success && orderResult.data) {
        setOrder(orderResult.data);
      } else {
        setError(orderResult.error || "수주 정보 조회에 실패했습니다.");
      }

      if (processResult.success && processResult.data) {
        setProcesses(processResult.data.items);
      }
    } catch {
      setError("서버 오류가 발생했습니다.");
    } finally {
      setLoading(false);
    }
  }, [orderId]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

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

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

  const handleConfirm = async () => {
    if (!order) return;

    // 담당자 필수 검증
    if (selectedAssignees.length === 0) {
      setError("담당자를 선택해주세요.");
      return;
    }

    setIsSubmitting(true);
    setError(null);
    try {
      // 공정별 품목 그룹핑 (processIds 추출을 위해)
      const groups = groupItemsByProcess(
        (order.items || []).map((item) => ({
          itemName: item.itemName,
          itemCode: item.itemCode,
          quantity: item.quantity,
        })),
        processes
      );

      // 모든 매칭된 공정 ID 추출 (공정별로 각각 작업지시 생성)
      const matchedGroups = groups.filter((g) => g.process.id !== "unmatched");
      const allProcessIds = matchedGroups
        .map((g) => parseInt(g.process.id, 10))
        .filter((id) => !isNaN(id));

      // 담당자 ID 배열 변환 (string[] → number[])
      const assigneeIds = selectedAssignees
        .map(id => parseInt(id, 10))
        .filter(id => !isNaN(id));

      const productionData: CreateProductionOrderData = {
        priority: selectedPriority,
        assigneeIds: assigneeIds.length > 0 ? assigneeIds : undefined,
        memo: memo || undefined,
        processIds: allProcessIds.length > 0 ? allProcessIds : undefined,
      };

      const result = await createProductionOrder(orderId, productionData);

      if (result.success && result.data) {
        // 다중 작업지시 응답 처리
        const workOrders = result.data.workOrders || (result.data.workOrder ? [result.data.workOrder] : []);
        setGeneratedWorkOrders(
          workOrders.map((wo: { workOrderNo: string; process?: { processName: string } }) => ({
            workOrderNo: wo.workOrderNo,
            processName: wo.process?.processName,
          }))
        );
        setShowSuccessDialog(true);
      } else {
        setError(result.error || "생산지시 생성에 실패했습니다.");
      }
    } catch {
      setError("서버 오류가 발생했습니다.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleSuccessDialogClose = () => {
    setShowSuccessDialog(false);
    // 수주 상세 페이지로 이동 (상태가 변경되었으므로)
    router.push(`/ko/sales/order-management-sales/${orderId}?mode=view`);
  };

  // 선택된 우선순위 설정 가져오기
  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 (error && !order) {
    return (
      <PageLayout>
        <div className="text-center py-12">
          <AlertCircle className="h-12 w-12 mx-auto mb-4 text-red-500" />
          <p className="text-muted-foreground">{error}</p>
          <Button variant="outline" onClick={handleCancel} className="mt-4">
            <ArrowLeft className="h-4 w-4 mr-2" />
            돌아가기
          </Button>
        </div>
      </PageLayout>
    );
  }

  if (!order) {
    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 allGroups = groupItemsByProcess(
    (order.items || []).map((item) => ({
      itemName: item.itemName,
      itemCode: item.itemCode,
      quantity: item.quantity,
    })),
    processes
  );

  // 공정 매칭된 그룹과 기타(미분류) 그룹 분리
  const processGroups = allGroups.filter((g) => g.process.id !== "unmatched");
  const unmatchedGroup = allGroups.find((g) => g.process.id === "unmatched");

  // 작업지시 수 = 공정 매칭된 그룹 수만 (기타 제외)
  const workOrderCount = processGroups.length;

  // order.items에서 스크린 품목 상세 데이터 변환
  const screenItems: ScreenItemDetail[] = (order.items || []).map((item, index) => ({
    no: (item as unknown as { serialNo?: number }).serialNo || index + 1,
    itemName: item.itemName,
    specification: item.specification || "-",
    quantity: item.quantity,
    unit: item.unit || "EA",
    unitPrice: item.unitPrice,
    supplyAmount: item.supplyAmount,
    taxAmount: item.taxAmount,
    totalAmount: item.totalAmount,
  }));

  // Order에서 UI에 표시할 데이터 변환
  const orderInfo = {
    orderNumber: order.lotNumber,
    client: order.client,
    siteName: order.siteName,
    dueDate: order.expectedShipDate || "-",
    itemCount: order.itemCount,
    creditGrade: "B (관리)", // API에서 제공하지 않아 기본값 사용
    status: STATUS_LABELS[order.status] || order.status,
    amount: order.amount,
  };

  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>
        }
      />

      {/* 에러 메시지 표시 */}
      {error && order && (
        <div className="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
          <AlertCircle className="h-5 w-5 text-red-500 flex-shrink-0 mt-0.5" />
          <div>
            <p className="text-sm font-medium text-red-800">생산지시 생성 실패</p>
            <p className="text-sm text-red-600 mt-1">{error}</p>
          </div>
        </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>
                <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>
              <Label className="text-sm font-medium flex items-center gap-2 mb-2">
                <User className="h-4 w-4" />
                담당자 (다중선택 가능) <span className="text-red-500">*</span>
              </Label>
              <div
                onClick={() => setIsAssigneeModalOpen(true)}
                className={cn(
                  "flex min-h-10 w-full md:w-[400px] cursor-pointer items-center rounded-md border bg-white px-3 py-2 text-sm ring-offset-background hover:bg-accent/50",
                  selectedAssignees.length === 0 ? "border-red-300" : "border-input"
                )}
              >
                {assigneeNames.length > 0 ? (
                  <span>{assigneeNames.join(', ')}</span>
                ) : (
                  <span className="text-muted-foreground">담당자를 선택하세요 (팀/개인)</span>
                )}
              </div>
              {selectedAssignees.length === 0 && (
                <p className="text-xs text-red-500 mt-1">담당자는 필수 선택 항목입니다.</p>
              )}
            </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">
              {processGroups.length > 0 ? (
                processGroups.map((group, groupIdx) => (
                  <div
                    key={group.process.id}
                    className="border rounded-lg p-4 bg-blue-50/50 border-blue-200"
                  >
                    <div className="flex items-center justify-between mb-3">
                      <BadgeSm className="bg-blue-100 text-blue-700 border-blue-200">
                        {group.process.processName}
                      </BadgeSm>
                      <span className="font-mono text-sm font-medium">
                        {order.lotNumber}-{String(groupIdx + 1).padStart(2, "0")}
                      </span>
                    </div>
                    <div className="mb-3">
                      <p className="text-sm text-muted-foreground">품목 수</p>
                      <p className="font-medium">{group.items.length}건</p>
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground mb-2">공정 순서</p>
                      <div className="flex flex-wrap gap-2">
                        {group.process.workSteps.length > 0 ? (
                          group.process.workSteps.map((step, idx) => (
                            <BadgeSm
                              key={idx}
                              className="bg-gray-50 text-gray-600 border-gray-200"
                            >
                              {idx + 1}. {step}
                            </BadgeSm>
                          ))
                        ) : (
                          <span className="text-sm text-muted-foreground">
                            공정관리에서 세부 작업단계를 등록해 주세요.
                          </span>
                        )}
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div className="border rounded-lg p-4 bg-gray-50/50 border-gray-200">
                  <div className="text-center py-4">
                    <p className="text-sm text-muted-foreground">
                      매칭되는 공정이 없습니다. 공정관리에서 분류규칙을 등록해 주세요.
                    </p>
                  </div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 기타 품목 (공정 미매칭) */}
        {unmatchedGroup && unmatchedGroup.items.length > 0 && (
          <Card>
            <CardHeader className="pb-3">
              <CardTitle className="text-base flex items-center gap-2">
                기타 품목
                <BadgeSm className="bg-gray-100 text-gray-600 border-gray-200">
                  {unmatchedGroup.items.length}건
                </BadgeSm>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-sm text-muted-foreground mb-3">
                공정에 매칭되지 않은 품목입니다. 출하 시 별도로 준비해 주세요.
              </p>
              <ul className="space-y-1">
                {unmatchedGroup.items.map((item, idx) => {
                  const qty = Number(item.quantity);
                  return (
                    <li key={idx} className="text-sm flex items-center gap-2">
                      <span className="text-muted-foreground">•</span>
                      <span>{item.itemName}</span>
                      <span className="text-muted-foreground">
                        ({Number.isInteger(qty) ? qty : qty.toFixed(2).replace(/\.?0+$/, "")}개)
                      </span>
                    </li>
                  );
                })}
              </ul>
            </CardContent>
          </Card>
        )}

        {/* 자재 소요량 및 재고 현황 - 추후 BOM API 연동 예정 */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">자재 소요량 및 재고 현황</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-center py-8 text-muted-foreground">
              <p>BOM 데이터 연동 후 자재 소요량이 표시됩니다.</p>
              <p className="text-sm mt-1">(추후 제공 예정)</p>
            </div>
          </CardContent>
        </Card>

        {/* 스크린 품목 상세 */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">스크린 품목 상세 ({screenItems.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-center">수량</TableHead>
                    <TableHead className="text-center">단위</TableHead>
                    <TableHead className="text-right">단가</TableHead>
                    <TableHead className="text-right">공급가</TableHead>
                    <TableHead className="text-right">세액</TableHead>
                    <TableHead className="text-right">합계</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {screenItems.length > 0 ? (
                    screenItems.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.specification}</TableCell>
                        <TableCell className="text-center">{item.quantity}</TableCell>
                        <TableCell className="text-center">{item.unit}</TableCell>
                        <TableCell className="text-right">{formatAmount(item.unitPrice)}</TableCell>
                        <TableCell className="text-right">{formatAmount(item.supplyAmount)}</TableCell>
                        <TableCell className="text-right">{formatAmount(item.taxAmount)}</TableCell>
                        <TableCell className="text-right font-medium">{formatAmount(item.totalAmount)}</TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
                        품목 정보가 없습니다.
                      </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 - 추후 BOM API 연동 예정 */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base">절곡물 BOM</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-center py-8 text-muted-foreground">
              <p>BOM 데이터 연동 후 절곡물 정보가 표시됩니다.</p>
              <p className="text-sm mt-1">(가이드레일, 케이스, 하단 마감재 - 추후 제공 예정)</p>
            </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"
              )}>
                <span className="hidden md:inline">우선순위: </span>{selectedConfig.productionOrder}
              </BadgeSm>
            )}
          </div>
          <div className="flex items-center gap-1 md:gap-2">
            <Button variant="outline" onClick={handleBackToDetail} size="sm" className="md:size-default">
              <ArrowLeft className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">수주상세로</span>
            </Button>
            <Button onClick={handleConfirm} disabled={isSubmitting} size="sm" className="md:size-default">
              <BarChart3 className="h-4 w-4 md:mr-2" />
              <span className="hidden md:inline">생산지시 확정</span>
              <span className="ml-1">({screenItems.length})</span>
            </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" />
              작업지시가 {generatedWorkOrders.length}건 생성되었습니다.
            </AlertDialogTitle>
            <AlertDialogDescription asChild>
              <div className="space-y-4 pt-2">
                <div>
                  <p className="text-sm text-muted-foreground mb-2">생성된 작업지시:</p>
                  <ul className="space-y-1">
                    {generatedWorkOrders.map((wo, idx) => (
                      <li key={idx} className="flex items-center gap-2">
                        <span className="font-mono font-semibold text-foreground">{wo.workOrderNo}</span>
                        {wo.processName && (
                          <BadgeSm className="bg-blue-100 text-blue-700 border-blue-200">
                            {wo.processName}
                          </BadgeSm>
                        )}
                      </li>
                    ))}
                  </ul>
                </div>
                <p className="text-sm text-muted-foreground">
                  생산관리 &gt; 작업지시 관리에서 확인하세요.
                </p>
              </div>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogAction onClick={handleSuccessDialogClose}>
              확인
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 담당자 선택 모달 */}
      <AssigneeSelectModal
        open={isAssigneeModalOpen}
        onOpenChange={setIsAssigneeModalOpen}
        selectedIds={selectedAssignees}
        onSelect={(ids, names) => {
          setSelectedAssignees(ids);
          setAssigneeNames(names);
        }}
      />
    </PageLayout>
  );
}