import React, { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Dialog, DialogContent, DialogTitle, DialogDescription } from "./ui/dialog";
import { Label } from "./ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Textarea } from "./ui/textarea";
import { Checkbox } from "./ui/checkbox";
import { Search, Download, ChevronDown, Edit, X, FileText, PlayCircle, TrendingDown, TrendingUp, Eye } from "lucide-react";
import { WorkOrderSheet } from "./WorkOrderSheet";
import { WorkOrderWrite } from "./WorkOrderWrite";

export function ProductionManagement() {
  const [mainTab, setMainTab] = useState("screen");
  const [searchTerm, setSearchTerm] = useState("");
  const [showWorkOrderSheet, setShowWorkOrderSheet] = useState(false);
  const [selectedWorkOrder, setSelectedWorkOrder] = useState<any>(null);

  // Mock 대시보드 데이터
  const dashboardData = {
    workOrders: 34,
    inProgress: 18,
    materialLoss: 3.8,
    completionRate: 91.2
  };

  // 작업지시서 보기
  const handleViewWorkOrder = (workOrder: any) => {
    setSelectedWorkOrder(workOrder);
    setShowWorkOrderSheet(true);
  };

  // 작업지시서에서 뒤로가기
  const handleBackFromWorkOrder = () => {
    setShowWorkOrderSheet(false);
    setSelectedWorkOrder(null);
  };

  // 작업지시서가 열려있으면 작업지시서만 표시
  if (showWorkOrderSheet && selectedWorkOrder) {
    return <WorkOrderSheet workOrder={selectedWorkOrder} onBack={handleBackFromWorkOrder} />;
  }

  return (
    <div className="p-4 md:p-6 space-y-6">
      {/* 헤더 */}
      <div className="bg-card border border-border/20 rounded-xl p-6">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold text-foreground mb-2">생산관리</h1>
            <p className="text-muted-foreground">스크린, 슬랫, 절곡, 재고 생산 작업지시 및 공정진행 관리</p>
          </div>
          <div className="flex space-x-3">
            <Button variant="outline" className="border-border/50">
              <Download className="h-4 w-4 mr-2" />
              Excel 다운로드
            </Button>
          </div>
        </div>
      </div>

      {/* 생산 대시보드 */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="border-0 shadow-sm hover:shadow-md transition-all duration-300">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs sm:text-sm font-medium text-muted-foreground">작업지시</CardTitle>
            <div className="w-8 h-8 sm:w-10 sm:h-10 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg flex items-center justify-center">
              <FileText className="h-4 w-4 sm:h-5 sm:w-5 text-white" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-lg sm:text-2xl font-bold">{dashboardData.workOrders}건</div>
            <p className="text-xs text-muted-foreground mt-1">
              이번달 작업지시
            </p>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-sm hover:shadow-md transition-all duration-300">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs sm:text-sm font-medium text-muted-foreground">진행중</CardTitle>
            <div className="w-8 h-8 sm:w-10 sm:h-10 bg-gradient-to-br from-orange-500 to-orange-600 rounded-lg flex items-center justify-center">
              <PlayCircle className="h-4 w-4 sm:h-5 sm:w-5 text-white" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-lg sm:text-2xl font-bold">{dashboardData.inProgress}건</div>
            <p className="text-xs text-muted-foreground mt-1">
              현재 생산중
            </p>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-sm hover:shadow-md transition-all duration-300">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs sm:text-sm font-medium text-muted-foreground">자재 LOSS</CardTitle>
            <div className="w-8 h-8 sm:w-10 sm:h-10 bg-gradient-to-br from-red-500 to-red-600 rounded-lg flex items-center justify-center">
              <TrendingDown className="h-4 w-4 sm:h-5 sm:w-5 text-white" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-lg sm:text-2xl font-bold">{dashboardData.materialLoss}%</div>
            <p className="text-xs text-muted-foreground mt-1">
              이번달 자재손실률
            </p>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-sm hover:shadow-md transition-all duration-300">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs sm:text-sm font-medium text-muted-foreground">완료율</CardTitle>
            <div className="w-8 h-8 sm:w-10 sm:h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-lg flex items-center justify-center">
              <TrendingUp className="h-4 w-4 sm:h-5 sm:w-5 text-white" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-lg sm:text-2xl font-bold">{dashboardData.completionRate}%</div>
            <p className="text-xs text-muted-foreground mt-1">
              이번달 완료율
            </p>
          </CardContent>
        </Card>
      </div>

      {/* 메인 탭 */}
      <Card className="border-border/50">
        <CardContent className="p-6">
          <Tabs value={mainTab} onValueChange={setMainTab} className="w-full">
            <TabsList className="grid w-full grid-cols-2 md:grid-cols-4 mb-6 bg-muted/40 p-1 h-11 gap-1">
              <TabsTrigger 
                value="screen" 
                className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border data-[state=active]:border-primary/20 hover:bg-background/50 transition-colors"
              >
                스크린 생산
              </TabsTrigger>
              <TabsTrigger 
                value="slat" 
                className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border data-[state=active]:border-primary/20 hover:bg-background/50 transition-colors"
              >
                슬랫 생산
              </TabsTrigger>
              <TabsTrigger 
                value="bending" 
                className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border data-[state=active]:border-primary/20 hover:bg-background/50 transition-colors"
              >
                절곡 생산
              </TabsTrigger>
              <TabsTrigger 
                value="stock" 
                className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border data-[state=active]:border-primary/20 hover:bg-background/50 transition-colors"
              >
                재고 생산
              </TabsTrigger>
            </TabsList>

            {/* 스크린 생산 */}
            <TabsContent value="screen" className="mt-0">
              <ScreenProduction searchTerm={searchTerm} setSearchTerm={setSearchTerm} onViewWorkOrder={handleViewWorkOrder} />
            </TabsContent>

            {/* 슬랫 생산 */}
            <TabsContent value="slat" className="mt-0">
              <SlatProduction searchTerm={searchTerm} setSearchTerm={setSearchTerm} onViewWorkOrder={handleViewWorkOrder} />
            </TabsContent>

            {/* 절곡 생산 */}
            <TabsContent value="bending" className="mt-0">
              <BendingProduction searchTerm={searchTerm} setSearchTerm={setSearchTerm} onViewWorkOrder={handleViewWorkOrder} />
            </TabsContent>

            {/* 재고 생산 */}
            <TabsContent value="stock" className="mt-0">
              <StockProduction searchTerm={searchTerm} setSearchTerm={setSearchTerm} onViewWorkOrder={handleViewWorkOrder} />
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
    </div>
  );
}

// 스크린 생산 컴포넌트
interface ProductionProps {
  searchTerm: string;
  setSearchTerm: (term: string) => void;
  onViewWorkOrder: (workOrder: any) => void;
}

function ScreenProduction({ searchTerm, setSearchTerm, onViewWorkOrder }: ProductionProps) {
  const [subTab, setSubTab] = useState("workOrder");

  return (
    <div className="space-y-5">
      <Tabs value={subTab} onValueChange={setSubTab} className="w-full">
        <TabsList className="w-full md:w-auto bg-muted/40 p-1 h-10 gap-1">
          <TabsTrigger 
            value="workOrder" 
            className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border-b-2 data-[state=active]:border-primary hover:bg-background/50 transition-colors px-6"
          >
            작업지시현황
          </TabsTrigger>
          <TabsTrigger 
            value="processProgress" 
            className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border-b-2 data-[state=active]:border-primary hover:bg-background/50 transition-colors px-6"
          >
            공정진행현황
          </TabsTrigger>
        </TabsList>

        {/* 작업지시현황 */}
        <TabsContent value="workOrder" className="space-y-5 mt-5">
          <WorkOrderStatus searchTerm={searchTerm} setSearchTerm={setSearchTerm} onViewWorkOrder={onViewWorkOrder} />
        </TabsContent>

        {/* 공정진행현황 */}
        <TabsContent value="processProgress" className="space-y-5 mt-5">
          <ProcessProgress />
        </TabsContent>
      </Tabs>
    </div>
  );
}

// 작업지시현황 컴포넌트
function WorkOrderStatus({ searchTerm, setSearchTerm, onViewWorkOrder }: ProductionProps) {
  const [showWriteForm, setShowWriteForm] = useState(false);
  const [sortField, setSortField] = useState<string>("");
  const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
  
  const handleSaveWorkOrder = (data: any) => {
    console.log("저장된 작업지시서:", data);
    // 여기에 실제 저장 로직 추가
  };

  const handleSort = (field: string) => {
    if (sortField === field) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      setSortDirection("asc");
    }
  };

  // 작업지시 데이터
  const workOrderData = [
    {
      no: 13,
      workPriority: 0,
      orderDate: "2025-07-25",
      buyer: "명보에스티",
      siteName: "일산 동국대병원 3층",
      productName: "KSS01",
      quantity: 10,
      requestDate: "2025-08-01",
      status: "대기"
    },
    {
      no: 12,
      workPriority: 0,
      orderDate: "2025-07-29",
      buyer: "명보에스티",
      siteName: "일산 동국대병원 2층",
      productName: "KSS01",
      quantity: 10,
      requestDate: "2025-08-01",
      status: "대기"
    },
    {
      no: 11,
      workPriority: 1,
      orderDate: "2025-07-31",
      buyer: "이에스티",
      siteName: "용인 기흥",
      productName: "KSS02",
      quantity: 2,
      requestDate: "2025-08-03",
      status: "작업중"
    },
    {
      no: 10,
      workPriority: 2,
      orderDate: "2025-06-24",
      buyer: "대성산업",
      siteName: "한덕중학교",
      productName: "KSS02",
      quantity: 9,
      requestDate: "2025-08-03",
      status: "작업중"
    },
    {
      no: 9,
      workPriority: 3,
      orderDate: "2025-07-14",
      buyer: "이엘도어",
      siteName: "파우아디움 2층",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-03",
      status: "작업중"
    },
    {
      no: 8,
      workPriority: 4,
      orderDate: "2025-07-26",
      buyer: "주일기업",
      siteName: "여의도IFC 1층",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-05",
      status: "작업중"
    },
    {
      no: 7,
      workPriority: 5,
      orderDate: "2025-08-01",
      buyer: "명보에스티",
      siteName: "일산 동국대병원 1층",
      productName: "KSS01",
      quantity: 20,
      requestDate: "2025-08-05",
      status: "작업취소"
    },
    {
      no: 6,
      workPriority: 6,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "여의도IFC 2층",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-05",
      status: "검수"
    },
    {
      no: 5,
      workPriority: 7,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "여의도IFC 3층",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-05",
      status: "검수"
    },
    {
      no: 4,
      workPriority: null,
      orderDate: "2025-08-01",
      buyer: "이엘도어",
      siteName: "파우아디움 1층",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-07",
      status: "완료"
    },
    {
      no: 3,
      workPriority: null,
      orderDate: "2025-08-03",
      buyer: "한국특수",
      siteName: "인천영종물류창고",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-07",
      status: "완료"
    },
    {
      no: 2,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "평택",
      productName: "KSS02",
      quantity: 1,
      requestDate: "2025-08-10",
      status: "완료"
    },
    {
      no: 1,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "장수",
      productName: "KSS02",
      quantity: 2,
      requestDate: "2025-08-10",
      status: "완료"
    }
  ];

  const getStatusBadge = (status: string) => {
    const statusConfig: Record<string, { bg: string; text: string; border: string }> = {
      "대기": { bg: "bg-gray-100 dark:bg-gray-800", text: "text-gray-700 dark:text-gray-300", border: "border-gray-300 dark:border-gray-600" },
      "작업중": { bg: "bg-blue-100 dark:bg-blue-900", text: "text-blue-700 dark:text-blue-300", border: "border-blue-300 dark:border-blue-600" },
      "작업취소": { bg: "bg-red-100 dark:bg-red-900", text: "text-red-700 dark:text-red-300", border: "border-red-300 dark:border-red-600" },
      "검수": { bg: "bg-yellow-100 dark:bg-yellow-900", text: "text-yellow-700 dark:text-yellow-300", border: "border-yellow-300 dark:border-yellow-600" },
      "완료": { bg: "bg-green-100 dark:bg-green-900", text: "text-green-700 dark:text-green-300", border: "border-green-300 dark:border-green-600" }
    };
    const config = statusConfig[status] || { bg: "bg-gray-100 dark:bg-gray-800", text: "text-gray-700 dark:text-gray-300", border: "border-gray-300" };
    return <Badge className={`${config.bg} ${config.text} border ${config.border} font-medium px-2.5 py-0.5`}>{status}</Badge>;
  };

  const handleRowClick = (item: any) => {
    onViewWorkOrder(item);
  };

  // 소팅 적용
  const sortedData = [...workOrderData].sort((a, b) => {
    if (!sortField) return 0;
    
    let aValue = a[sortField as keyof typeof a];
    let bValue = b[sortField as keyof typeof b];
    
    // null 처리
    if (aValue === null) aValue = "";
    if (bValue === null) bValue = "";
    
    // 숫자 비교
    if (typeof aValue === "number" && typeof bValue === "number") {
      return sortDirection === "asc" ? aValue - bValue : bValue - aValue;
    }
    
    // 문자열 비교
    const aStr = String(aValue).toLowerCase();
    const bStr = String(bValue).toLowerCase();
    
    if (sortDirection === "asc") {
      return aStr > bStr ? 1 : -1;
    } else {
      return aStr < bStr ? 1 : -1;
    }
  });

  // 작성 페이지 표시
  if (showWriteForm) {
    return (
      <WorkOrderWrite 
        onBack={() => setShowWriteForm(false)} 
        onSave={handleSaveWorkOrder}
      />
    );
  }

  return (
    <div className="space-y-5">
      {/* 검색 및 버튼 */}
      <Card className="border-border/50 bg-card/50">
        <CardContent className="p-4">
          <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="고객사, 현장명, 제품명으로 검색..."
                className="pl-10 bg-background"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <div className="flex gap-2 flex-wrap sm:flex-nowrap">
              <Button 
                onClick={() => setShowWriteForm(true)}
                className="bg-green-600 hover:bg-green-700 flex-1 sm:flex-none"
              >
                <Edit className="h-4 w-4 mr-2" />
                작업지시서 작성
              </Button>
              <Button 
                onClick={() => workOrderData.length > 0 && handleRowClick(workOrderData[0])}
                variant="outline"
                className="border-blue-600 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-950 flex-1 sm:flex-none"
              >
                <Eye className="h-4 w-4 mr-2" />
                미리보기
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 데스크톱 테이블 */}
      <Card className="hidden md:block border-border/50">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="bg-muted/30 hover:bg-muted/30 border-b-2 border-border">
                <TableHead className="text-center w-[60px] font-semibold">No.</TableHead>
                <TableHead className="text-center w-[100px]">
                  <button 
                    onClick={() => handleSort("workPriority")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">작업순위</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "workPriority" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center w-[120px]">
                  <button 
                    onClick={() => handleSort("orderDate")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">수주계약일</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "orderDate" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center w-[150px]">
                  <button 
                    onClick={() => handleSort("buyer")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">고객사</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "buyer" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center">
                  <button 
                    onClick={() => handleSort("siteName")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">설치현장</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "siteName" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center w-[120px]">
                  <button 
                    onClick={() => handleSort("productName")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">제품명</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "productName" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center w-[80px] font-semibold">수량</TableHead>
                <TableHead className="text-center w-[120px]">
                  <button 
                    onClick={() => handleSort("requestDate")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">출고요청일</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "requestDate" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center w-[100px] font-semibold">상태</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {sortedData.map((item, index) => (
                <TableRow 
                  key={item.no} 
                  className={`hover:bg-muted/50 cursor-pointer transition-colors ${index % 2 === 0 ? "bg-background" : "bg-muted/10"}`}
                  onClick={() => handleRowClick(item)}
                >
                <TableCell className="text-center font-medium">{item.no}</TableCell>
                <TableCell className="text-center">
                  {item.workPriority !== null ? (
                    <div className="inline-flex items-center justify-center px-2.5 py-1 rounded-md bg-primary/10 text-primary font-semibold">
                      {item.workPriority}
                    </div>
                  ) : (
                    <span className="text-muted-foreground">-</span>
                  )}
                </TableCell>
                <TableCell className="text-center">{item.orderDate}</TableCell>
                <TableCell className="text-center font-medium">{item.buyer}</TableCell>
                <TableCell className="text-center">{item.siteName}</TableCell>
                <TableCell className="text-center font-semibold text-primary">{item.productName}</TableCell>
                <TableCell className="text-center">{item.quantity}</TableCell>
                <TableCell className="text-center">{item.requestDate}</TableCell>
                <TableCell className="text-center">{getStatusBadge(item.status)}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
        </div>
      </Card>

      {/* 모바일 카드 */}
      <div className="md:hidden space-y-3">
        {sortedData.map((item) => (
          <Card 
            key={item.no} 
            className="cursor-pointer hover:border-primary/50 transition-all hover:shadow-md"
            onClick={() => handleRowClick(item)}
          >
            <CardContent className="p-4 space-y-3">
              <div className="flex items-start justify-between">
                <div className="space-y-1 flex-1">
                  <div className="flex items-center gap-2">
                    <span className="text-xs text-muted-foreground">No. {item.no}</span>
                    {item.workPriority !== null && (
                      <div className="inline-flex items-center justify-center px-2 py-0.5 rounded-md bg-primary/10 text-primary text-xs font-semibold">
                        순위 {item.workPriority}
                      </div>
                    )}
                  </div>
                  <div className="font-semibold text-base">{item.buyer}</div>
                  <div className="text-sm text-muted-foreground">{item.siteName}</div>
                </div>
                {getStatusBadge(item.status)}
              </div>

              <div className="grid grid-cols-2 gap-3 pt-2 border-t border-border/50">
                <div>
                  <div className="text-xs text-muted-foreground mb-1">제품명</div>
                  <div className="font-semibold text-primary">{item.productName}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground mb-1">수량</div>
                  <div className="font-medium">{item.quantity} EA</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground mb-1">수주계약일</div>
                  <div className="text-sm">{item.orderDate}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground mb-1">출고요청일</div>
                  <div className="text-sm">{item.requestDate}</div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}

// 작업지시서 모달
interface WorkOrderSheetModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  workOrder: any;
}

function WorkOrderSheetModal({ open, onOpenChange, workOrder }: WorkOrderSheetModalProps) {
  const [worker1, setWorker1] = useState("");
  const [worker2, setWorker2] = useState("");
  const [worker3, setWorker3] = useState("");

  // 작업자 목록
  const workers = ["김동실", "영준서", "유영수", "배진석"];

  // 재고현황 및 자재부위 데이터
  const materialData = [
    {
      no: 1,
      category: "FSS-07",
      type: "철리커",
      productName: "6960",
      sizeWidth: "3050",
      sizeHeight: "",
      quantity: "",
      lotNo: ""
    },
    {
      no: 2,
      category: "1",
      type: "FSS-02",
      productName: "철리커",
      sizeWidth: "3500",
      sizeHeight: "2000",
      quantity: "",
      lotNo: ""
    },
    {
      no: 3,
      category: "",
      type: "",
      productName: "",
      sizeWidth: "",
      sizeHeight: "",
      quantity: "",
      lotNo: ""
    }
  ];

  // 하단 목록 데이터
  const historyData = [
    {
      no: 4,
      date: "2025-08-03",
      instruction: "제작지시문",
      buyer: "과학고 3동",
      site: "KSS02",
      quantity: "2",
      requestDate: "2025-08-10",
      status: "대기"
    },
    {
      no: 3,
      date: "2025-08-04",
      instruction: "제작지시문",
      buyer: "과학고 4동",
      site: "KSS02",
      quantity: "1",
      requestDate: "2025-08-10",
      status: "대기"
    },
    {
      no: 2,
      date: "2025-08-04",
      instruction: "명보에스티",
      buyer: "평택",
      site: "KSS02",
      quantity: "1",
      requestDate: "2025-08-10",
      status: "대기"
    },
    {
      no: 1,
      date: "2025-08-04",
      instruction: "명보에스티",
      buyer: "장수",
      site: "KSS02",
      quantity: "2",
      requestDate: "2025-08-10",
      status: ""
    }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] h-[95vh] p-0 flex flex-col gap-0">
        <DialogHeader className="sr-only">
          <DialogTitle>스크린 작업지시서</DialogTitle>
          <DialogDescription>
            작업지시서 상세 정보 및 작업자 배치
          </DialogDescription>
        </DialogHeader>
        {/* 헤더 */}
        <div className="flex-shrink-0 flex items-center justify-between p-4 md:p-6 border-b bg-muted/30">
          <h2 className="text-lg md:text-xl font-semibold">스크린 작업지시서</h2>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => onOpenChange(false)}
          >
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* 컨텐츠 */}
        <div className="flex-1 overflow-y-auto">
          <div className="p-4 md:p-6 space-y-6">
            {/* 작업 기본정보 */}
            <Card className="border-l-4 border-l-red-500">
              <CardHeader className="pb-3">
                <div className="flex items-center gap-2">
                  <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                    1
                  </div>
                  <CardTitle className="text-base md:text-lg">▶ 작업 기본정보</CardTitle>
                </div>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  {/* 1행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">수주계약일</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">발주처</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">협성일</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">세분류</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" readOnly />
                  </div>

                  {/* 2행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">출고요청일</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">배송방식</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" readOnly />
                  </div>
                  <div className="space-y-1 lg:col-span-2">
                    <Label className="text-xs text-muted-foreground">비고</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" />
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 두 개의 섹션을 좌우 배치 (데스크톱) / 상하 배치 (모바일) */}
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
              {/* 왼쪽: 재고현황 및 자재부위 */}
              <div className="lg:col-span-8">
                <Card className="border-l-4 border-l-red-500">
                  <CardHeader className="pb-3">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                          2
                        </div>
                        <CardTitle className="text-base md:text-lg">▶ 재고현황 및 자재부위</CardTitle>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                          3
                        </div>
                        <Button variant="ghost" size="sm" className="h-8 text-xs">
                          <Edit className="h-3 w-3 mr-1" />
                          로트번호 업그레이션
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    {/* 데스크톱 테이블 */}
                    <div className="hidden md:block overflow-x-auto">
                      <Table>
                        <TableHeader>
                          <TableRow className="bg-muted/50">
                            <TableHead className="text-center w-[50px] text-xs">외관<br/>품목<br/>순서</TableHead>
                            <TableHead className="text-center w-[60px] text-xs">층</TableHead>
                            <TableHead className="text-center w-[80px] text-xs">부호</TableHead>
                            <TableHead className="text-center w-[100px] text-xs">품목명</TableHead>
                            <TableHead className="text-center text-xs" colSpan={2}>제작사이즈</TableHead>
                            <TableHead className="text-center w-[70px] text-xs">수량</TableHead>
                            <TableHead className="text-center w-[120px] text-xs">입고 LOT NO.</TableHead>
                          </TableRow>
                          <TableRow className="bg-muted/50">
                            <TableHead className="text-center" colSpan={4}></TableHead>
                            <TableHead className="text-center text-xs">가로</TableHead>
                            <TableHead className="text-center text-xs">세로</TableHead>
                            <TableHead className="text-center" colSpan={2}></TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {materialData.map((item) => (
                            <TableRow key={item.no}>
                              <TableCell className="text-center text-xs">{item.no}</TableCell>
                              <TableCell className="text-center text-xs">{item.category}</TableCell>
                              <TableCell className="text-center text-xs">{item.type}</TableCell>
                              <TableCell className="text-center text-xs">{item.productName}</TableCell>
                              <TableCell className="text-center text-xs">{item.sizeWidth}</TableCell>
                              <TableCell className="text-center text-xs">{item.sizeHeight}</TableCell>
                              <TableCell className="text-center text-xs">{item.quantity}</TableCell>
                              <TableCell className="text-center">
                                {item.no === 2 ? (
                                  <div className="text-xs text-red-600">로트번호</div>
                                ) : (
                                  <div className="text-xs">{item.lotNo}</div>
                                )}
                              </TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>

                    {/* 모바일 카드 */}
                    <div className="md:hidden space-y-2">
                      {materialData.map((item) => (
                        <Card key={item.no} className="border">
                          <CardContent className="p-3 space-y-2 text-xs">
                            <div className="flex justify-between items-start">
                              <div className="font-semibold">No. {item.no}</div>
                              {item.no === 2 && (
                                <Badge variant="destructive" className="text-xs">로트번호</Badge>
                              )}
                            </div>
                            <div className="grid grid-cols-2 gap-2">
                              <div><span className="text-muted-foreground">층:</span> {item.category}</div>
                              <div><span className="text-muted-foreground">부호:</span> {item.type}</div>
                              <div><span className="text-muted-foreground">품목:</span> {item.productName}</div>
                              <div><span className="text-muted-foreground">수량:</span> {item.quantity}</div>
                              <div><span className="text-muted-foreground">가로:</span> {item.sizeWidth}</div>
                              <div><span className="text-muted-foreground">세로:</span> {item.sizeHeight}</div>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  </CardContent>
                </Card>

                {/* 하단 목록 테이블 */}
                <Card className="mt-4">
                  <CardContent className="p-4">
                    <div className="overflow-x-auto">
                      <Table>
                        <TableHeader>
                          <TableRow className="bg-muted/50">
                            <TableHead className="text-center text-xs">No</TableHead>
                            <TableHead className="text-center text-xs">날짜</TableHead>
                            <TableHead className="text-center text-xs">제작지시문</TableHead>
                            <TableHead className="text-center text-xs">발주처</TableHead>
                            <TableHead className="text-center text-xs">현장명</TableHead>
                            <TableHead className="text-center text-xs">수량</TableHead>
                            <TableHead className="text-center text-xs">출고요청일</TableHead>
                            <TableHead className="text-center text-xs">상태</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody>
                          {historyData.map((item) => (
                            <TableRow key={item.no}>
                              <TableCell className="text-center text-xs">{item.no}</TableCell>
                              <TableCell className="text-center text-xs">{item.date}</TableCell>
                              <TableCell className="text-center text-xs">{item.instruction}</TableCell>
                              <TableCell className="text-center text-xs">{item.buyer}</TableCell>
                              <TableCell className="text-center text-xs">{item.site}</TableCell>
                              <TableCell className="text-center text-xs">{item.quantity}</TableCell>
                              <TableCell className="text-center text-xs">{item.requestDate}</TableCell>
                              <TableCell className="text-center text-xs">{item.status}</TableCell>
                            </TableRow>
                          ))}
                        </TableBody>
                      </Table>
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* 오른쪽: 작업자 배치 + 우선 작업순위 */}
              <div className="lg:col-span-4 space-y-4">
                {/* 작업자 배치 */}
                <Card className="border-l-4 border-l-primary">
                  <CardHeader className="pb-3">
                    <div className="flex items-center gap-2">
                      <CardTitle className="text-base md:text-lg">▶ 작업자 배치</CardTitle>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="space-y-2">
                      <Label className="text-xs">작업자1</Label>
                      <Select value={worker1} onValueChange={setWorker1}>
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue placeholder="선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {workers.map((worker) => (
                            <SelectItem key={worker} value={worker} className="text-sm">
                              {worker}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label className="text-xs">작업자2</Label>
                      <Select value={worker2} onValueChange={setWorker2}>
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue placeholder="선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {workers.map((worker) => (
                            <SelectItem key={worker} value={worker} className="text-sm">
                              {worker}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label className="text-xs">작업자3</Label>
                      <Select value={worker3} onValueChange={setWorker3}>
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue placeholder="선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {workers.map((worker) => (
                            <SelectItem key={worker} value={worker} className="text-sm">
                              {worker}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="grid grid-cols-2 gap-2 pt-2">
                      <div className="space-y-2">
                        <Label className="text-xs">현재순</Label>
                        <Select>
                          <SelectTrigger className="h-8 text-sm">
                            <SelectValue placeholder="0" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="0">0</SelectItem>
                            <SelectItem value="1">1</SelectItem>
                            <SelectItem value="2">2</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="space-y-2">
                        <Label className="text-xs">실정순위</Label>
                        <Select>
                          <SelectTrigger className="h-8 text-sm">
                            <SelectValue placeholder="선택" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="1">1</SelectItem>
                            <SelectItem value="2">2</SelectItem>
                            <SelectItem value="3">3</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  </CardContent>
                </Card>

                {/* 우선 작업순위 */}
                <Card className="border-l-4 border-l-red-500">
                  <CardHeader className="pb-3">
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                        5
                      </div>
                      <CardTitle className="text-base md:text-lg">▶ 우선 작업순위</CardTitle>
                    </div>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      <div className="space-y-1">
                        <Label className="text-xs text-muted-foreground">대비실</Label>
                        <Input className="h-8 text-sm" readOnly />
                      </div>
                      <div className="space-y-1">
                        <Label className="text-xs text-muted-foreground">출목명</Label>
                        <Badge variant="outline" className="w-full h-8 flex items-center justify-start text-xs">
                          로트번호
                        </Badge>
                      </div>
                      <div className="space-y-1">
                        <Label className="text-xs text-muted-foreground">업고 LOT NO.</Label>
                        <Input className="h-8 text-sm" readOnly />
                      </div>
                      <div className="space-y-1">
                        <Label className="text-xs text-muted-foreground">내역실</Label>
                        <div className="border rounded-md p-2 min-h-[60px] text-xs text-muted-foreground bg-muted/20">
                          
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>
          </div>
        </div>

        {/* 하단 버튼 */}
        <div className="flex-shrink-0 p-3 md:p-4 border-t bg-background">
          <div className="flex flex-col sm:flex-row justify-end gap-2">
            <Button variant="default" className="bg-blue-600 hover:bg-blue-700 h-9">
              저장
            </Button>
            <Button variant="outline" className="h-9" onClick={() => onOpenChange(false)}>
              취소
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 공정진행현황 컴포넌트
function ProcessProgress() {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedProcess, setSelectedProcess] = useState<any>(null);
  const [showProcessDetailModal, setShowProcessDetailModal] = useState(false);

  // 공정진행 데이터
  const processProgressData = [
    {
      no: 13,
      workPriority: 0,
      orderDate: "2025-07-25",
      buyer: "명보에스티",
      siteName: "일산 동국대병원 3층",
      productName: "KSS01",
      quantity: 10,
      requestDate: "2025-08-01",
      processStatus: "대기"
    },
    {
      no: 12,
      workPriority: 0,
      orderDate: "2025-07-29",
      buyer: "명보에스티",
      siteName: "일산 동국대병원 2층",
      productName: "KSS01",
      quantity: 10,
      requestDate: "2025-08-01",
      processStatus: "대기"
    },
    {
      no: 11,
      workPriority: 1,
      orderDate: "2025-07-31",
      buyer: "이에스티",
      siteName: "용인 기흥",
      productName: "KSS02",
      quantity: 2,
      requestDate: "2025-08-03",
      processStatus: "포장"
    },
    {
      no: 10,
      workPriority: 2,
      orderDate: "2025-06-24",
      buyer: "대성산업",
      siteName: "한덕중학교",
      productName: "KSS02",
      quantity: 9,
      requestDate: "2025-08-03",
      processStatus: "중간검사"
    },
    {
      no: 9,
      workPriority: 3,
      orderDate: "2025-07-14",
      buyer: "이엘도어",
      siteName: "파우아티움 2층",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-03",
      processStatus: "미싱",
      highlight: true
    },
    {
      no: 8,
      workPriority: 4,
      orderDate: "2025-07-26",
      buyer: "주일기업",
      siteName: "여의도IFC 1층",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-05",
      processStatus: "절단"
    },
    {
      no: 7,
      workPriority: 5,
      orderDate: "2025-08-01",
      buyer: "명보에스티",
      siteName: "일산 동국대병원 1층",
      productName: "KSS01",
      quantity: 20,
      requestDate: "2025-08-05",
      processStatus: "작업취소"
    },
    {
      no: 6,
      workPriority: 6,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "여의도IFC 2층",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-05",
      processStatus: "준비"
    },
    {
      no: 5,
      workPriority: 7,
      orderDate: "2025-08-01",
      buyer: "주�����기업",
      siteName: "여의도IFC 3층",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-05",
      processStatus: "준비"
    },
    {
      no: 4,
      workPriority: null,
      orderDate: "2025-08-01",
      buyer: "이엘도어",
      siteName: "파우아티움 1층",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-07",
      processStatus: "출고대기"
    },
    {
      no: 3,
      workPriority: null,
      orderDate: "2025-08-03",
      buyer: "한국특수",
      siteName: "인천영종물류창고",
      productName: "KSS01",
      quantity: 5,
      requestDate: "2025-08-07",
      processStatus: "출고대기"
    },
    {
      no: 2,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "평택",
      productName: "KSS02",
      quantity: 1,
      requestDate: "2025-08-10",
      processStatus: "출고대기"
    },
    {
      no: 1,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "장수",
      productName: "KSS02",
      quantity: 2,
      requestDate: "2025-08-10",
      processStatus: "출고대기"
    }
  ];

  const getProcessStatusBadge = (status: string) => {
    const statusConfig: Record<string, { bg: string; text: string }> = {
      "대기": { bg: "bg-gray-100", text: "text-gray-700" },
      "절단": { bg: "bg-blue-100", text: "text-blue-700" },
      "미싱": { bg: "bg-purple-100", text: "text-purple-700" },
      "중간검사": { bg: "bg-orange-100", text: "text-orange-700" },
      "포장": { bg: "bg-green-100", text: "text-green-700" },
      "준비": { bg: "bg-cyan-100", text: "text-cyan-700" },
      "작업취소": { bg: "bg-red-100", text: "text-red-700" },
      "출고대기": { bg: "bg-yellow-100", text: "text-yellow-700" }
    };
    const config = statusConfig[status] || { bg: "bg-gray-100", text: "text-gray-700" };
    return <Badge className={`${config.bg} ${config.text} border-0`}>{status}</Badge>;
  };

  const handleRowClick = (item: any) => {
    setSelectedProcess(item);
    setShowProcessDetailModal(true);
  };

  return (
    <div className="space-y-4">
      {/* 검색 */}
      <div className="flex items-center gap-4">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search..."
            className="pl-10"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
      </div>

      {/* 데스크톱 테이블 */}
      <div className="hidden md:block overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow className="bg-muted/50">
              <TableHead className="text-center w-[60px]">
                <div className="text-xs">No.5<br/>TOP</div>
              </TableHead>
              <TableHead className="text-center w-[80px]">
                <div className="flex items-center justify-center gap-1">
                  <span className="text-xs">작업<br/>순위</span>
                  <ChevronDown className="h-3 w-3" />
                </div>
              </TableHead>
              <TableHead className="text-center w-[120px]">
                <div className="flex items-center justify-center gap-1">
                  <span className="text-xs">수주<br/>계약일</span>
                  <ChevronDown className="h-3 w-3" />
                </div>
              </TableHead>
              <TableHead className="text-center">
                <span className="text-xs">발주처</span>
              </TableHead>
              <TableHead className="text-center">
                <span className="text-xs">현장명</span>
              </TableHead>
              <TableHead className="text-center w-[100px]">
                <span className="text-xs">제품명</span>
              </TableHead>
              <TableHead className="text-center w-[80px]">
                <span className="text-xs">수량<br/>(톱)</span>
              </TableHead>
              <TableHead className="text-center w-[120px]">
                <div className="flex items-center justify-center gap-1">
                  <span className="text-xs">출고요청일</span>
                  <ChevronDown className="h-3 w-3" />
                </div>
              </TableHead>
              <TableHead className="text-center w-[100px]">
                <div className="flex items-center justify-center gap-1">
                  <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                    1
                  </div>
                  <span className="text-xs">공정지시<br/>현황</span>
                  <ChevronDown className="h-3 w-3" />
                </div>
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {processProgressData.map((item) => (
              <TableRow 
                key={item.no} 
                className={`hover:bg-muted/30 cursor-pointer ${item.highlight ? 'bg-orange-50' : ''}`}
                onClick={() => handleRowClick(item)}
              >
                <TableCell className="text-center text-sm">{item.no}</TableCell>
                <TableCell className="text-center text-sm">{item.workPriority ?? ""}</TableCell>
                <TableCell className="text-center text-sm">{item.orderDate}</TableCell>
                <TableCell className="text-center text-sm">{item.buyer}</TableCell>
                <TableCell className="text-center text-sm">{item.siteName}</TableCell>
                <TableCell className="text-center text-sm font-semibold">{item.productName}</TableCell>
                <TableCell className="text-center text-sm">{item.quantity}</TableCell>
                <TableCell className="text-center text-sm">{item.requestDate}</TableCell>
                <TableCell className="text-center">{getProcessStatusBadge(item.processStatus)}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* 모바일 카드 */}
      <div className="md:hidden space-y-3">
        {processProgressData.map((item) => (
          <Card 
            key={item.no} 
            className={`cursor-pointer ${item.highlight ? 'border-orange-300 bg-orange-50' : ''}`}
            onClick={() => handleRowClick(item)}
          >
            <CardContent className="p-4 space-y-3">
              <div className="flex items-start justify-between">
                <div className="space-y-1">
                  <div className="text-xs text-muted-foreground">No. {item.no}</div>
                  <div className="font-semibold">{item.buyer}</div>
                  <div className="text-sm text-muted-foreground">{item.siteName}</div>
                </div>
                {getProcessStatusBadge(item.processStatus)}
              </div>

              <div className="grid grid-cols-2 gap-2 text-sm">
                <div>
                  <span className="text-muted-foreground">작업순위: </span>
                  <span className="font-medium">{item.workPriority ?? "-"}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">제품: </span>
                  <span className="font-semibold">{item.productName}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">수량: </span>
                  <span className="font-medium">{item.quantity}톱</span>
                </div>
                <div>
                  <span className="text-muted-foreground">계약일: </span>
                  <span className="font-medium">{item.orderDate}</span>
                </div>
              </div>

              <div className="text-xs text-muted-foreground">
                출고요청일: {item.requestDate}
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 공정진행상세정보 모달 */}
      {selectedProcess && (
        <ProcessDetailModal
          open={showProcessDetailModal}
          onOpenChange={setShowProcessDetailModal}
          processData={selectedProcess}
        />
      )}
    </div>
  );
}

// 공정진행상세정보 모달
interface ProcessDetailModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  processData: any;
}

function ProcessDetailModal({ open, onOpenChange, processData }: ProcessDetailModalProps) {
  const [showInspectionReport, setShowInspectionReport] = useState(false);

  // 작업 상세 데이터
  const workDetailData = [
    {
      no: 1,
      materialCode: "250729-01",
      floor: "1",
      symbol: "FSS-01",
      materialName: "실리카",
      sizeWidth: "6960",
      sizeHeight: "3050",
      cutSpec: "1220*2장\n800*1장",
      cutting: true,
      sewing: false,
      inspection: false,
      packaging: false,
      status: "완곡"
    },
    {
      no: 2,
      materialCode: "250729-01",
      floor: "1",
      symbol: "FSS-02",
      materialName: "실리카",
      sizeWidth: "5160",
      sizeHeight: "3050",
      cutSpec: "1220*2장\n800*1장",
      cutting: false,
      sewing: false,
      inspection: false,
      packaging: false,
      status: "농화색"
    },
    {
      no: 3,
      materialCode: "",
      floor: "",
      symbol: "",
      materialName: "",
      sizeWidth: "",
      sizeHeight: "",
      cutSpec: "",
      cutting: false,
      sewing: false,
      inspection: false,
      packaging: false,
      status: ""
    },
    {
      no: 4,
      materialCode: "",
      floor: "",
      symbol: "",
      materialName: "",
      sizeWidth: "",
      sizeHeight: "",
      cutSpec: "",
      cutting: false,
      sewing: false,
      inspection: false,
      packaging: false,
      status: ""
    }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] h-[95vh] p-0 flex flex-col gap-0">
        <DialogHeader className="sr-only">
          <DialogTitle>스크린 직업상세정보</DialogTitle>
          <DialogDescription>
            공정진행 상세 정보 및 작업 상태
          </DialogDescription>
        </DialogHeader>
        {/* 헤더 */}
        <div className="flex-shrink-0 flex items-center justify-between p-4 md:p-6 border-b bg-muted/30">
          <h2 className="text-lg md:text-xl font-semibold">스크린 직업상세정보</h2>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => onOpenChange(false)}
          >
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* 컨텐츠 */}
        <div className="flex-1 overflow-y-auto">
          <div className="p-4 md:p-6 space-y-6">
            {/* 작업 기본정보 */}
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-base md:text-lg">▶ 작업 기본정보</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  {/* 1행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">수주계약일</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">발주처</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">현장명</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">제품명</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>

                  {/* 2행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">출고요청일</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">배송방식</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1 lg:col-span-2">
                    <Label className="text-xs text-muted-foreground">비고</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" />
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 작업 상세정보 */}
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-base md:text-lg">▶ 작업 상세정보</CardTitle>
              </CardHeader>
              <CardContent>
                {/* 데스크톱 테이블 */}
                <div className="hidden md:block overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-muted/50">
                        <TableHead className="text-center w-[60px] text-xs" rowSpan={2}>
                          일련<br/>번호
                        </TableHead>
                        <TableHead className="text-center w-[100px] text-xs" rowSpan={2}>
                          원자재코드
                        </TableHead>
                        <TableHead className="text-center w-[60px] text-xs" rowSpan={2}>
                          층
                        </TableHead>
                        <TableHead className="text-center w-[80px] text-xs" rowSpan={2}>
                          부호
                        </TableHead>
                        <TableHead className="text-center w-[100px] text-xs" rowSpan={2}>
                          자재명
                        </TableHead>
                        <TableHead className="text-center text-xs" colSpan={2}>
                          <div className="flex items-center justify-center gap-1">
                            제작사이즈
                            <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                              1
                            </div>
                          </div>
                        </TableHead>
                        <TableHead className="text-center w-[100px] text-xs" rowSpan={2}>
                          제단사양
                        </TableHead>
                        <TableHead className="text-center text-xs" colSpan={4}>
                          <div className="flex items-center justify-center gap-1">
                            <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                              2
                            </div>
                            공정 별 CHECK
                            <input type="checkbox" className="ml-2 w-4 h-4" />
                          </div>
                        </TableHead>
                        <TableHead className="text-center w-[80px] text-xs" rowSpan={2}>
                          
                        </TableHead>
                      </TableRow>
                      <TableRow className="bg-muted/50">
                        <TableHead className="text-center text-xs">가로</TableHead>
                        <TableHead className="text-center text-xs">세로</TableHead>
                        <TableHead className="text-center text-xs">
                          <div className="flex items-center justify-center gap-1">
                            <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                              3
                            </div>
                            절단
                          </div>
                        </TableHead>
                        <TableHead className="text-center text-xs">
                          <div className="flex items-center justify-center gap-1">
                            <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                              4
                            </div>
                            미싱
                          </div>
                        </TableHead>
                        <TableHead className="text-center text-xs">중간검사</TableHead>
                        <TableHead className="text-center text-xs">포장</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {workDetailData.map((item) => (
                        <TableRow key={item.no}>
                          <TableCell className="text-center text-xs">{item.no}</TableCell>
                          <TableCell className="text-center text-xs font-mono">{item.materialCode}</TableCell>
                          <TableCell className="text-center text-xs">{item.floor}</TableCell>
                          <TableCell className="text-center text-xs">{item.symbol}</TableCell>
                          <TableCell className="text-center text-xs">{item.materialName}</TableCell>
                          <TableCell className="text-center text-xs">{item.sizeWidth}</TableCell>
                          <TableCell className="text-center text-xs">{item.sizeHeight}</TableCell>
                          <TableCell className="text-center text-xs whitespace-pre-line">{item.cutSpec}</TableCell>
                          <TableCell className="text-center">
                            <input 
                              type="checkbox" 
                              className="w-4 h-4" 
                              checked={item.cutting}
                              readOnly
                            />
                          </TableCell>
                          <TableCell className="text-center">
                            <input 
                              type="checkbox" 
                              className="w-4 h-4" 
                              checked={item.sewing}
                              readOnly
                            />
                          </TableCell>
                          <TableCell className="text-center">
                            <input 
                              type="checkbox" 
                              className="w-4 h-4 cursor-pointer" 
                              checked={item.inspection}
                              onClick={(e) => {
                                e.stopPropagation();
                                setShowInspectionReport(true);
                              }}
                              readOnly
                            />
                          </TableCell>
                          <TableCell className="text-center">
                            <input 
                              type="checkbox" 
                              className="w-4 h-4" 
                              checked={item.packaging}
                              readOnly
                            />
                          </TableCell>
                          <TableCell className="text-center">
                            {item.status && (
                              <Badge 
                                variant="outline" 
                                className={item.status === "완곡" ? "text-yellow-700 border-yellow-300 bg-yellow-50" : ""}
                              >
                                {item.status}
                              </Badge>
                            )}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>

                {/* 모바일 카드 */}
                <div className="md:hidden space-y-3">
                  {workDetailData.filter(item => item.materialCode).map((item) => (
                    <Card key={item.no} className="border">
                      <CardContent className="p-3 space-y-3">
                        <div className="flex items-start justify-between">
                          <div className="space-y-1">
                            <div className="text-xs text-muted-foreground">일련번호: {item.no}</div>
                            <div className="font-mono text-sm">{item.materialCode}</div>
                            <div className="text-xs">
                              <span className="text-muted-foreground">층: </span>{item.floor} / 
                              <span className="text-muted-foreground"> 부호: </span>{item.symbol}
                            </div>
                          </div>
                          {item.status && (
                            <Badge variant="outline" className="text-xs">
                              {item.status}
                            </Badge>
                          )}
                        </div>

                        <div className="grid grid-cols-2 gap-2 text-xs">
                          <div>
                            <span className="text-muted-foreground">자재명:</span> {item.materialName}
                          </div>
                          <div>
                            <span className="text-muted-foreground">가로:</span> {item.sizeWidth}
                          </div>
                          <div>
                            <span className="text-muted-foreground">세로:</span> {item.sizeHeight}
                          </div>
                          <div>
                            <span className="text-muted-foreground">제단사양:</span> {item.cutSpec.split('\n')[0]}
                          </div>
                        </div>

                        <div className="flex items-center gap-4 text-xs pt-2 border-t">
                          <label className="flex items-center gap-1">
                            <input type="checkbox" checked={item.cutting} readOnly className="w-3 h-3" />
                            절단
                          </label>
                          <label className="flex items-center gap-1">
                            <input type="checkbox" checked={item.sewing} readOnly className="w-3 h-3" />
                            미싱
                          </label>
                          <label className="flex items-center gap-1 cursor-pointer">
                            <input 
                              type="checkbox" 
                              checked={item.inspection} 
                              readOnly 
                              className="w-3 h-3 cursor-pointer"
                              onClick={(e) => {
                                e.stopPropagation();
                                setShowInspectionReport(true);
                              }}
                            />
                            중간검사
                          </label>
                          <label className="flex items-center gap-1">
                            <input type="checkbox" checked={item.packaging} readOnly className="w-3 h-3" />
                            포장
                          </label>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        {/* 하단 버튼 */}
        <div className="flex-shrink-0 p-3 md:p-4 border-t bg-background">
          <div className="flex flex-col sm:flex-row justify-end gap-2">
            <Button variant="outline" className="h-9">
              수정
            </Button>
            <Button variant="default" className="bg-blue-600 hover:bg-blue-700 h-9">
              저장
            </Button>
            <Button variant="outline" className="h-9">
              작업일지PDF
            </Button>
          </div>
        </div>
      </DialogContent>

      {/* 중간검사 성적서 모달 */}
      <InspectionReportModal
        open={showInspectionReport}
        onOpenChange={setShowInspectionReport}
      />
    </Dialog>
  );
}

// 슬랫 생산 컴포넌트
function SlatProduction({ searchTerm, setSearchTerm, onViewWorkOrder }: ProductionProps) {
  const [subTab, setSubTab] = useState("workOrder");

  return (
    <div className="space-y-5">
      <Tabs value={subTab} onValueChange={setSubTab} className="w-full">
        <TabsList className="w-full md:w-auto bg-muted/40 p-1 h-10 gap-1">
          <TabsTrigger 
            value="workOrder" 
            className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border-b-2 data-[state=active]:border-primary hover:bg-background/50 transition-colors px-6"
          >
            작업지시현황
          </TabsTrigger>
          <TabsTrigger 
            value="processProgress" 
            className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border-b-2 data-[state=active]:border-primary hover:bg-background/50 transition-colors px-6"
          >
            공정진행현황
          </TabsTrigger>
        </TabsList>

        <TabsContent value="workOrder" className="space-y-5 mt-5">
          <SlatWorkOrder searchTerm={searchTerm} setSearchTerm={setSearchTerm} onViewWorkOrder={onViewWorkOrder} />
        </TabsContent>

        <TabsContent value="processProgress" className="space-y-5 mt-5">
          <SlatProcessProgress searchTerm={searchTerm} setSearchTerm={setSearchTerm} />
        </TabsContent>
      </Tabs>
    </div>
  );
}

// 슬랫 공정진행현황 컴포넌트
function SlatProcessProgress({ searchTerm, setSearchTerm }: ProductionProps) {
  const [selectedProcess, setSelectedProcess] = useState<any>(null);
  const [showProcessDetailModal, setShowProcessDetailModal] = useState(false);

  // 슬랫 공정진행 데이터
  const slatProcessProgressData = [
    {
      no: 10,
      workPriority: 0,
      orderDate: "2025-06-24",
      buyer: "한빛에스티",
      siteName: "반포3지구",
      productName: "KQTS01",
      quantity: 9,
      requestDate: "2025-08-03",
      processStatus: "대기"
    },
    {
      no: 9,
      workPriority: 0,
      orderDate: "2025-07-14",
      buyer: "이엘도어",
      siteName: "상도동주상복합(1층)",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-03",
      processStatus: "대기"
    },
    {
      no: 8,
      workPriority: 1,
      orderDate: "2025-07-26",
      buyer: "주일기업",
      siteName: "과천지식정보원장",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-05",
      processStatus: "포장"
    },
    {
      no: 7,
      workPriority: 2,
      orderDate: "2025-08-01",
      buyer: "명보에스티",
      siteName: "오창큐브",
      productName: "KQTS01",
      quantity: 20,
      requestDate: "2025-08-05",
      processStatus: "작업취소"
    },
    {
      no: 6,
      workPriority: 3,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "번월공단",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-05",
      processStatus: "중간검사"
    },
    {
      no: 5,
      workPriority: 4,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "이천종리 우미린1단지",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-05",
      processStatus: "절단"
    },
    {
      no: 4,
      workPriority: 5,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "이천종리 우미린2단지",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-07",
      processStatus: "준비"
    },
    {
      no: 3,
      workPriority: 6,
      orderDate: "2025-08-03",
      buyer: "한국특수",
      siteName: "인천영명용항청고",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-07",
      processStatus: "준비"
    },
    {
      no: 2,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "상도동주상복합(2층)",
      productName: "KQTS01",
      quantity: 1,
      requestDate: "2025-08-10",
      processStatus: "출고대기"
    },
    {
      no: 1,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "상도동주상복합(3층)",
      productName: "KQTS01",
      quantity: 2,
      requestDate: "2025-08-10",
      processStatus: "출고대기"
    }
  ];

  const getStatusConfig = (status: string) => {
    const configs: Record<string, { bg: string; text: string }> = {
      "대기": { bg: "bg-gray-100", text: "text-gray-700" },
      "준비": { bg: "bg-yellow-100", text: "text-yellow-700" },
      "절단": { bg: "bg-orange-100", text: "text-orange-700" },
      "중간검사": { bg: "bg-blue-100", text: "text-blue-700" },
      "포장": { bg: "bg-purple-100", text: "text-purple-700" },
      "작업취소": { bg: "bg-red-100", text: "text-red-700" },
      "출고대기": { bg: "bg-green-100", text: "text-green-700" }
    };
    return configs[status] || configs["대기"];
  };

  const handleRowClick = (item: any) => {
    setSelectedProcess(item);
    setShowProcessDetailModal(true);
  };

  return (
    <div className="space-y-4">
      {/* 검색 */}
      <div className="flex items-center gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
          <Input
            placeholder="검색..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-9 h-9"
          />
        </div>
      </div>

      {/* 데스크톱 테이블 */}
      <div className="hidden md:block border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow className="bg-muted/50">
              <TableHead className="text-center w-[60px]">No.</TableHead>
              <TableHead className="text-center w-[100px]">
                작업순위
                <ChevronDown className="inline h-3 w-3 ml-1" />
              </TableHead>
              <TableHead className="text-center w-[120px]">
                수주<br/>계약일
                <ChevronDown className="inline h-3 w-3 ml-1" />
              </TableHead>
              <TableHead className="text-center w-[120px]">발주처</TableHead>
              <TableHead className="text-center">현장명</TableHead>
              <TableHead className="text-center w-[100px]">제품명</TableHead>
              <TableHead className="text-center w-[80px]">수량<br/>(통)</TableHead>
              <TableHead className="text-center w-[120px]">
                출고요청일
                <ChevronDown className="inline h-3 w-3 ml-1" />
              </TableHead>
              <TableHead className="text-center w-[120px]">
                <div className="flex items-center justify-center gap-1">
                  <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                    1
                  </div>
                  공정진행<br/>현황
                  <ChevronDown className="inline h-3 w-3 ml-1" />
                </div>
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {slatProcessProgressData.map((item) => (
              <TableRow 
                key={item.no}
                className="hover:bg-muted/30 cursor-pointer"
                onClick={() => handleRowClick(item)}
              >
                <TableCell className="text-center text-sm">{item.no}</TableCell>
                <TableCell className="text-center text-sm">
                  {item.workPriority !== null ? item.workPriority : '-'}
                </TableCell>
                <TableCell className="text-center text-sm">{item.orderDate}</TableCell>
                <TableCell className="text-center text-sm">{item.buyer}</TableCell>
                <TableCell className="text-center text-sm">{item.siteName}</TableCell>
                <TableCell className="text-center text-sm">{item.productName}</TableCell>
                <TableCell className="text-center text-sm">{item.quantity}</TableCell>
                <TableCell className="text-center text-sm">{item.requestDate}</TableCell>
                <TableCell className="text-center">
                  <Badge 
                    className={`${getStatusConfig(item.processStatus).bg} ${getStatusConfig(item.processStatus).text} border-0`}
                  >
                    {item.processStatus}
                  </Badge>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* 모바일 카드 */}
      <div className="md:hidden space-y-3">
        {slatProcessProgressData.map((item) => (
          <Card 
            key={item.no}
            className="cursor-pointer"
            onClick={() => handleRowClick(item)}
          >
            <CardContent className="p-4 space-y-3">
              <div className="flex items-start justify-between">
                <div className="space-y-1">
                  <div className="flex items-center gap-2">
                    <span className="text-xs text-muted-foreground">No. {item.no}</span>
                    {item.workPriority !== null && (
                      <Badge variant="outline" className="text-xs">
                        순위 {item.workPriority}
                      </Badge>
                    )}
                  </div>
                  <div className="font-semibold">{item.siteName}</div>
                  <div className="text-sm text-muted-foreground">{item.buyer}</div>
                </div>
                <Badge 
                  className={`${getStatusConfig(item.processStatus).bg} ${getStatusConfig(item.processStatus).text} border-0`}
                >
                  {item.processStatus}
                </Badge>
              </div>

              <div className="grid grid-cols-2 gap-2 text-sm">
                <div>
                  <span className="text-muted-foreground">제품: </span>
                  <span className="font-medium">{item.productName}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">수량: </span>
                  <span className="font-medium">{item.quantity}통</span>
                </div>
                <div className="col-span-2">
                  <span className="text-muted-foreground">계약일: </span>
                  <span className="font-medium">{item.orderDate}</span>
                </div>
              </div>

              <div className="text-xs text-muted-foreground">
                출고요청일: {item.requestDate}
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 슬랫 작업상세정보 모달 */}
      {selectedProcess && (
        <SlatProcessDetailModal
          open={showProcessDetailModal}
          onOpenChange={setShowProcessDetailModal}
          processData={selectedProcess}
        />
      )}
    </div>
  );
}

// 슬랫 작업상세정보 모달
interface SlatProcessDetailModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  processData: any;
}

function SlatProcessDetailModal({ open, onOpenChange, processData }: SlatProcessDetailModalProps) {
  const [showInspectionReport, setShowInspectionReport] = useState(false);

  // 작업 상세 데이터
  const workDetailData = [
    {
      no: 1,
      materialLot: "250729-01",
      floor: "1",
      symbol: "FST-01",
      materialName: "철구면 EGI 1.5ST",
      sizeWidth: "3610",
      sizeHeight: "4350",
      cutSpec: "61",
      cutting: true,
      inspection: true,
      packaging: false,
      status: "황적"
    },
    {
      no: 2,
      materialLot: "250729-01",
      floor: "1",
      symbol: "FST-02",
      materialName: "철구면 EGI 1.5ST",
      sizeWidth: "3610",
      sizeHeight: "4350",
      cutSpec: "61",
      cutting: true,
      inspection: true,
      packaging: false,
      status: "홍반석"
    },
    {
      no: 3,
      materialLot: "",
      floor: "",
      symbol: "",
      materialName: "",
      sizeWidth: "",
      sizeHeight: "",
      cutSpec: "",
      cutting: false,
      inspection: false,
      packaging: false,
      status: ""
    },
    {
      no: 4,
      materialLot: "",
      floor: "",
      symbol: "",
      materialName: "",
      sizeWidth: "",
      sizeHeight: "",
      cutSpec: "",
      cutting: false,
      inspection: false,
      packaging: false,
      status: ""
    }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] h-[95vh] p-0 flex flex-col gap-0">
        <DialogHeader className="sr-only">
          <DialogTitle>슬랫 작업상세정보</DialogTitle>
          <DialogDescription>
            슬랫 공정진행 상세 정보 및 작업 상태
          </DialogDescription>
        </DialogHeader>
        {/* 헤더 */}
        <div className="flex-shrink-0 flex items-center justify-between p-4 md:p-6 border-b bg-muted/30">
          <h2 className="text-lg md:text-xl font-semibold">슬랫 작업상세정보</h2>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => onOpenChange(false)}
          >
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* 컨텐츠 */}
        <div className="flex-1 overflow-y-auto">
          <div className="p-4 md:p-6 space-y-6">
            {/* 작업 기본정보 */}
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-base md:text-lg">▶ 작업 기본정보</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  {/* 1행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">수주계약일</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">발주처</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">현장명</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">제품명</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>

                  {/* 2행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">출고요청일</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">배송방식</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1 lg:col-span-2">
                    <Label className="text-xs text-muted-foreground">비고</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" />
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 작업 상세정보 */}
            <Card>
              <CardHeader className="pb-3">
                <CardTitle className="text-base md:text-lg">▶ 작업 상세정보</CardTitle>
              </CardHeader>
              <CardContent>
                {/* 데스크톱 테이블 */}
                <div className="hidden md:block overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-muted/50">
                        <TableHead className="text-center w-[60px] text-xs" rowSpan={2}>
                          일련<br/>번호
                        </TableHead>
                        <TableHead className="text-center w-[120px] text-xs" rowSpan={2}>
                          원자재로트
                        </TableHead>
                        <TableHead className="text-center w-[60px] text-xs" rowSpan={2}>
                          층
                        </TableHead>
                        <TableHead className="text-center w-[80px] text-xs" rowSpan={2}>
                          부호
                        </TableHead>
                        <TableHead className="text-center w-[150px] text-xs" rowSpan={2}>
                          자재명
                        </TableHead>
                        <TableHead className="text-center text-xs" colSpan={2}>
                          <div className="flex items-center justify-center gap-1">
                            제작사이즈
                            <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                              1
                            </div>
                          </div>
                        </TableHead>
                        <TableHead className="text-center w-[100px] text-xs" rowSpan={2}>
                          <div className="flex items-center justify-center gap-1">
                            <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                              3
                            </div>
                            제단사양<br/>(매)
                          </div>
                        </TableHead>
                        <TableHead className="text-center text-xs" colSpan={3}>
                          <div className="flex items-center justify-center gap-1">
                            <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                              2
                            </div>
                            공정 별 CHECK
                            <input type="checkbox" className="ml-2 w-4 h-4" />
                          </div>
                        </TableHead>
                        <TableHead className="text-center w-[80px] text-xs" rowSpan={2}>
                          
                        </TableHead>
                      </TableRow>
                      <TableRow className="bg-muted/50">
                        <TableHead className="text-center text-xs">가로</TableHead>
                        <TableHead className="text-center text-xs">세로</TableHead>
                        <TableHead className="text-center text-xs">절단</TableHead>
                        <TableHead className="text-center text-xs">
                          <div className="flex items-center justify-center gap-1">
                            <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                              4
                            </div>
                            중간검사
                          </div>
                        </TableHead>
                        <TableHead className="text-center text-xs">포장</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {workDetailData.map((item) => (
                        <TableRow key={item.no}>
                          <TableCell className="text-center text-xs">{item.no}</TableCell>
                          <TableCell className="text-center text-xs font-mono">{item.materialLot}</TableCell>
                          <TableCell className="text-center text-xs">{item.floor}</TableCell>
                          <TableCell className="text-center text-xs">{item.symbol}</TableCell>
                          <TableCell className="text-center text-xs">{item.materialName}</TableCell>
                          <TableCell className="text-center text-xs">{item.sizeWidth}</TableCell>
                          <TableCell className="text-center text-xs">{item.sizeHeight}</TableCell>
                          <TableCell className="text-center text-xs">{item.cutSpec}</TableCell>
                          <TableCell className="text-center">
                            <input 
                              type="checkbox" 
                              className="w-4 h-4" 
                              checked={item.cutting}
                              readOnly
                            />
                          </TableCell>
                          <TableCell className="text-center">
                            <input 
                              type="checkbox" 
                              className="w-4 h-4 cursor-pointer" 
                              checked={item.inspection}
                              onClick={(e) => {
                                e.stopPropagation();
                                setShowInspectionReport(true);
                              }}
                              readOnly
                            />
                          </TableCell>
                          <TableCell className="text-center">
                            <input 
                              type="checkbox" 
                              className="w-4 h-4" 
                              checked={item.packaging}
                              readOnly
                            />
                          </TableCell>
                          <TableCell className="text-center">
                            {item.status && (
                              <Badge 
                                variant="outline" 
                                className={item.status === "황적" ? "text-yellow-700 border-yellow-300 bg-yellow-50" : "text-red-700 border-red-300 bg-red-50"}
                              >
                                {item.status}
                              </Badge>
                            )}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>

                {/* 모바일 카드 */}
                <div className="md:hidden space-y-3">
                  {workDetailData.filter(item => item.materialLot).map((item) => (
                    <Card key={item.no} className="border">
                      <CardContent className="p-3 space-y-3">
                        <div className="flex items-start justify-between">
                          <div className="space-y-1">
                            <div className="text-xs text-muted-foreground">일련번호: {item.no}</div>
                            <div className="font-mono text-sm">{item.materialLot}</div>
                            <div className="text-xs">
                              <span className="text-muted-foreground">층: </span>{item.floor} / 
                              <span className="text-muted-foreground"> 부호: </span>{item.symbol}
                            </div>
                          </div>
                          {item.status && (
                            <Badge variant="outline" className="text-xs">
                              {item.status}
                            </Badge>
                          )}
                        </div>

                        <div className="grid grid-cols-2 gap-2 text-xs">
                          <div className="col-span-2">
                            <span className="text-muted-foreground">자재명:</span> {item.materialName}
                          </div>
                          <div>
                            <span className="text-muted-foreground">가로:</span> {item.sizeWidth}
                          </div>
                          <div>
                            <span className="text-muted-foreground">세로:</span> {item.sizeHeight}
                          </div>
                          <div>
                            <span className="text-muted-foreground">제단사양:</span> {item.cutSpec}매
                          </div>
                        </div>

                        <div className="flex items-center gap-4 text-xs pt-2 border-t">
                          <label className="flex items-center gap-1">
                            <input type="checkbox" checked={item.cutting} readOnly className="w-3 h-3" />
                            절단
                          </label>
                          <label className="flex items-center gap-1 cursor-pointer">
                            <input 
                              type="checkbox" 
                              checked={item.inspection} 
                              readOnly 
                              className="w-3 h-3 cursor-pointer"
                              onClick={(e) => {
                                e.stopPropagation();
                                setShowInspectionReport(true);
                              }}
                            />
                            중간검사
                          </label>
                          <label className="flex items-center gap-1">
                            <input type="checkbox" checked={item.packaging} readOnly className="w-3 h-3" />
                            포장
                          </label>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        {/* 하단 버튼 */}
        <div className="flex-shrink-0 p-3 md:p-4 border-t bg-background">
          <div className="flex flex-col sm:flex-row justify-end gap-2">
            <Button variant="outline" className="h-9">
              수정
            </Button>
            <Button variant="default" className="bg-blue-600 hover:bg-blue-700 h-9">
              저장
            </Button>
            <Button variant="outline" className="h-9">
              작업일지PDF
            </Button>
          </div>
        </div>
      </DialogContent>

      {/* 조인트바 중간검사 성적서 모달 */}
      <JointBarInspectionModal
        open={showInspectionReport}
        onOpenChange={setShowInspectionReport}
      />
    </Dialog>
  );
}

// 조인트바 중간검사 성적서 모달
interface JointBarInspectionModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

function JointBarInspectionModal({ open, onOpenChange }: JointBarInspectionModalProps) {
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] h-[95vh] p-0 flex flex-col gap-0">
        <DialogHeader className="sr-only">
          <DialogTitle>조인트바-중간 검사성적서</DialogTitle>
          <DialogDescription>조인트바 중간검사 성적서 및 품질 검사 결과</DialogDescription>
        </DialogHeader>
        {/* 헤더 */}
        <div className="flex-shrink-0 flex items-center justify-between p-4 border-b">
          <h2 className="text-lg md:text-xl font-semibold">조인트바-중간 검사성적서</h2>
          <Button variant="ghost" size="icon" onClick={() => onOpenChange(false)}>
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* 컨텐츠 */}
        <div className="flex-1 overflow-y-auto p-4 md:p-6">
          <div className="space-y-6 max-w-5xl mx-auto">
            <div className="border-2 border-black">
              {/* 타이틀 */}
              <div className="grid grid-cols-12 border-b-2 border-black">
                <div className="col-span-6 p-4">
                  <div className="text-2xl md:text-3xl font-bold text-blue-600">KJ</div>
                  <div className="text-xs">경동기업</div>
                </div>
                <div className="col-span-4 p-4 flex items-center justify-center border-l-2 border-black">
                  <h2 className="text-xl md:text-2xl font-bold">조인트바-중간 검사성적서</h2>
                </div>
                <div className="col-span-2 border-l-2 border-black">
                  <div className="flex items-center justify-center py-2">
                    <div className="w-8 h-8 rounded-full bg-red-500 text-white flex items-center justify-center font-bold">4</div>
                  </div>
                  <div className="grid grid-cols-3 border-t border-black text-xs">
                    <div className="p-1 text-center border-r border-black">작성</div>
                    <div className="p-1 text-center border-r border-black">검토</div>
                    <div className="p-1 text-center">승인</div>
                  </div>
                  <div className="grid grid-cols-3 border-t border-black h-10">
                    <div className="border-r border-black"></div>
                    <div className="border-r border-black"></div>
                    <div></div>
                  </div>
                  <div className="grid grid-cols-2 border-t border-black text-xs">
                    <div className="p-1 text-center border-r border-black">관리/승급</div>
                    <div className="p-1 text-center">색상</div>
                  </div>
                  <div className="grid grid-cols-2 border-t border-black text-xs h-6">
                    <div className="border-r border-black bg-blue-50 flex items-center justify-center">홍길</div>
                    <div></div>
                  </div>
                </div>
              </div>

              {/* 기본정보 ① */}
              <div className="border-b-2 border-black">
                <div className="flex items-center gap-2 p-2 bg-red-50">
                  <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">1</div>
                </div>
                <div className="grid grid-cols-12 text-xs md:text-sm">
                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">품명</div>
                  <div className="col-span-4 p-2 border-b border-r border-black">슬렌</div>
                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">제품 LOT NO</div>
                  <div className="col-span-4 p-2 border-b border-black text-blue-600 font-semibold">KD-TS-250717-02</div>

                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">규격</div>
                  <div className="col-span-4 p-2 border-b border-r border-black">EGI 1.5ST</div>
                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">로트크기</div>
                  <div className="col-span-4 p-2 border-b border-black">5 (EA)</div>

                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">발주처</div>
                  <div className="col-span-4 p-2 border-b border-r border-black">현지금속 주식회사</div>
                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">검사일자</div>
                  <div className="col-span-4 p-2 border-b border-black">연도-월-일</div>

                  <div className="col-span-2 p-2 bg-gray-100 border-r border-black text-center font-semibold">적용번</div>
                  <div className="col-span-4 p-2 border-r border-black bg-orange-100">인천 포대회원급</div>
                  <div className="col-span-2 p-2 bg-gray-100 border-r border-black text-center font-semibold">검사자</div>
                  <div className="col-span-4 p-2"></div>
                </div>
              </div>

              {/* 중간검사 표 ③ */}
              <div className="p-2">
                <div className="flex items-center gap-2 mb-2">
                  <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">3</div>
                  <div className="font-semibold">중간검사</div>
                </div>
                <div className="overflow-x-auto">
                  <table className="w-full border-2 border-black text-xs">
                    <thead>
                      <tr className="bg-blue-50">
                        <th className="border border-black p-1" rowSpan={3}>일반<br/>번호</th>
                        <th className="border border-black p-1" colSpan={2}>관리항목</th>
                        <th className="border border-black p-1" colSpan={8}>치수(mm)</th>
                        <th className="border border-black p-1" rowSpan={3}>판정<br/>(적/부)</th>
                      </tr>
                      <tr className="bg-blue-50">
                        <th className="border border-black p-1" rowSpan={2}>가공상태</th>
                        <th className="border border-black p-1" rowSpan={2}>조립상태</th>
                        <th className="border border-black p-1" colSpan={2}>① 눈이</th>
                        <th className="border border-black p-1" colSpan={2}>② 눈이</th>
                        <th className="border border-black p-1" colSpan={2}>③ 길이(폭대폭대폭)</th>
                        <th className="border border-black p-1" colSpan={2}>④ 간극</th>
                      </tr>
                      <tr className="bg-blue-50">
                        <th className="border border-black p-1">도면상수</th>
                        <th className="border border-black p-1">측정값</th>
                        <th className="border border-black p-1">도면상수</th>
                        <th className="border border-black p-1">측정값</th>
                        <th className="border border-black p-1">기준치</th>
                        <th className="border border-black p-1">측정값</th>
                        <th className="border border-black p-1">기준치</th>
                        <th className="border border-black p-1">측정값</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td className="border border-black p-1 text-center">1</td>
                        <td className="border border-black p-1">
                          <div className="flex gap-1 justify-center">
                            <label className="flex items-center gap-1 text-xs">
                              <input type="checkbox" className="w-3 h-3" /> 양호
                            </label>
                            <label className="flex items-center gap-1 text-xs">
                              <input type="checkbox" className="w-3 h-3" /> 불량
                            </label>
                          </div>
                        </td>
                        <td className="border border-black p-1">
                          <div className="flex gap-1 justify-center">
                            <label className="flex items-center gap-1 text-xs">
                              <input type="checkbox" className="w-3 h-3" /> 양호
                            </label>
                            <label className="flex items-center gap-1 text-xs">
                              <input type="checkbox" className="w-3 h-3" /> 불량
                            </label>
                          </div>
                        </td>
                        <td className="border border-black p-1 text-center text-blue-600 font-semibold">16.5 ± 1</td>
                        <td className="border border-black p-1"></td>
                        <td className="border border-black p-1 text-center text-blue-600 font-semibold">14.5 ± 1</td>
                        <td className="border border-black p-1"></td>
                        <td className="border border-black p-1 text-center text-blue-600 font-semibold">300 ± 4</td>
                        <td className="border border-black p-1"></td>
                        <td className="border border-black p-1 text-center text-blue-600 font-semibold">150 ± 4</td>
                        <td className="border border-black p-1"></td>
                        <td className="border border-black p-1 text-center"></td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                <div className="mt-4 border-2 border-black p-2">
                  <div className="text-xs font-semibold mb-2">[부적합 내용]</div>
                  <div className="min-h-[60px] bg-gray-50"></div>
                </div>
              </div>

              {/* 하단 */}
              <div className="grid grid-cols-2 border-t-2 border-black">
                <div className="p-2 border-r-2 border-black">
                  <div className="text-xs">KDQP-01-005</div>
                </div>
                <div className="p-2 flex items-center justify-end gap-4">
                  <div className="flex items-center gap-2">
                    <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">5</div>
                    <div className="text-sm font-semibold text-red-600">중합격</div>
                  </div>
                  <div className="border-2 border-red-500 px-8 py-4">
                    <div className="text-3xl font-bold text-red-600">불합격</div>
                  </div>
                  <div className="text-xs">(주)경동기업</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="flex-shrink-0 p-3 md:p-4 border-t bg-background">
          <div className="flex flex-col sm:flex-row justify-end gap-2">
            <Button variant="outline" className="h-9">수정</Button>
            <Button variant="default" className="bg-blue-600 hover:bg-blue-700 h-9">제출</Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 슬랫 작업지시현황 컴포넌트
interface SlatWorkOrderProps {
  searchTerm: string;
  setSearchTerm: (term: string) => void;
  onViewWorkOrder: (workOrder: any) => void;
}

function SlatWorkOrder({ searchTerm, setSearchTerm, onViewWorkOrder }: SlatWorkOrderProps) {
  const [showWriteForm, setShowWriteForm] = useState(false);
  
  const handleSaveWorkOrder = (data: any) => {
    console.log("저장된 슬랫 작업지시서:", data);
  };

  // 슬랫 작업지시 데���터
  const slatWorkOrderData = [
    {
      no: 10,
      workPriority: 0,
      orderDate: "2025-06-24",
      buyer: "한빛에스티",
      siteName: "반포3지구",
      productName: "KQTS01",
      quantity: 9,
      requestDate: "2025-08-03",
      workStatus: "대기"
    },
    {
      no: 9,
      workPriority: 0,
      orderDate: "2025-07-14",
      buyer: "이엘도어",
      siteName: "상도동주상복합(1층)",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-03",
      workStatus: "대기"
    },
    {
      no: 8,
      workPriority: 1,
      orderDate: "2025-07-26",
      buyer: "주일기업",
      siteName: "과천시청복현장",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-05",
      workStatus: "작업중"
    },
    {
      no: 7,
      workPriority: 2,
      orderDate: "2025-08-01",
      buyer: "명보에스티",
      siteName: "오창큐브",
      productName: "KQTS01",
      quantity: 20,
      requestDate: "2025-08-05",
      workStatus: "작업완료"
    },
    {
      no: 6,
      workPriority: 3,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "번월공단",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-05",
      workStatus: "작업중"
    },
    {
      no: 5,
      workPriority: 4,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "이천종리 우미린타지1",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-05",
      workStatus: "작업중"
    },
    {
      no: 4,
      workPriority: 5,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "이천종리 우미린2단지",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-07",
      workStatus: "작업중"
    },
    {
      no: 3,
      workPriority: 6,
      orderDate: "2025-08-03",
      buyer: "한국특수",
      siteName: "인천영명용항청고",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-07",
      workStatus: "작업중"
    },
    {
      no: 2,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "상도동주상복합(2층)",
      productName: "KQTS01",
      quantity: 1,
      requestDate: "2025-08-10",
      workStatus: "완료"
    },
    {
      no: 1,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "상도동주상복합(3층)",
      productName: "KQTS01",
      quantity: 2,
      requestDate: "2025-08-10",
      workStatus: "완료"
    }
  ];

  const getStatusConfig = (status: string) => {
    const configs: Record<string, { bg: string; text: string }> = {
      "대기": { bg: "bg-gray-100", text: "text-gray-700" },
      "작업중": { bg: "bg-orange-100", text: "text-orange-700" },
      "작업완료": { bg: "bg-blue-100", text: "text-blue-700" },
      "완료": { bg: "bg-green-100", text: "text-green-700" }
    };
    return configs[status] || configs["대기"];
  };

  const handleRowClick = (item: any) => {
    onViewWorkOrder(item);
  };

  // 작성 페이지 표시
  if (showWriteForm) {
    return (
      <WorkOrderWrite 
        onBack={() => setShowWriteForm(false)} 
        onSave={handleSaveWorkOrder}
      />
    );
  }

  return (
    <div className="space-y-5">
      {/* 검색 및 버튼 */}
      <Card className="border-border/50 bg-card/50">
        <CardContent className="p-4">
          <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="고객사, 현장명, 제품명으로 검색..."
                className="pl-10 bg-background"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <div className="flex gap-2 flex-wrap sm:flex-nowrap">
              <Button 
                onClick={() => setShowWriteForm(true)}
                className="bg-green-600 hover:bg-green-700 flex-1 sm:flex-none"
              >
                <Edit className="h-4 w-4 mr-2" />
                작업지시서 작성
              </Button>
              <Button 
                onClick={() => slatWorkOrderData.length > 0 && handleRowClick(slatWorkOrderData[0])}
                variant="outline"
                className="border-blue-600 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-950 flex-1 sm:flex-none"
              >
                <Eye className="h-4 w-4 mr-2" />
                미리보기
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 데스크톱 테이블 */}
      <Card className="hidden md:block border-border/50">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="bg-muted/30 hover:bg-muted/30 border-b-2 border-border">
                <TableHead className="text-center w-[60px] font-semibold">No.</TableHead>
                <TableHead className="text-center w-[100px] font-semibold">
                  작업순위
                  <ChevronDown className="inline h-3 w-3 ml-1" />
                </TableHead>
                <TableHead className="text-center w-[120px] font-semibold">
                  수주계약일
                  <ChevronDown className="inline h-3 w-3 ml-1" />
                </TableHead>
                <TableHead className="text-center w-[120px] font-semibold">발주처</TableHead>
                <TableHead className="text-center font-semibold">현장명</TableHead>
                <TableHead className="text-center w-[100px] font-semibold">제품명</TableHead>
                <TableHead className="text-center w-[80px] font-semibold">수량(통)</TableHead>
                <TableHead className="text-center w-[120px] font-semibold">
                  출고요청일
                  <ChevronDown className="inline h-3 w-3 ml-1" />
                </TableHead>
                <TableHead className="text-center w-[120px] font-semibold">
                  작업지시현황
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {slatWorkOrderData.map((item, index) => (
                <TableRow 
                  key={item.no}
                  className={`hover:bg-muted/50 cursor-pointer transition-colors ${index % 2 === 0 ? "bg-background" : "bg-muted/10"}`}
                  onClick={() => handleRowClick(item)}
                >
                  <TableCell className="text-center font-medium">{item.no}</TableCell>
                  <TableCell className="text-center">
                    {item.workPriority !== null ? (
                      <div className="inline-flex items-center justify-center px-2.5 py-1 rounded-md bg-primary/10 text-primary font-semibold">
                        {item.workPriority}
                      </div>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </TableCell>
                  <TableCell className="text-center">{item.orderDate}</TableCell>
                  <TableCell className="text-center font-medium">{item.buyer}</TableCell>
                  <TableCell className="text-center">{item.siteName}</TableCell>
                  <TableCell className="text-center font-semibold text-primary">{item.productName}</TableCell>
                  <TableCell className="text-center">{item.quantity}</TableCell>
                  <TableCell className="text-center">{item.requestDate}</TableCell>
                  <TableCell className="text-center">
                    <Badge 
                      className={`${getStatusConfig(item.workStatus).bg} ${getStatusConfig(item.workStatus).text} border font-medium px-2.5 py-0.5`}
                    >
                      {item.workStatus}
                    </Badge>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </Card>

      {/* 모바일 카드 */}
      <div className="md:hidden space-y-3">
        {slatWorkOrderData.map((item) => (
          <Card 
            key={item.no}
            className="cursor-pointer hover:border-primary/50 transition-all hover:shadow-md"
            onClick={() => handleRowClick(item)}
          >
            <CardContent className="p-4 space-y-3">
              <div className="flex items-start justify-between">
                <div className="space-y-1 flex-1">
                  <div className="flex items-center gap-2">
                    <span className="text-xs text-muted-foreground">No. {item.no}</span>
                    {item.workPriority !== null && (
                      <div className="inline-flex items-center justify-center px-2 py-0.5 rounded-md bg-primary/10 text-primary text-xs font-semibold">
                        순위 {item.workPriority}
                      </div>
                    )}
                  </div>
                  <div className="font-semibold text-base">{item.siteName}</div>
                  <div className="text-sm text-muted-foreground">{item.buyer}</div>
                </div>
                <Badge 
                  className={`${getStatusConfig(item.workStatus).bg} ${getStatusConfig(item.workStatus).text} border font-medium px-2.5 py-0.5`}
                >
                  {item.workStatus}
                </Badge>
              </div>

              <div className="grid grid-cols-2 gap-3 pt-2 border-t border-border/50">
                <div>
                  <div className="text-xs text-muted-foreground mb-1">제품명</div>
                  <div className="font-semibold text-primary">{item.productName}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground mb-1">수량</div>
                  <div className="font-medium">{item.quantity} 통</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground mb-1">수주계약일</div>
                  <div className="text-sm">{item.orderDate}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground mb-1">출고요청일</div>
                  <div className="text-sm">{item.requestDate}</div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

    </div>
  );
}

// 슬랫 작업지시서 모달
interface SlatWorkOrderModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  orderData: any;
}

function SlatWorkOrderModal({ open, onOpenChange, orderData }: SlatWorkOrderModalProps) {
  const [worker1, setWorker1] = useState("김동철");
  const [worker2, setWorker2] = useState("선택");
  const [worker3, setWorker3] = useState("선택");

  const workers = ["선택", "김동철", "김준성", "유영수", "배진석"];

  // 제고물건 데이터
  const materialsData = [
    {
      no: 1,
      floor: "1",
      symbol: "FSS-01",
      itemName: "실리카",
      sizeWidth: "696",
      sizeHeight: "3050",
      quantity: "47",
      lightType: "1",
      lotNo: "로트번호"
    },
    {
      no: 2,
      floor: "",
      symbol: "",
      itemName: "",
      sizeWidth: "",
      sizeHeight: "",
      quantity: "",
      lightType: "",
      lotNo: ""
    },
    {
      no: 3,
      floor: "",
      symbol: "",
      itemName: "",
      sizeWidth: "",
      sizeHeight: "",
      quantity: "",
      lightType: "",
      lotNo: ""
    },
    {
      no: 4,
      floor: "",
      symbol: "",
      itemName: "",
      sizeWidth: "",
      sizeHeight: "",
      quantity: "",
      lightType: "",
      lotNo: ""
    }
  ];

  // 조인트바 데이터
  const jointBarData = [
    {
      no: 1,
      itemType: "조인트바",
      quantity: "5",
      completedLotNo: "로트번호"
    }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] h-[95vh] p-0 flex flex-col gap-0">
        <DialogHeader className="sr-only">
          <DialogTitle>슬랫 작업지시서</DialogTitle>
          <DialogDescription>
            슬랫 생산 작업지시 상세 정보
          </DialogDescription>
        </DialogHeader>
        {/* 헤더 */}
        <div className="flex-shrink-0 flex items-center justify-between p-4 md:p-6 border-b bg-muted/30">
          <h2 className="text-lg md:text-xl font-semibold">슬랫 작업지시서</h2>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => onOpenChange(false)}
          >
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* 컨텐츠 */}
        <div className="flex-1 overflow-y-auto">
          <div className="p-4 md:p-6 space-y-6">
            {/* 작업 기본정보 */}
            <Card className="border-l-4 border-l-red-500">
              <CardHeader className="pb-3">
                <div className="flex items-center gap-2">
                  <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                    1
                  </div>
                  <CardTitle className="text-base md:text-lg">▶ 작업 기본정보</CardTitle>
                </div>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  {/* 1행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">수주계약일</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">발주처</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">현장명</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">제품명</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>

                  {/* 2행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">출고요청일</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">배송방식</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1 lg:col-span-2">
                    <Label className="text-xs text-muted-foreground">비고</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" />
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 메인 그리드 */}
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
              {/* 왼쪽: 제고물건 및 규격부위 */}
              <div className="lg:col-span-8 space-y-4">
                <Card className="border-l-4 border-l-red-500">
                  <CardHeader className="pb-3">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                          2
                        </div>
                        <CardTitle className="text-base md:text-lg">▶ 제고물건 및 규격부위</CardTitle>
                      </div>
                      <div className="flex items-center gap-2">
                        <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                          3
                        </div>
                        <Button variant="outline" size="sm" className="h-7 text-xs">
                          로트번호 업로드확용
                        </Button>
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent>
                    {/* 본문 */}
                    <div className="space-y-3">
                      <div className="text-sm font-semibold">본문</div>
                      
                      {/* 데스크톱 테이블 */}
                      <div className="hidden md:block overflow-x-auto">
                        <Table>
                          <TableHeader>
                            <TableRow className="bg-muted/50">
                              <TableHead className="text-center w-[60px] text-xs" rowSpan={2}>일련<br/>번호</TableHead>
                              <TableHead className="text-center w-[60px] text-xs" rowSpan={2}>층</TableHead>
                              <TableHead className="text-center w-[80px] text-xs" rowSpan={2}>부호</TableHead>
                              <TableHead className="text-center w-[100px] text-xs" rowSpan={2}>품목명</TableHead>
                              <TableHead className="text-center text-xs" colSpan={4}>
                                <div className="flex items-center justify-center gap-1">
                                  제작사이즈
                                  <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                                    4
                                  </div>
                                </div>
                              </TableHead>
                              <TableHead className="text-center w-[120px] text-xs" rowSpan={2}>입고 LOT NO.</TableHead>
                            </TableRow>
                            <TableRow className="bg-muted/50">
                              <TableHead className="text-center text-xs">가로</TableHead>
                              <TableHead className="text-center text-xs">세로</TableHead>
                              <TableHead className="text-center text-xs">예수</TableHead>
                              <TableHead className="text-center text-xs">발광</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {materialsData.map((item) => (
                              <TableRow key={item.no}>
                                <TableCell className="text-center text-xs">{item.no}</TableCell>
                                <TableCell className="text-center text-xs">{item.floor}</TableCell>
                                <TableCell className="text-center text-xs">{item.symbol}</TableCell>
                                <TableCell className="text-center text-xs">{item.itemName}</TableCell>
                                <TableCell className="text-center text-xs">{item.sizeWidth}</TableCell>
                                <TableCell className="text-center text-xs">{item.sizeHeight}</TableCell>
                                <TableCell className="text-center text-xs">{item.quantity}</TableCell>
                                <TableCell className="text-center text-xs">{item.lightType}</TableCell>
                                <TableCell className="text-center text-xs">{item.lotNo}</TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>

                      {/* 모바일 카드 */}
                      <div className="md:hidden space-y-2">
                        {materialsData.filter(item => item.itemName).map((item) => (
                          <Card key={item.no} className="border">
                            <CardContent className="p-3 space-y-2">
                              <div className="flex items-center justify-between">
                                <div className="text-xs font-semibold">No. {item.no}</div>
                                <Badge variant="outline" className="text-xs">{item.symbol}</Badge>
                              </div>
                              <div className="grid grid-cols-2 gap-2 text-xs">
                                <div>
                                  <span className="text-muted-foreground">층:</span> {item.floor}
                                </div>
                                <div>
                                  <span className="text-muted-foreground">품목:</span> {item.itemName}
                                </div>
                                <div>
                                  <span className="text-muted-foreground">가로:</span> {item.sizeWidth}
                                </div>
                                <div>
                                  <span className="text-muted-foreground">세��:</span> {item.sizeHeight}
                                </div>
                                <div>
                                  <span className="text-muted-foreground">예수:</span> {item.quantity}
                                </div>
                                <div>
                                  <span className="text-muted-foreground">발광:</span> {item.lightType}
                                </div>
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>

                      {/* 조인트바 섹션 */}
                      <div className="mt-4">
                        <div className="text-sm font-semibold mb-2">조인트바</div>
                        
                        {/* 데스크톱 테이블 */}
                        <div className="hidden md:block">
                          <Table>
                            <TableHeader>
                              <TableRow className="bg-muted/50">
                                <TableHead className="text-center w-[60px] text-xs">일련<br/>번호</TableHead>
                                <TableHead className="text-center text-xs">
                                  <div className="flex items-center justify-center gap-1">
                                    품목<br/>종류
                                    <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                                      5
                                    </div>
                                  </div>
                                </TableHead>
                                <TableHead className="text-center text-xs">수량</TableHead>
                                <TableHead className="text-center text-xs">성적서 LOT NO.</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {jointBarData.map((item) => (
                                <TableRow key={item.no}>
                                  <TableCell className="text-center text-xs">{item.no}</TableCell>
                                  <TableCell className="text-center text-xs">{item.itemType}</TableCell>
                                  <TableCell className="text-center text-xs">{item.quantity}</TableCell>
                                  <TableCell className="text-center text-xs">{item.completedLotNo}</TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>

                        {/* 모바일 카드 */}
                        <div className="md:hidden space-y-2">
                          {jointBarData.map((item) => (
                            <Card key={item.no} className="border">
                              <CardContent className="p-3">
                                <div className="grid grid-cols-2 gap-2 text-xs">
                                  <div>
                                    <span className="text-muted-foreground">No:</span> {item.no}
                                  </div>
                                  <div>
                                    <span className="text-muted-foreground">품목:</span> {item.itemType}
                                  </div>
                                  <div>
                                    <span className="text-muted-foreground">수량:</span> {item.quantity}
                                  </div>
                                  <div className="col-span-2">
                                    <span className="text-muted-foreground">LOT NO:</span> {item.completedLotNo}
                                  </div>
                                </div>
                              </CardContent>
                            </Card>
                          ))}
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* 오른쪽: 작업자 배치 + 우선 작업순위 */}
              <div className="lg:col-span-4 space-y-4">
                {/* 작업자 배치 */}
                <Card className="border-l-4 border-l-red-500">
                  <CardHeader className="pb-3">
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                        1
                      </div>
                      <CardTitle className="text-base md:text-lg">▶ 작업자 배치</CardTitle>
                      <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold ml-auto">
                        ⊕
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="space-y-2">
                      <Label className="text-xs">작업자1</Label>
                      <Select value={worker1} onValueChange={setWorker1}>
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue placeholder="선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {workers.map((worker) => (
                            <SelectItem key={worker} value={worker} className="text-sm">
                              {worker}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label className="text-xs">작업자2</Label>
                      <Select value={worker2} onValueChange={setWorker2}>
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue placeholder="선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {workers.map((worker) => (
                            <SelectItem key={worker} value={worker} className="text-sm">
                              {worker}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label className="text-xs">작업자3</Label>
                      <Select value={worker3} onValueChange={setWorker3}>
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue placeholder="선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {workers.map((worker) => (
                            <SelectItem key={worker} value={worker} className="text-sm">
                              {worker}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </CardContent>
                </Card>

                {/* 우선 작업순위 */}
                <Card className="border-l-4 border-l-red-500">
                  <CardHeader className="pb-3">
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                        2
                      </div>
                      <CardTitle className="text-base md:text-lg">▶ 우선 작업순위</CardTitle>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="space-y-2">
                      <Label className="text-xs text-muted-foreground">연제순위</Label>
                      <Select defaultValue="선택">
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="선택">선택</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label className="text-xs text-muted-foreground">실제순위</Label>
                      <Select defaultValue="선택">
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="선택">선택</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </CardContent>
                </Card>

                {/* 하단 버튼 그룹 */}
                <div className="flex items-center justify-end gap-2">
                  <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                    3
                  </div>
                  <Button variant="outline" size="sm" className="h-8 text-sm">
                    작성
                  </Button>
                  <Button variant="outline" size="sm" className="h-8 text-sm">
                    취소
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 하단 버튼 */}
        <div className="flex-shrink-0 p-3 md:p-4 border-t bg-background">
          <div className="flex flex-col sm:flex-row justify-end gap-2">
            <Button variant="outline" className="h-9">
              수정
            </Button>
            <Button variant="default" className="bg-blue-600 hover:bg-blue-700 h-9">
              저장
            </Button>
            <Button variant="outline" className="h-9">
              작업지시서PDF
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 절곡 생산 컴포넌트
function BendingProduction({ searchTerm, setSearchTerm, onViewWorkOrder }: ProductionProps) {
  const [subTab, setSubTab] = useState("workOrder");

  return (
    <div className="space-y-5">
      <Tabs value={subTab} onValueChange={setSubTab} className="w-full">
        <TabsList className="w-full md:w-auto bg-muted/40 p-1 h-10 gap-1">
          <TabsTrigger 
            value="workOrder" 
            className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border-b-2 data-[state=active]:border-primary hover:bg-background/50 transition-colors px-6"
          >
            작업지시현황
          </TabsTrigger>
          <TabsTrigger 
            value="processProgress" 
            className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border-b-2 data-[state=active]:border-primary hover:bg-background/50 transition-colors px-6"
          >
            공정진행현황
          </TabsTrigger>
        </TabsList>

        {/* 작업지시현황 */}
        <TabsContent value="workOrder" className="space-y-5 mt-5">
          <BendingWorkOrder searchTerm={searchTerm} setSearchTerm={setSearchTerm} onViewWorkOrder={onViewWorkOrder} />
        </TabsContent>

        {/* 공정진행현황 */}
        <TabsContent value="processProgress" className="space-y-5 mt-5">
          <BendingProcessProgress searchTerm={searchTerm} setSearchTerm={setSearchTerm} />
        </TabsContent>
      </Tabs>
    </div>
  );
}

// 절곡 작업지시현황 컴포넌트
interface BendingWorkOrderProps {
  searchTerm: string;
  setSearchTerm: (term: string) => void;
  onViewWorkOrder: (workOrder: any) => void;
}

function BendingWorkOrder({ searchTerm, setSearchTerm, onViewWorkOrder }: BendingWorkOrderProps) {
  const [showWriteForm, setShowWriteForm] = useState(false);
  const [sortField, setSortField] = useState<string>("");
  const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
  
  const handleSaveWorkOrder = (data: any) => {
    console.log("저장된 절곡 작업지시서:", data);
    // 여기에 실제 저장 로직 추가
  };

  const handleSort = (field: string) => {
    if (sortField === field) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      setSortDirection("asc");
    }
  };

  // 절곡 작업지시 데이터
  const bendingWorkOrderData = [
    {
      no: 10,
      workPriority: 0,
      orderDate: "2025-06-24",
      buyer: "한빛에스티",
      siteName: "반포3지구",
      productName: "KSS02",
      quantity: 9,
      requestDate: "2025-08-03",
      workStatus: "대기"
    },
    {
      no: 9,
      workPriority: 0,
      orderDate: "2025-07-14",
      buyer: "이엘도어",
      siteName: "상도동주상복합(1층)",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-03",
      workStatus: "대기"
    },
    {
      no: 8,
      workPriority: 1,
      orderDate: "2025-07-26",
      buyer: "주일기업",
      siteName: "과천지식정보원장",
      productName: "KSS02",
      quantity: 5,
      requestDate: "2025-08-05",
      workStatus: "작업중"
    },
    {
      no: 7,
      workPriority: 2,
      orderDate: "2025-08-01",
      buyer: "명보에스티",
      siteName: "오창큐브",
      productName: "KSS02",
      quantity: 20,
      requestDate: "2025-08-05",
      workStatus: "작업취소"
    },
    {
      no: 6,
      workPriority: 3,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "번월공단",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-05",
      workStatus: "작업중"
    },
    {
      no: 5,
      workPriority: 4,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "이천종리 우미린1단지",
      productName: "KSS02",
      quantity: 5,
      requestDate: "2025-08-05",
      workStatus: "작업중"
    },
    {
      no: 4,
      workPriority: 5,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "이천종리 우미린2단지",
      productName: "KSS02",
      quantity: 5,
      requestDate: "2025-08-07",
      workStatus: "협수"
    },
    {
      no: 3,
      workPriority: 6,
      orderDate: "2025-08-03",
      buyer: "한국특수",
      siteName: "인천영림물류창고",
      productName: "KQTS01",
      quantity: 5,
      requestDate: "2025-08-07",
      workStatus: "협수"
    },
    {
      no: 2,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "상도동주상복합(2층)",
      productName: "KSS02",
      quantity: 1,
      requestDate: "2025-08-10",
      workStatus: "완료"
    },
    {
      no: 1,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "상도동주상복합(3층)",
      productName: "KSS02",
      quantity: 2,
      requestDate: "2025-08-10",
      workStatus: "완료"
    }
  ];

  const getStatusConfig = (status: string) => {
    const configs: Record<string, { bg: string; text: string }> = {
      "대기": { bg: "bg-gray-100", text: "text-gray-700" },
      "작업중": { bg: "bg-orange-100", text: "text-orange-700" },
      "작업취소": { bg: "bg-red-100", text: "text-red-700" },
      "협수": { bg: "bg-purple-100", text: "text-purple-700" },
      "완료": { bg: "bg-green-100", text: "text-green-700" }
    };
    return configs[status] || configs["대기"];
  };

  const handleRowClick = (item: any) => {
    onViewWorkOrder(item);
  };

  // 소팅 적용
  const sortedData = [...bendingWorkOrderData].sort((a, b) => {
    if (!sortField) return 0;
    
    let aValue = a[sortField as keyof typeof a];
    let bValue = b[sortField as keyof typeof b];
    
    // null 처리
    if (aValue === null) aValue = "";
    if (bValue === null) bValue = "";
    
    // 숫자 비교
    if (typeof aValue === "number" && typeof bValue === "number") {
      return sortDirection === "asc" ? aValue - bValue : bValue - aValue;
    }
    
    // 문자열 비교
    const aStr = String(aValue).toLowerCase();
    const bStr = String(bValue).toLowerCase();
    
    if (sortDirection === "asc") {
      return aStr > bStr ? 1 : -1;
    } else {
      return aStr < bStr ? 1 : -1;
    }
  });

  // 작성 페이지 표시
  if (showWriteForm) {
    return (
      <WorkOrderWrite 
        onBack={() => setShowWriteForm(false)} 
        onSave={handleSaveWorkOrder}
        productionType="절곡"
      />
    );
  }

  return (
    <div className="space-y-5">
      {/* 검색 및 버튼 */}
      <Card className="border-border/50 bg-card/50">
        <CardContent className="p-4">
          <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="발주처, 현장명, 제품명으로 검색..."
                className="pl-10 bg-background"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <div className="flex gap-2 flex-wrap sm:flex-nowrap">
              <Button 
                onClick={() => setShowWriteForm(true)}
                className="bg-green-600 hover:bg-green-700 flex-1 sm:flex-none"
              >
                <Edit className="h-4 w-4 mr-2" />
                작업지시서 작성
              </Button>
              <Button 
                onClick={() => bendingWorkOrderData.length > 0 && handleRowClick(bendingWorkOrderData[0])}
                variant="outline"
                className="border-blue-600 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-950 flex-1 sm:flex-none"
              >
                <Eye className="h-4 w-4 mr-2" />
                미리보기
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 데스크톱 테이블 */}
      <Card className="hidden md:block border-border/50">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="bg-muted/30 hover:bg-muted/30 border-b-2 border-border">
                <TableHead className="text-center w-[60px] font-semibold">No.</TableHead>
                <TableHead className="text-center w-[100px]">
                  <button 
                    onClick={() => handleSort("workPriority")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">작업순위</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "workPriority" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center w-[120px]">
                  <button 
                    onClick={() => handleSort("orderDate")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">수주계약일</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "orderDate" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center w-[150px]">
                  <button 
                    onClick={() => handleSort("buyer")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">발주처</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "buyer" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center">
                  <button 
                    onClick={() => handleSort("siteName")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">현장명</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "siteName" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center w-[100px]">
                  <button 
                    onClick={() => handleSort("productName")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">제품명</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "productName" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center w-[80px]">
                  <button 
                    onClick={() => handleSort("quantity")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">수량</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "quantity" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center w-[120px]">
                  <button 
                    onClick={() => handleSort("requestDate")}
                    className="flex items-center justify-center gap-1 w-full hover:text-primary transition-colors"
                  >
                    <span className="font-semibold">출고요청일</span>
                    <ChevronDown className={`h-4 w-4 transition-transform ${sortField === "requestDate" && sortDirection === "desc" ? "rotate-180" : ""}`} />
                  </button>
                </TableHead>
                <TableHead className="text-center w-[120px] font-semibold">
                  작업지시현황
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {sortedData.map((item, index) => (
                <TableRow 
                  key={item.no}
                  className={`hover:bg-muted/50 cursor-pointer transition-colors ${index % 2 === 0 ? "bg-background" : "bg-muted/10"}`}
                  onClick={() => handleRowClick(item)}
                >
                  <TableCell className="text-center font-medium">{item.no}</TableCell>
                  <TableCell className="text-center">
                    {item.workPriority !== null ? (
                      <div className="inline-flex items-center justify-center px-2.5 py-1 rounded-md bg-primary/10 text-primary font-semibold">
                        {item.workPriority}
                      </div>
                    ) : (
                      <span className="text-muted-foreground">-</span>
                    )}
                  </TableCell>
                  <TableCell className="text-center">{item.orderDate}</TableCell>
                  <TableCell className="text-center font-medium">{item.buyer}</TableCell>
                  <TableCell className="text-center">{item.siteName}</TableCell>
                  <TableCell className="text-center font-semibold text-primary">{item.productName}</TableCell>
                  <TableCell className="text-center">{item.quantity}</TableCell>
                  <TableCell className="text-center">{item.requestDate}</TableCell>
                  <TableCell className="text-center">
                    <Badge 
                      className={`${getStatusConfig(item.workStatus).bg} ${getStatusConfig(item.workStatus).text} border font-medium px-2.5 py-0.5`}
                    >
                      {item.workStatus}
                    </Badge>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </Card>

      {/* 모바일 카드 */}
      <div className="md:hidden space-y-3">
        {sortedData.map((item) => (
          <Card 
            key={item.no}
            className="cursor-pointer hover:border-primary/50 transition-all hover:shadow-md"
            onClick={() => handleRowClick(item)}
          >
            <CardContent className="p-4 space-y-3">
              <div className="flex items-start justify-between">
                <div className="space-y-1 flex-1">
                  <div className="flex items-center gap-2">
                    <span className="text-xs text-muted-foreground">No. {item.no}</span>
                    {item.workPriority !== null && (
                      <div className="inline-flex items-center justify-center px-2 py-0.5 rounded-md bg-primary/10 text-primary text-xs font-semibold">
                        순위 {item.workPriority}
                      </div>
                    )}
                  </div>
                  <div className="font-semibold text-base">{item.siteName}</div>
                  <div className="text-sm text-muted-foreground">{item.buyer}</div>
                </div>
                <Badge 
                  className={`${getStatusConfig(item.workStatus).bg} ${getStatusConfig(item.workStatus).text} border font-medium px-2.5 py-0.5`}
                >
                  {item.workStatus}
                </Badge>
              </div>

              <div className="grid grid-cols-2 gap-3 pt-2 border-t border-border/50">
                <div>
                  <div className="text-xs text-muted-foreground mb-1">제품명</div>
                  <div className="font-semibold text-primary">{item.productName}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground mb-1">수량</div>
                  <div className="font-medium">{item.quantity} 통</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground mb-1">수주계약일</div>
                  <div className="text-sm">{item.orderDate}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground mb-1">출고요청일</div>
                  <div className="text-sm">{item.requestDate}</div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

    </div>
  );
}

// 절곡 공정진행현황 컴포넌트
function BendingProcessProgress({ searchTerm, setSearchTerm }: ProductionProps) {
  const [selectedProcess, setSelectedProcess] = useState<any>(null);
  const [showProcessDetailModal, setShowProcessDetailModal] = useState(false);

  // 절곡 공정진행 데이터
  const bendingProcessProgressData = [
    {
      no: 10,
      workPriority: 0,
      orderDate: "2025-06-24",
      buyer: "한빛에스티",
      siteName: "반포3지구",
      productName: "KSS02",
      quantity: 9,
      requestDate: "2025-08-03",
      processStatus: "대기"
    },
    {
      no: 9,
      workPriority: 0,
      orderDate: "2025-07-14",
      buyer: "이엘도어",
      siteName: "상도동주상복합(1층)",
      productName: "KSS02",
      quantity: 5,
      requestDate: "2025-08-03",
      processStatus: "대기"
    },
    {
      no: 8,
      workPriority: 1,
      orderDate: "2025-07-26",
      buyer: "주일기업",
      siteName: "과천지식정보원장",
      productName: "KSS02",
      quantity: 5,
      requestDate: "2025-08-05",
      processStatus: "절곡"
    },
    {
      no: 7,
      workPriority: 2,
      orderDate: "2025-08-01",
      buyer: "명보에스티",
      siteName: "오창큐브",
      productName: "KSS02",
      quantity: 20,
      requestDate: "2025-08-05",
      processStatus: "작업취소"
    },
    {
      no: 6,
      workPriority: 3,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "번월공단",
      productName: "KSS02",
      quantity: 5,
      requestDate: "2025-08-05",
      processStatus: "용접"
    },
    {
      no: 5,
      workPriority: 4,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "이천종리 우미린1단지",
      productName: "KSS02",
      quantity: 5,
      requestDate: "2025-08-05",
      processStatus: "절단"
    },
    {
      no: 4,
      workPriority: 5,
      orderDate: "2025-08-01",
      buyer: "주일기업",
      siteName: "이천종리 우미린2단지",
      productName: "KSS02",
      quantity: 5,
      requestDate: "2025-08-07",
      processStatus: "준비"
    },
    {
      no: 3,
      workPriority: 6,
      orderDate: "2025-08-03",
      buyer: "한국특수",
      siteName: "인천영명용항청고",
      productName: "KSS02",
      quantity: 5,
      requestDate: "2025-08-07",
      processStatus: "준비"
    },
    {
      no: 2,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "상도동주상복합(2층)",
      productName: "KSS02",
      quantity: 1,
      requestDate: "2025-08-10",
      processStatus: "출고대기"
    },
    {
      no: 1,
      workPriority: null,
      orderDate: "2025-08-04",
      buyer: "명보에스티",
      siteName: "상도동주상복합(3층)",
      productName: "KSS02",
      quantity: 2,
      requestDate: "2025-08-10",
      processStatus: "출고대기"
    }
  ];

  const getStatusConfig = (status: string) => {
    const configs: Record<string, { bg: string; text: string }> = {
      "대기": { bg: "bg-gray-100", text: "text-gray-700" },
      "준비": { bg: "bg-yellow-100", text: "text-yellow-700" },
      "절단": { bg: "bg-orange-100", text: "text-orange-700" },
      "절곡": { bg: "bg-purple-100", text: "text-purple-700" },
      "용접": { bg: "bg-blue-100", text: "text-blue-700" },
      "작업취소": { bg: "bg-red-100", text: "text-red-700" },
      "출고대기": { bg: "bg-green-100", text: "text-green-700" }
    };
    return configs[status] || configs["대기"];
  };

  const handleRowClick = (item: any) => {
    setSelectedProcess(item);
    setShowProcessDetailModal(true);
  };

  return (
    <div className="space-y-4">
      {/* 검색 */}
      <div className="flex items-center gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
          <Input
            placeholder="검색..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-9 h-9"
          />
        </div>
      </div>

      {/* 데스크톱 테이블 */}
      <div className="hidden md:block border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow className="bg-muted/50">
              <TableHead className="text-center w-[60px]">No.</TableHead>
              <TableHead className="text-center w-[100px]">
                작업순위
                <ChevronDown className="inline h-3 w-3 ml-1" />
              </TableHead>
              <TableHead className="text-center w-[120px]">
                수주계약일
                <ChevronDown className="inline h-3 w-3 ml-1" />
              </TableHead>
              <TableHead className="text-center w-[120px]">발주처</TableHead>
              <TableHead className="text-center">현장명</TableHead>
              <TableHead className="text-center w-[100px]">제품명</TableHead>
              <TableHead className="text-center w-[80px]">수량(통)</TableHead>
              <TableHead className="text-center w-[120px]">
                출고요청일
                <ChevronDown className="inline h-3 w-3 ml-1" />
              </TableHead>
              <TableHead className="text-center w-[120px]">
                공정진행현황
              </TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {bendingProcessProgressData.map((item) => (
              <TableRow 
                key={item.no}
                className="hover:bg-muted/30 cursor-pointer"
                onClick={() => handleRowClick(item)}
              >
                <TableCell className="text-center text-sm">{item.no}</TableCell>
                <TableCell className="text-center text-sm">
                  {item.workPriority !== null ? item.workPriority : '-'}
                </TableCell>
                <TableCell className="text-center text-sm">{item.orderDate}</TableCell>
                <TableCell className="text-center text-sm">{item.buyer}</TableCell>
                <TableCell className="text-center text-sm">{item.siteName}</TableCell>
                <TableCell className="text-center text-sm">{item.productName}</TableCell>
                <TableCell className="text-center text-sm">{item.quantity}</TableCell>
                <TableCell className="text-center text-sm">{item.requestDate}</TableCell>
                <TableCell className="text-center">
                  <Badge 
                    className={`${getStatusConfig(item.processStatus).bg} ${getStatusConfig(item.processStatus).text} border-0`}
                  >
                    {item.processStatus}
                  </Badge>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* 모바일 카드 */}
      <div className="md:hidden space-y-3">
        {bendingProcessProgressData.map((item) => (
          <Card 
            key={item.no}
            className="cursor-pointer"
            onClick={() => handleRowClick(item)}
          >
            <CardContent className="p-4 space-y-3">
              <div className="flex items-start justify-between">
                <div className="space-y-1">
                  <div className="flex items-center gap-2">
                    <span className="text-xs text-muted-foreground">No. {item.no}</span>
                    {item.workPriority !== null && (
                      <Badge variant="outline" className="text-xs">
                        순위 {item.workPriority}
                      </Badge>
                    )}
                  </div>
                  <div className="font-semibold">{item.siteName}</div>
                  <div className="text-sm text-muted-foreground">{item.buyer}</div>
                </div>
                <Badge 
                  className={`${getStatusConfig(item.processStatus).bg} ${getStatusConfig(item.processStatus).text} border-0`}
                >
                  {item.processStatus}
                </Badge>
              </div>

              <div className="grid grid-cols-2 gap-2 text-sm">
                <div>
                  <span className="text-muted-foreground">제품: </span>
                  <span className="font-medium">{item.productName}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">수량: </span>
                  <span className="font-medium">{item.quantity}통</span>
                </div>
                <div className="col-span-2">
                  <span className="text-muted-foreground">계약일: </span>
                  <span className="font-medium">{item.orderDate}</span>
                </div>
              </div>

              <div className="text-xs text-muted-foreground">
                출고요청일: {item.requestDate}
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 공정 상세 모달 */}
      {selectedProcess && (
        <Dialog open={showProcessDetailModal} onOpenChange={setShowProcessDetailModal}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>공정 상세</DialogTitle>
            </DialogHeader>
            <div className="space-y-2">
              <p><strong>현장명:</strong> {selectedProcess.siteName}</p>
              <p><strong>발주처:</strong> {selectedProcess.buyer}</p>
              <p><strong>제품명:</strong> {selectedProcess.productName}</p>
              <p><strong>공정상태:</strong> {selectedProcess.processStatus}</p>
            </div>
          </DialogContent>
        </Dialog>
      )}
    </div>
  );
}

// 절곡 작업지시서 모달
interface BendingWorkOrderModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  orderData: any;
}

function BendingWorkOrderModal({ open, onOpenChange, orderData }: BendingWorkOrderModalProps) {
  const [worker1, setWorker1] = useState("김동실");
  const [worker2, setWorker2] = useState("원문서");
  const [worker3, setWorker3] = useState("유영수");

  const workers = ["선택", "김동실", "원문서", "유영수", "배진석"];

  // 케이스 데이터
  const caseData1 = [
    { no: 1, floor: "1", material: "RSA630-30", size: "3000", quantity: "4", lotNo: "자동입력" },
    { no: 2, floor: "1", material: "RSA630-30", size: "3000", quantity: "4", lotNo: "자동입력" },
    { no: 3, floor: "1", material: "RSA630-30", size: "3000", quantity: "4", lotNo: "자동입력" },
    { no: 4, floor: "1", material: "RSA630-30", size: "120*75", quantity: "4", lotNo: "" }
  ];

  const caseData2 = [
    { no: 1, floor: "1", material: "EGI 1.5ST", size: "4000", quantity: "1", lotNo: "자동입력" },
    { no: 2, floor: "", material: "", size: "4000", quantity: "1", lotNo: "자동입력" },
    { no: 3, floor: "", material: "", size: "4000", quantity: "2", lotNo: "자동입력" },
    { no: 4, floor: "", material: "", size: "3000", quantity: "4", lotNo: "자동입력" }
  ];

  const caseData3 = [
    { no: 1, floor: "1", material: "EGI 1.5ST", size: "3000", quantity: "1", lotNo: "자동입력" },
    { no: 2, floor: "", material: "", size: "4150", quantity: "2", lotNo: "자동입력" },
    { no: 3, floor: "", material: "", size: "1219", quantity: "1", lotNo: "자동입력" },
    { no: 4, floor: "", material: "", size: "3000", quantity: "1", lotNo: "자동입력" },
    { no: 5, floor: "", material: "", size: "4150", quantity: "2", lotNo: "자동입력" },
    { no: 6, floor: "", material: "", size: "1219", quantity: "1", lotNo: "자동입력" },
    { no: 7, floor: "", material: "", size: "3000", quantity: "1", lotNo: "자동입력" },
    { no: 8, floor: "", material: "", size: "4150", quantity: "2", lotNo: "자동입력" }
  ];

  const caseData4 = [
    { no: 1, floor: "", material: "EGI 0.8T", size: "3000", quantity: "6", lotNo: "자동입력" },
    { no: 2, floor: "", material: "EGI 0.8T", size: "3000", quantity: "9", lotNo: "자동입력" }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] h-[95vh] p-0 flex flex-col gap-0">
        <DialogHeader className="sr-only">
          <DialogTitle>절곡 작업지시서</DialogTitle>
          <DialogDescription>
            절곡 생산 작업지시 상세 정보
          </DialogDescription>
        </DialogHeader>
        {/* 헤더 */}
        <div className="flex-shrink-0 flex items-center justify-between p-4 md:p-6 border-b bg-muted/30">
          <h2 className="text-lg md:text-xl font-semibold">절곡 작업지시서</h2>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => onOpenChange(false)}
          >
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* 컨텐츠 */}
        <div className="flex-1 overflow-y-auto">
          <div className="p-4 md:p-6 space-y-6">
            {/* 작업 기본정보 */}
            <Card className="border-l-4 border-l-red-500">
              <CardHeader className="pb-3">
                <CardTitle className="text-base md:text-lg">▶ 작업 기본정보</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  {/* 1행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">수주계약일</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">발주처</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">현장명</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">제품명</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>

                  {/* 2행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">출고요청일</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">배송방식</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1 lg:col-span-2">
                    <Label className="text-xs text-muted-foreground">비고</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" />
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 메인 그리드 */}
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
              {/* 왼쪽: 제고물건 및 자재부위 */}
              <div className="lg:col-span-8 space-y-4">
                <Card className="border-l-4 border-l-red-500">
                  <CardHeader className="pb-3">
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                        1
                      </div>
                      <CardTitle className="text-base md:text-lg">▶ 제고물건 및 자재부위</CardTitle>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-4">
                    {/* 상단 2개 테이블 */}
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                      {/* 케이스1 */}
                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <div className="text-sm font-semibold text-red-600">1. 케이스 [500*300] 하좌우 위 타입</div>
                          <div className="flex items-center gap-2">
                            <div className="w-5 h-5 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                              ⊕
                            </div>
                          </div>
                        </div>
                        <div className="overflow-x-auto">
                          <Table className="border">
                            <TableHeader>
                              <TableRow className="bg-muted/50">
                                <TableHead className="text-center text-xs">밸브타입</TableHead>
                                <TableHead className="text-center text-xs">재질</TableHead>
                                <TableHead className="text-center text-xs">절곡(크기) / 수량 / 입고 LOT NO.</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {caseData1.map((item) => (
                                <TableRow key={item.no}>
                                  <TableCell className="text-center text-xs">{item.floor}</TableCell>
                                  <TableCell className="text-center text-xs">{item.material}</TableCell>
                                  <TableCell className="p-1">
                                    <div className="flex items-center gap-1">
                                      <Input className="h-6 text-xs" defaultValue={item.size} />
                                      <Input className="h-6 text-xs w-12" defaultValue={item.quantity} />
                                      <Input className="h-6 text-xs" defaultValue={item.lotNo} readOnly />
                                      <div className="w-4 h-4 rounded-full bg-black flex-shrink-0"></div>
                                    </div>
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                      </div>

                      {/* 배전반실 */}
                      <div className="space-y-2">
                        <div className="text-sm font-semibold text-red-600">2. 배전반실</div>
                        <div className="overflow-x-auto">
                          <Table className="border">
                            <TableHeader>
                              <TableRow className="bg-muted/50">
                                <TableHead className="text-center text-xs">밸브타입</TableHead>
                                <TableHead className="text-center text-xs">재질</TableHead>
                                <TableHead className="text-center text-xs">절곡(크기) / 수량 / 입고 LOT NO.</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {caseData2.map((item, idx) => (
                                <TableRow key={idx}>
                                  <TableCell className="text-center text-xs">{item.floor}</TableCell>
                                  <TableCell className="text-center text-xs">{item.material}</TableCell>
                                  <TableCell className="p-1">
                                    <div className="flex items-center gap-1">
                                      <Input className="h-6 text-xs" defaultValue={item.size} />
                                      <Input className="h-6 text-xs w-12" defaultValue={item.quantity} />
                                      <Input className="h-6 text-xs" defaultValue={item.lotNo} readOnly />
                                      <div className="w-4 h-4 rounded-full bg-black flex-shrink-0"></div>
                                    </div>
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                      </div>
                    </div>

                    {/* 하단 2개 테이블 */}
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                      {/* 케이스3 */}
                      <div className="space-y-2">
                        <div className="text-sm font-semibold text-red-600">3. 케이스 [500*300] 하좌우 위 타입</div>
                        <div className="overflow-x-auto">
                          <Table className="border">
                            <TableHeader>
                              <TableRow className="bg-muted/50">
                                <TableHead className="text-center text-xs">밸브타입</TableHead>
                                <TableHead className="text-center text-xs">재질</TableHead>
                                <TableHead className="text-center text-xs">절곡(크기) / 수량 / 입고 LOT NO.</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {caseData3.map((item, idx) => (
                                <TableRow key={idx}>
                                  <TableCell className="text-center text-xs">{item.floor}</TableCell>
                                  <TableCell className="text-center text-xs">{item.material}</TableCell>
                                  <TableCell className="p-1">
                                    <div className="flex items-center gap-1">
                                      <Input className="h-6 text-xs" defaultValue={item.size} />
                                      <Input className="h-6 text-xs w-12" defaultValue={item.quantity} />
                                      <Input className="h-6 text-xs" defaultValue={item.lotNo} readOnly />
                                      <div className="w-4 h-4 rounded-full bg-black flex-shrink-0"></div>
                                    </div>
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                      </div>

                      {/* 우지대적연 */}
                      <div className="space-y-2">
                        <div className="text-sm font-semibold text-red-600">4. 우지대적연</div>
                        <div className="overflow-x-auto">
                          <Table className="border">
                            <TableHeader>
                              <TableRow className="bg-muted/50">
                                <TableHead className="text-center text-xs">밸브타입</TableHead>
                                <TableHead className="text-center text-xs">재질</TableHead>
                                <TableHead className="text-center text-xs">절곡(크기) / 수량 / 입고 LOT NO.</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {caseData4.map((item, idx) => (
                                <TableRow key={idx}>
                                  <TableCell className="text-center text-xs">{item.floor}</TableCell>
                                  <TableCell className="text-center text-xs">{item.material}</TableCell>
                                  <TableCell className="p-1">
                                    <div className="flex items-center gap-1">
                                      <Input className="h-6 text-xs" defaultValue={item.size} />
                                      <Input className="h-6 text-xs w-12" defaultValue={item.quantity} />
                                      <Input className="h-6 text-xs" defaultValue={item.lotNo} readOnly />
                                      <div className="w-4 h-4 rounded-full bg-black flex-shrink-0"></div>
                                    </div>
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              </div>

              {/* 오른쪽: 작업자 배치 + 우선 작업순위 */}
              <div className="lg:col-span-4 space-y-4">
                {/* 작업자 배치 */}
                <Card className="border-l-4 border-l-red-500">
                  <CardHeader className="pb-3">
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                        1
                      </div>
                      <CardTitle className="text-base md:text-lg">▶ 작업자 배치</CardTitle>
                      <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold ml-auto">
                        ⊕
                      </div>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="space-y-2">
                      <Label className="text-xs">작업자1</Label>
                      <Select value={worker1} onValueChange={setWorker1}>
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue placeholder="선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {workers.map((worker) => (
                            <SelectItem key={worker} value={worker} className="text-sm">
                              {worker}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label className="text-xs">작업자2</Label>
                      <Select value={worker2} onValueChange={setWorker2}>
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue placeholder="선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {workers.map((worker) => (
                            <SelectItem key={worker} value={worker} className="text-sm">
                              {worker}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label className="text-xs">작업자3</Label>
                      <Select value={worker3} onValueChange={setWorker3}>
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue placeholder="선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {workers.map((worker) => (
                            <SelectItem key={worker} value={worker} className="text-sm">
                              {worker}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </CardContent>
                </Card>

                {/* 우선 작업순위 */}
                <Card className="border-l-4 border-l-red-500">
                  <CardHeader className="pb-3">
                    <div className="flex items-center gap-2">
                      <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                        2
                      </div>
                      <CardTitle className="text-base md:text-lg">▶ 우선 작업순위</CardTitle>
                    </div>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="space-y-2">
                      <Label className="text-xs text-muted-foreground">권장순위</Label>
                      <Select defaultValue="0">
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="0">0</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    <div className="space-y-2">
                      <Label className="text-xs text-muted-foreground">���정순위</Label>
                      <Select defaultValue="선택">
                        <SelectTrigger className="h-8 text-sm">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="선택">선택</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </CardContent>
                </Card>

                {/* 하단 버튼 그룹 */}
                <div className="flex items-center justify-end gap-2">
                  <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                    3
                  </div>
                  <Button variant="outline" size="sm" className="h-8 text-sm">
                    저장
                  </Button>
                  <Button variant="outline" size="sm" className="h-8 text-sm">
                    취소
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 하단 버튼 */}
        <div className="flex-shrink-0 p-3 md:p-4 border-t bg-background">
          <div className="flex flex-col sm:flex-row justify-end gap-2">
            <Button variant="outline" className="h-9">
              수정
            </Button>
            <Button variant="default" className="bg-blue-600 hover:bg-blue-700 h-9">
              저장
            </Button>
            <Button variant="outline" className="h-9">
              작업지시서PDF
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 절곡 작업상세정보 모달
interface BendingProcessDetailModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  processData: any;
}

function BendingProcessDetailModal({ open, onOpenChange, processData }: BendingProcessDetailModalProps) {
  const [showInspectionModal, setShowInspectionModal] = useState(false);
  const [showBendingInfoModal, setShowBendingInfoModal] = useState(false);

  // 작업 상세정보 데이터
  const detailData = [
    {
      no: 1,
      materialCode: "1507-29-01",
      materialName: "가이드레일",
      spec: "국민용(120*120)",
      material: "EGI 1.5ST",
      length: "4300",
      quantity: "6",
      cutting: true,
      bending: false,
      processCheck: false
    },
    {
      no: 2,
      materialCode: "RTA415-43",
      materialName: "가이드레일",
      spec: "국민용(120*120)",
      material: "EGI 1.5ST",
      length: "3500",
      quantity: "32",
      cutting: true,
      bending: false,
      processCheck: false
    },
    {
      no: 3,
      materialCode: "RC4710-43",
      materialName: "가이드레일",
      spec: "국민용(120*120)",
      material: "EGI 1.5ST",
      length: "3000",
      quantity: "8",
      cutting: true,
      bending: false,
      processCheck: false
    },
    {
      no: 4,
      materialCode: "",
      materialName: "케이스",
      spec: "520*380",
      material: "EGI 1.5ST",
      length: "4000",
      quantity: "8",
      cutting: true,
      bending: false,
      processCheck: false
    },
    {
      no: 5,
      materialCode: "",
      materialName: "케이스",
      spec: "500*380",
      material: "EGI 1.5ST",
      length: "3500",
      quantity: "2",
      cutting: true,
      bending: false,
      processCheck: false
    },
    {
      no: 6,
      materialCode: "",
      materialName: "케이스",
      spec: "500*380",
      material: "EGI 1.5ST",
      length: "2438",
      quantity: "14",
      cutting: true,
      bending: false,
      processCheck: false
    },
    {
      no: 7,
      materialCode: "",
      materialName: "",
      spec: "",
      material: "",
      length: "",
      quantity: "",
      cutting: false,
      bending: false,
      processCheck: false
    }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] h-[95vh] p-0 flex flex-col gap-0">
        <DialogHeader className="sr-only">
          <DialogTitle>절곡 작업상세정보</DialogTitle>
          <DialogDescription>
            절곡 생산 공정진행 상세 정보
          </DialogDescription>
        </DialogHeader>
        {/* 헤더 */}
        <div className="flex-shrink-0 flex items-center justify-between p-4 md:p-6 border-b bg-muted/30">
          <h2 className="text-lg md:text-xl font-semibold">절곡 작업상세정보</h2>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => onOpenChange(false)}
          >
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* 컨텐츠 */}
        <div className="flex-1 overflow-y-auto">
          <div className="p-4 md:p-6 space-y-6">
            {/* 기본정보 */}
            <Card className="border-l-4 border-l-blue-500">
              <CardHeader className="pb-3">
                <CardTitle className="text-base md:text-lg">▶ 작업 기본정보</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  {/* 1행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">수주계약일:</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">발주처:</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">제품명:</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>

                  {/* 2행 */}
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">출고요청일:</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">배송방식:</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">현장명:</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm bg-muted/50" readOnly />
                  </div>

                  {/* 3행 */}
                  <div className="space-y-1 md:col-span-3">
                    <Label className="text-xs text-muted-foreground">비고:</Label>
                    <Input defaultValue="자동입력" className="h-8 text-sm" />
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 작업 상세정보 */}
            <Card className="border-l-4 border-l-red-500">
              <CardHeader className="pb-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                      1
                    </div>
                    <CardTitle className="text-base md:text-lg">▶ 작업 상세정보</CardTitle>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                {/* 데스크톱 테이블 */}
                <div className="hidden lg:block overflow-x-auto">
                  <Table className="border">
                    <TableHeader>
                      <TableRow className="bg-muted/50">
                        <TableHead className="text-center text-xs w-[50px]">일련<br/>번호</TableHead>
                        <TableHead className="text-center text-xs w-[120px]">자재코드</TableHead>
                        <TableHead className="text-center text-xs w-[120px]">자재명</TableHead>
                        <TableHead className="text-center text-xs w-[150px]">규격</TableHead>
                        <TableHead className="text-center text-xs w-[100px]">재질</TableHead>
                        <TableHead className="text-center text-xs" colSpan={2}>제작사이즈</TableHead>
                        <TableHead className="text-center text-xs w-[60px]">절단</TableHead>
                        <TableHead className="text-center text-xs w-[60px]">절곡</TableHead>
                        <TableHead className="text-center text-xs w-[100px]">공정현황<br/>CHECK</TableHead>
                        <TableHead className="text-center text-xs w-[120px]">중간검사</TableHead>
                        <TableHead className="text-center text-xs w-[80px]">보정</TableHead>
                        <TableHead className="text-center text-xs w-[120px]">
                          <div className="flex items-center justify-center gap-1">
                            <div className="w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center text-xs font-bold">
                              2
                            </div>
                            절곡<br/>바라시
                          </div>
                        </TableHead>
                      </TableRow>
                      <TableRow className="bg-muted/50">
                        <TableHead colSpan={5}></TableHead>
                        <TableHead className="text-center text-xs w-[80px]">길이</TableHead>
                        <TableHead className="text-center text-xs w-[60px]">수량</TableHead>
                        <TableHead colSpan={5}></TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {detailData.map((item) => (
                        <TableRow key={item.no}>
                          <TableCell className="text-center text-xs">{item.no}</TableCell>
                          <TableCell className="text-center text-xs">{item.materialCode}</TableCell>
                          <TableCell className="text-center text-xs">{item.materialName}</TableCell>
                          <TableCell className="text-center text-xs">{item.spec}</TableCell>
                          <TableCell className="text-center text-xs">{item.material}</TableCell>
                          <TableCell className="text-center text-xs">{item.length}</TableCell>
                          <TableCell className="text-center text-xs">{item.quantity}</TableCell>
                          <TableCell className="text-center">
                            <Checkbox checked={item.cutting} className="mx-auto" />
                          </TableCell>
                          <TableCell className="text-center">
                            <Checkbox checked={item.bending} className="mx-auto" />
                          </TableCell>
                          <TableCell className="text-center">
                            <Checkbox checked={item.processCheck} className="mx-auto" />
                          </TableCell>
                          <TableCell className="text-center">
                            {item.no <= 6 && (
                              <Button 
                                variant="outline" 
                                size="sm" 
                                className="h-6 text-xs"
                                onClick={() => setShowInspectionModal(true)}
                              >
                                중간검사
                              </Button>
                            )}
                          </TableCell>
                          <TableCell className="text-center">
                            {item.no <= 6 && (
                              <Button variant="outline" size="sm" className="h-6 text-xs">
                                보정
                              </Button>
                            )}
                            {item.no === 2 && (
                              <div className="text-red-500 text-xs mt-1">불량건</div>
                            )}
                          </TableCell>
                          <TableCell className="text-center">
                            {item.no <= 6 && (
                              <Button 
                                variant="outline" 
                                size="sm" 
                                className="h-6 text-xs"
                                onClick={() => setShowBendingInfoModal(true)}
                              >
                                보기
                              </Button>
                            )}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>

                {/* 모바일 카드 */}
                <div className="lg:hidden space-y-3">
                  {detailData.filter(item => item.no <= 6).map((item) => (
                    <Card key={item.no} className="border">
                      <CardContent className="p-3 space-y-2">
                        <div className="flex items-center justify-between">
                          <Badge variant="outline">{item.no}번</Badge>
                          <div className="flex gap-2">
                            <Button 
                              variant="outline" 
                              size="sm" 
                              className="h-7 text-xs"
                              onClick={() => setShowInspectionModal(true)}
                            >
                              중간검사
                            </Button>
                            <Button variant="outline" size="sm" className="h-7 text-xs">
                              보정
                            </Button>
                          </div>
                        </div>
                        <div className="grid grid-cols-2 gap-2 text-xs">
                          <div>
                            <span className="text-muted-foreground">자재코드: </span>
                            {item.materialCode || '-'}
                          </div>
                          <div>
                            <span className="text-muted-foreground">자재명: </span>
                            {item.materialName}
                          </div>
                          <div className="col-span-2">
                            <span className="text-muted-foreground">규격: </span>
                            {item.spec}
                          </div>
                          <div>
                            <span className="text-muted-foreground">재질: </span>
                            {item.material}
                          </div>
                          <div>
                            <span className="text-muted-foreground">길이: </span>
                            {item.length}
                          </div>
                          <div>
                            <span className="text-muted-foreground">수량: </span>
                            {item.quantity}
                          </div>
                        </div>
                        <div className="flex items-center gap-4 text-xs">
                          <div className="flex items-center gap-1">
                            <Checkbox checked={item.cutting} />
                            <span>절단</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <Checkbox checked={item.bending} />
                            <span>절곡</span>
                          </div>
                          <div className="flex items-center gap-1">
                            <Checkbox checked={item.processCheck} />
                            <span>공정확인</span>
                          </div>
                        </div>
                        {item.no === 2 && (
                          <div className="text-red-500 text-xs">불량건</div>
                        )}
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </CardContent>
            </Card>

            {/* 자재 사용량 */}
            <Card className="border-l-4 border-l-green-500">
              <CardHeader className="pb-3">
                <div className="flex items-center gap-2">
                  <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">
                    1
                  </div>
                  <CardTitle className="text-base md:text-lg">▶ 자재 사용량</CardTitle>
                </div>
              </CardHeader>
              <CardContent>
                {/* 데스크톱 테이블 */}
                <div className="hidden md:block overflow-x-auto">
                  <Table className="border">
                    <TableHeader>
                      <TableRow className="bg-muted/50">
                        <TableHead className="text-center text-xs w-[100px]" rowSpan={2}>재질</TableHead>
                        <TableHead className="text-center text-xs" colSpan={6}>자재별 사용량</TableHead>
                      </TableRow>
                      <TableRow className="bg-muted/50">
                        <TableHead className="text-center text-xs">SUS 1.5T</TableHead>
                        <TableHead className="text-center text-xs">SUS 1.2T</TableHead>
                        <TableHead className="text-center text-xs">EGI 1.6T</TableHead>
                        <TableHead className="text-center text-xs">EGI 1.2T</TableHead>
                        <TableHead className="text-center text-xs">EGI 0.8T</TableHead>
                        <TableHead className="text-center text-xs">EGI 0.4</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      <TableRow>
                        <TableCell className="text-center text-sm font-medium">소요량</TableCell>
                        <TableCell className="text-center text-sm">17.6</TableCell>
                        <TableCell className="text-center text-sm">76.6</TableCell>
                        <TableCell className="text-center text-sm">316.6</TableCell>
                        <TableCell className="text-center text-sm">4.8</TableCell>
                        <TableCell className="text-center text-sm">25.7</TableCell>
                        <TableCell className="text-center text-sm">-</TableCell>
                      </TableRow>
                      <TableRow className="bg-blue-50">
                        <TableCell className="text-center text-sm font-medium">합계</TableCell>
                        <TableCell className="text-center text-sm font-medium">17.6</TableCell>
                        <TableCell className="text-center text-sm font-medium">76.6</TableCell>
                        <TableCell className="text-center text-sm font-medium">316.6</TableCell>
                        <TableCell className="text-center text-sm font-medium">4.8</TableCell>
                        <TableCell className="text-center text-sm font-medium">25.7</TableCell>
                        <TableCell className="text-center text-sm font-medium">-</TableCell>
                      </TableRow>
                    </TableBody>
                  </Table>
                </div>

                {/* 모바일 카드 */}
                <div className="md:hidden space-y-3">
                  <div className="grid grid-cols-2 gap-2 text-sm">
                    <div className="p-2 border rounded">
                      <div className="text-xs text-muted-foreground mb-1">SUS 1.5T</div>
                      <div className="font-medium">17.6</div>
                    </div>
                    <div className="p-2 border rounded">
                      <div className="text-xs text-muted-foreground mb-1">SUS 1.2T</div>
                      <div className="font-medium">76.6</div>
                    </div>
                    <div className="p-2 border rounded">
                      <div className="text-xs text-muted-foreground mb-1">EGI 1.6T</div>
                      <div className="font-medium">316.6</div>
                    </div>
                    <div className="p-2 border rounded">
                      <div className="text-xs text-muted-foreground mb-1">EGI 1.2T</div>
                      <div className="font-medium">4.8</div>
                    </div>
                    <div className="p-2 border rounded">
                      <div className="text-xs text-muted-foreground mb-1">EGI 0.8T</div>
                      <div className="font-medium">25.7</div>
                    </div>
                    <div className="p-2 border rounded">
                      <div className="text-xs text-muted-foreground mb-1">EGI 0.4</div>
                      <div className="font-medium">-</div>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        {/* 하단 버튼 */}
        <div className="flex-shrink-0 p-3 md:p-4 border-t bg-background">
          <div className="flex flex-col sm:flex-row justify-end gap-2">
            <Button variant="outline" className="h-9">
              수정
            </Button>
            <Button variant="default" className="bg-blue-600 hover:bg-blue-700 h-9">
              저장
            </Button>
            <Button variant="outline" className="h-9">
              작업일지PDF
            </Button>
          </div>
        </div>
      </DialogContent>

      {/* 중간검사 성적서 모달 */}
      {showInspectionModal && (
        <BendingInspectionModal
          open={showInspectionModal}
          onOpenChange={setShowInspectionModal}
        />
      )}

      {/* 절곡바라시 기초정보 모달 */}
      {showBendingInfoModal && (
        <BendingInfoModal
          open={showBendingInfoModal}
          onOpenChange={setShowBendingInfoModal}
        />
      )}
    </Dialog>
  );
}

// 절곡바라시 기초정보 모달
interface BendingInfoModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

function BendingInfoModal({ open, onOpenChange }: BendingInfoModalProps) {
  // 절곡지수 데이터
  const bendingData = [
    {
      group: "1",
      image: "1번(상/하접철)",
      no: "1번(상/하접철)",
      material: "SUS 1.2T",
      indices: [10, 21, 90, 104, 119, 134, null, null, null, null, null, null, null, null, null],
      length: 4300,
      quantity: 6,
      area: 3.4
    },
    {
      group: "2",
      image: "2번(대각선면)",
      no: "2번(대각선면)",
      material: "SUS 1.2T",
      indices: [10, 21, 130, 249, 278, 292, 301, 322, null, null, null, null, null, null, null],
      length: 3500,
      quantity: 32,
      area: 15,
      note: "A각"
    },
    {
      group: "3",
      image: "3번(본체)",
      no: "3번(본체)",
      material: "EGI 1.5ST",
      indices: [9, 34, 113, 179, 258, 283, 292, null, null, null, null, null, null, null, null],
      length: 3000,
      quantity: 8,
      area: 3.2,
      note: "A각"
    },
    {
      group: "4",
      image: "4번(측면형-D)",
      no: "4번(측면형-D)",
      material: "EGI 1.5ST",
      indices: [43, 137, 180, null, null, null, null, null, null, null, null, null, null, null, null],
      length: null,
      quantity: null,
      area: null
    }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] h-[95vh] p-0 flex flex-col gap-0">
        <DialogHeader className="sr-only">
          <DialogTitle>절곡바라시 기초정보</DialogTitle>
          <DialogDescription>
            절곡 바라시 기초정보 상세
          </DialogDescription>
        </DialogHeader>
        {/* 헤더 */}
        <div className="flex-shrink-0 flex items-center justify-between p-4 md:p-6 border-b bg-muted/30">
          <h2 className="text-lg md:text-xl font-semibold">절곡바라시 기초정보</h2>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => onOpenChange(false)}
          >
            <X className="h-4 w-4" />
          </Button>
        </div>

        {/* 컨텐츠 */}
        <div className="flex-1 overflow-y-auto">
          <div className="p-4 md:p-6 space-y-6">
            {/* 제목 */}
            <div className="border-2 border-black p-4">
              <div className="grid grid-cols-[auto_1fr_auto] gap-4 items-center">
                <div className="text-2xl font-bold">1.</div>
                <div className="text-xl font-bold text-center">가이드레일</div>
                <div className="text-xl font-bold">벽면형(120*70)</div>
              </div>
            </div>

            {/* 메인 테이블 */}
            <div className="border-2 border-black">
              {/* 데스크톱 테이블 */}
              <div className="hidden xl:block overflow-x-auto">
                <Table className="border-collapse">
                  <TableHeader>
                    <TableRow className="border-b-2 border-black">
                      <TableHead className="text-center text-sm border-r border-black" rowSpan={2}>그림</TableHead>
                      <TableHead className="text-center text-sm border-r border-black" rowSpan={2}>번호</TableHead>
                      <TableHead className="text-center text-sm border-r border-black" rowSpan={2}>재질</TableHead>
                      <TableHead className="text-center text-sm border-r border-black" colSpan={15}>절곡지수</TableHead>
                      <TableHead className="text-center text-sm border-r border-black" rowSpan={2}>길이</TableHead>
                      <TableHead className="text-center text-sm border-r border-black" rowSpan={2}>수량</TableHead>
                      <TableHead className="text-center text-sm" rowSpan={2}>면적</TableHead>
                    </TableRow>
                    <TableRow className="border-b border-black">
                      {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15].map(i => (
                        <TableHead key={i} className="text-center text-xs border-r border-gray-300 w-[50px]">{i}</TableHead>
                      ))}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {bendingData.map((item, idx) => (
                      <TableRow key={idx} className="border-b border-black">
                        <TableCell className="text-center text-xs border-r border-black p-2">
                          <div className="w-16 h-16 border border-gray-300 flex items-center justify-center text-xs text-muted-foreground">
                            {item.group}
                          </div>
                        </TableCell>
                        <TableCell className="text-center text-xs border-r border-black">{item.no}</TableCell>
                        <TableCell className="text-center text-xs border-r border-black">{item.material}</TableCell>
                        {item.indices.map((val, i) => (
                          <TableCell key={i} className="text-center text-xs border-r border-gray-300">
                            {val !== null ? val : ''}
                            {item.note && i === 4 && (
                              <div className="text-red-500 text-xs italic">{item.note}</div>
                            )}
                          </TableCell>
                        ))}
                        <TableCell className="text-center text-xs border-r border-black">{item.length || ''}</TableCell>
                        <TableCell className="text-center text-xs border-r border-black">{item.quantity || ''}</TableCell>
                        <TableCell className="text-center text-xs">{item.area || ''}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* 모바일 카드 */}
              <div className="xl:hidden space-y-4 p-4">
                {bendingData.map((item, idx) => (
                  <Card key={idx} className="border-2">
                    <CardContent className="p-4 space-y-3">
                      <div className="flex items-center gap-2">
                        <div className="w-16 h-16 border-2 border-gray-300 flex items-center justify-center text-lg font-bold">
                          {item.group}
                        </div>
                        <div className="flex-1">
                          <div className="font-semibold">{item.no}</div>
                          <div className="text-sm text-muted-foreground">{item.material}</div>
                        </div>
                      </div>
                      
                      <div className="grid grid-cols-5 gap-1 text-xs">
                        {item.indices.map((val, i) => (
                          <div key={i} className="border p-1 text-center">
                            {val !== null ? val : '-'}
                          </div>
                        ))}
                      </div>

                      {item.note && (
                        <div className="text-red-500 text-xs italic">{item.note}</div>
                      )}

                      <div className="grid grid-cols-3 gap-2 text-sm pt-2 border-t">
                        <div>
                          <span className="text-muted-foreground">길이: </span>
                          <span className="font-medium">{item.length || '-'}</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">수량: </span>
                          <span className="font-medium">{item.quantity || '-'}</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">면적: </span>
                          <span className="font-medium">{item.area || '-'}</span>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>

              {/* 우측 요약 테이블 */}
              <div className="flex justify-end p-4">
                <div className="border-2 border-black">
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-muted/50 border-b border-black">
                        <TableHead className="text-center text-sm border-r border-black">길이</TableHead>
                        <TableHead className="text-center text-sm border-r border-black">수량</TableHead>
                        <TableHead className="text-center text-sm">면적</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      <TableRow className="border-b border-gray-300">
                        <TableCell className="text-center text-sm border-r border-black">4300</TableCell>
                        <TableCell className="text-center text-sm border-r border-black">6</TableCell>
                        <TableCell className="text-center text-sm">3.4</TableCell>
                      </TableRow>
                      <TableRow className="border-b border-gray-300">
                        <TableCell className="text-center text-sm border-r border-black">3500</TableCell>
                        <TableCell className="text-center text-sm border-r border-black">32</TableCell>
                        <TableCell className="text-center text-sm">15</TableCell>
                      </TableRow>
                      <TableRow>
                        <TableCell className="text-center text-sm border-r border-black">3000</TableCell>
                        <TableCell className="text-center text-sm border-r border-black">8</TableCell>
                        <TableCell className="text-center text-sm">3.2</TableCell>
                      </TableRow>
                    </TableBody>
                  </Table>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* 하단 버튼 */}
        <div className="flex-shrink-0 p-3 md:p-4 border-t bg-background">
          <div className="flex flex-col sm:flex-row justify-end gap-2">
            <Button variant="outline" className="h-9">수정</Button>
            <Button variant="default" className="bg-blue-600 hover:bg-blue-700 h-9">저장</Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 절곡 중간검사 성적서 모달
interface BendingInspectionModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

function BendingInspectionModal({ open, onOpenChange }: BendingInspectionModalProps) {
  // 검사 데이터
  const inspectionData = [
    {
      type: "측정 1",
      drawing: "1",
      spec: "벽면형 (120*70)",
      material: "SUS 1.2T",
      lotNo: "LOT-2025-001",
      measurements: [
        { value: 3000, angle: 90, length1: 90, length2: 90, status: "O.K" },
        { value: 3000, angle: 90, length1: 90, length2: 90, status: "O.K" },
        { value: 3000, angle: 90, length1: 90, length2: 90, status: "O.K" }
      ]
    },
    {
      type: "측정 2",
      drawing: "2",
      spec: "벽면형 (120*70)",
      material: "SUS 1.2T",
      lotNo: "LOT-2025-002",
      measurements: [
        { value: 4350, angle: 90, length1: null, length2: null, status: "N.G" },
        { value: 4350, angle: 90, length1: null, length2: null, status: "O.K" }
      ]
    },
    {
      type: "측정 3",
      drawing: "3",
      spec: "벽면형 (120*70)",
      material: "EGI 1.5ST",
      lotNo: "LOT-2025-003",
      measurements: [
        { value: 3000, angle: null, length1: 12, length2: 12, status: "O.K" },
        { value: 3000, angle: null, length1: 12, length2: 12, status: "O.K" }
      ]
    },
    {
      type: "측정 4",
      drawing: "4",
      spec: "벽면형 (120*70)",
      material: "EGI 1.5ST",
      lotNo: "LOT-2025-004",
      measurements: [
        { value: 2000, angle: 12, length1: 12, length2: null, status: "O.K" }
      ]
    }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] w-[95vw] max-h-[95vh] h-[95vh] p-0 flex flex-col gap-0">
        <DialogHeader className="sr-only">
          <DialogTitle>절곡 중간검사 성적서</DialogTitle>
          <DialogDescription>
            절곡 중간검사 성적서 상세
          </DialogDescription>
        </DialogHeader>
        {/* 헤더 */}
        <div className="flex-shrink-0 flex items-center justify-between p-4 md:p-6 border-b bg-muted/30">
          <h2 className="text-lg md:text-xl font-semibold">절곡 중간검사 성적서</h2>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => onOpenChange(false)}
          >
            <X className="h-4 w-4" />
          </Button>
        </div>

        <div className="flex-1 overflow-y-auto p-4 md:p-6">
          <div className="space-y-6 max-w-5xl mx-auto">
            <div className="border-2 border-black">
              {/* 타이틀 */}
              <div className="grid grid-cols-12 border-b-2 border-black">
                <div className="col-span-6 p-4 flex items-center">
                  <div className="space-y-1">
                    <div className="text-2xl md:text-3xl font-bold text-blue-600">KJ</div>
                    <div className="text-sm text-muted-foreground">중간검사 성적서</div>
                  </div>
                </div>
                <div className="col-span-6 border-l-2 border-black p-4">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-muted-foreground">작성일: </span>
                      <span className="font-medium">2025-08-15</span>
                    </div>
                    <div className="text-right">
                      <div className="border-2 border-red-500 px-8 py-4">
                        <div className="text-3xl font-bold text-red-600">불합격</div>
                      </div>
                      <div className="text-xs mt-1">(주)경동기업</div>
                    </div>
                  </div>
                </div>
              </div>

              {/* 기본 정보 */}
              <div className="border-b-2 border-black">
                <div className="flex items-center gap-2 p-2 bg-red-50">
                  <div className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-sm font-bold">1</div>
                </div>
                <div className="grid grid-cols-12 text-xs md:text-sm">
                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">제품명</div>
                  <div className="col-span-4 p-2 border-b border-r border-black text-blue-600 font-semibold">KQTS01 - 가이드레일</div>
                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">생산수량</div>
                  <div className="col-span-4 p-2 border-b border-black">46 (통)</div>

                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">제품 LOT NO</div>
                  <div className="col-span-4 p-2 border-b border-black text-blue-600 font-semibold">KD-SA-250717-01</div>

                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">규격</div>
                  <div className="col-span-4 p-2 border-b border-r border-black">실리카 포털체크</div>
                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">로트크기</div>
                  <div className="col-span-4 p-2 border-b border-black">2 (개소)</div>

                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">발주처</div>
                  <div className="col-span-4 p-2 border-b border-r border-black">중앙산다</div>
                  <div className="col-span-2 p-2 bg-gray-100 border-b border-r border-black text-center font-semibold">검사일자</div>
                  <div className="col-span-4 p-2 border-b border-black">연도-월-일</div>

                  <div className="col-span-2 p-2 bg-gray-100 border-r border-black text-center font-semibold">원공부</div>
                  <div className="col-span-4 p-2 border-r border-black bg-orange-100">미싱</div>
                  <div className="col-span-2 p-2 bg-gray-100 border-r border-black text-center font-semibold">검사자</div>
                  <div className="col-span-4 p-2"></div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="flex-shrink-0 p-3 md:p-4 border-t bg-background">
          <div className="flex flex-col sm:flex-row justify-end gap-2">
            <Button variant="outline" className="h-9">수정</Button>
            <Button variant="default" className="bg-blue-600 hover:bg-blue-700 h-9">재출</Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 재고 생산 컴포넌트
function StockProduction({ searchTerm, setSearchTerm, onViewWorkOrder }: ProductionProps) {
  const [subTab, setSubTab] = useState("workOrder");

  return (
    <div className="space-y-5">
      <Tabs value={subTab} onValueChange={setSubTab} className="w-full">
        <TabsList className="w-full md:w-auto bg-muted/40 p-1 h-10 gap-1">
          <TabsTrigger 
            value="workOrder" 
            className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border-b-2 data-[state=active]:border-primary hover:bg-background/50 transition-colors px-6"
          >
            작업지시현황
          </TabsTrigger>
          <TabsTrigger 
            value="processProgress" 
            className="data-[state=active]:bg-background data-[state=active]:shadow-sm data-[state=active]:border-b-2 data-[state=active]:border-primary hover:bg-background/50 transition-colors px-6"
          >
            공정진행현황
          </TabsTrigger>
        </TabsList>

        <TabsContent value="workOrder" className="space-y-4">
          <div className="text-center py-12 text-muted-foreground">
            <p className="text-lg">재고 생산 작업지시 데이터를 준비중입니다.</p>
          </div>
        </TabsContent>

        <TabsContent value="processProgress" className="space-y-4">
          <div className="text-center py-12 text-muted-foreground">
            <p className="text-lg">재고 생산 공정진행 데이터를 준비중입니다.</p>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}

export default ProductionManagement;