import React, { useState, useMemo, Fragment } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Checkbox } from "./ui/checkbox";
import { 
  Search, 
  Download, 
  Calendar, 
  Plus,
  ChevronLeft,
  ChevronRight,
  FileText,
  ClipboardCheck,
  Upload,
  X,
  CheckCircle,
  XCircle,
  Clock
} from "lucide-react";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";

interface QualityManagementProps {
  defaultTab?: "incoming" | "process" | "final" | "inspection";
}

export function QualityManagement({ defaultTab = "inspection" }: QualityManagementProps = {}) {
  const [mainTab, setMainTab] = useState(defaultTab);

  // Mock 대시보드 데이터
  const dashboardData = {
    totalInspections: 156,
    passRate: 94.2,
    failedCount: 9,
    inProgressCount: 5
  };

  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">
              <ClipboardCheck 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.totalInspections}건</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">
              <CheckCircle 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.passRate}%</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-red-500 to-red-600 rounded-lg flex items-center justify-center">
              <XCircle 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.failedCount}건</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">
              <Clock 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.inProgressCount}건</div>
            <p className="text-xs text-muted-foreground mt-1">
              검사 진행중
            </p>
          </CardContent>
        </Card>
      </div>

      {/* 메인 탭 */}
      <Card>
        <CardContent className="p-6">
          <Tabs value={mainTab} onValueChange={setMainTab} className="w-full">
            <TabsList className="w-full md:w-auto">
              <TabsTrigger value="inspection">제품 검사현황</TabsTrigger>
              <TabsTrigger value="schedule">월간 검사 일정</TabsTrigger>
            </TabsList>

            {/* 제품 검사현황 탭 */}
            <TabsContent value="inspection" className="space-y-4">
              <ProductInspectionStatus />
            </TabsContent>

            {/* 월간 검사 일정 탭 */}
            <TabsContent value="schedule" className="space-y-4">
              <MonthlyInspectionSchedule />
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
    </div>
  );
}

// 제품 검사현황 컴포넌트
function ProductInspectionStatus() {
  const [selectedStatus, setSelectedStatus] = useState("전체");
  const [selectedDelivery, setSelectedDelivery] = useState("납품일");
  const [selectedDate, setSelectedDate] = useState("8/12/2018");
  const [searchTerm, setSearchTerm] = useState("");
  const [finishedProductOnly, setFinishedProductOnly] = useState(false);
  const [selectedInspection, setSelectedInspection] = useState<any>(null);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [isRequestModalOpen, setIsRequestModalOpen] = useState(false);
  const [isDeliveryConfirmOpen, setIsDeliveryConfirmOpen] = useState(false);
  const [isScheduleModalOpen, setIsScheduleModalOpen] = useState(false);
  const [isTestReportOpen, setIsTestReportOpen] = useState(false);

  // 검사 데이터
  const inspectionData = [
    {
      no: 4,
      status: "대기",
      buyer: "명보에스티",
      siteName: "양산중학교 3동",
      setId: "",
      lotCount: 1,
      totalQty: 10,
      requestDate: "",
      scheduledDate: "",
      inspectionDate: "",
      deliveryRate: "",
      finalJudgment: "",
      updateDate: "",
      note: "[상태]"
    },
    {
      no: 3,
      status: "대기",
      buyer: "명보에스티",
      siteName: "양산중학교 2동",
      setId: "",
      lotCount: 1,
      totalQty: 20,
      requestDate: "",
      scheduledDate: "",
      inspectionDate: "",
      deliveryRate: "",
      finalJudgment: "",
      updateDate: "",
      note: "[상태]"
    },
    {
      no: 2,
      status: "대기",
      buyer: "명보에스티",
      siteName: "양산중학교 1동",
      setId: "",
      lotCount: 1,
      totalQty: 20,
      requestDate: "",
      scheduledDate: "",
      inspectionDate: "",
      deliveryRate: "",
      finalJudgment: "",
      updateDate: "",
      note: "[상태]"
    },
    {
      no: 1,
      status: "일정확정",
      buyer: "명보에스티",
      siteName: "양산중학교",
      setId: "SET-250812",
      lotCount: 3,
      totalQty: 50,
      requestDate: "08-12",
      scheduledDate: "08-16",
      inspectionDate: "김검사",
      deliveryRate: "10%",
      finalJudgment: "합격",
      updateDate: "08-13",
      note: "[상태]"
    }
  ];

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      "대기": "bg-gray-100 text-gray-700",
      "일정확정": "bg-blue-100 text-blue-700",
      "검사중": "bg-yellow-100 text-yellow-700",
      "완료": "bg-green-100 text-green-700"
    };
    return colors[status] || "bg-gray-100 text-gray-700";
  };

  return (
    <div className="space-y-4">
      {/* 상단 필터 영역 */}
      <div className="flex flex-col md:flex-row gap-4 items-start md:items-end justify-between">
        {/* 필터 그룹 */}
        <div className="flex flex-wrap items-end gap-3">
          {/* 상태 선택 */}
          <div className="space-y-1">
            <Select value={selectedStatus} onValueChange={setSelectedStatus}>
              <SelectTrigger className="w-32 h-9">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="전체">전체</SelectItem>
                <SelectItem value="대기">대기</SelectItem>
                <SelectItem value="일정확정">일정확정</SelectItem>
                <SelectItem value="검사중">검사중</SelectItem>
                <SelectItem value="완료">완료</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 납품일 선택 */}
          <div className="space-y-1">
            <Select value={selectedDelivery} onValueChange={setSelectedDelivery}>
              <SelectTrigger className="w-32 h-9">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="납품일">납품일</SelectItem>
                <SelectItem value="요청일">요청일</SelectItem>
                <SelectItem value="검사일">검사일</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 날짜 선택 */}
          <div className="flex items-center gap-2 border rounded-md px-3 py-1.5 h-9">
            <Input 
              type="text" 
              value={selectedDate}
              onChange={(e) => setSelectedDate(e.target.value)}
              className="border-0 p-0 h-auto focus-visible:ring-0 w-24 text-sm"
            />
            <Calendar className="h-4 w-4 text-muted-foreground" />
          </div>
        </div>

        {/* 검색 및 체크박스 */}
        <div className="flex items-center gap-3 w-full md:w-auto">
          <div className="relative flex-1 md:w-64">
            <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 className="flex items-center space-x-2 whitespace-nowrap">
            <Checkbox 
              id="finished-only"
              checked={finishedProductOnly}
              onCheckedChange={(checked) => setFinishedProductOnly(checked as boolean)}
            />
            <label
              htmlFor="finished-only"
              className="text-sm font-medium leading-none cursor-pointer"
            >
              완성제품만
            </label>
          </div>
        </div>
      </div>

      {/* 데스크톱 테이블 */}
      <div className="hidden lg:block border rounded-lg overflow-hidden">
        <Table>
          <TableHeader>
            <TableRow className="bg-muted/50">
              <TableHead className="text-center w-12">체크</TableHead>
              <TableHead className="text-center w-16">번호</TableHead>
              <TableHead className="text-center w-24">상태</TableHead>
              <TableHead className="text-center w-32">발주처</TableHead>
              <TableHead className="text-center">현장명</TableHead>
              <TableHead className="text-center w-32">Set_ID</TableHead>
              <TableHead className="text-center w-20">로트수</TableHead>
              <TableHead className="text-center w-20">총개수</TableHead>
              <TableHead className="text-center w-24">요청일</TableHead>
              <TableHead className="text-center w-24">예정일</TableHead>
              <TableHead className="text-center w-24">검사일</TableHead>
              <TableHead className="text-center w-24">전달율</TableHead>
              <TableHead className="text-center w-24">최종<br/>판정</TableHead>
              <TableHead className="text-center w-24">업데이<br/>트</TableHead>
              <TableHead className="text-center w-20">...</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {inspectionData.map((item) => (
              <TableRow key={item.no} className="hover:bg-muted/30">
                <TableCell className="text-center">
                  <Checkbox />
                </TableCell>
                <TableCell className="text-center text-sm">{item.no}</TableCell>
                <TableCell className="text-center">
                  <Badge 
                    className={`${getStatusColor(item.status)} border-0 text-xs cursor-pointer hover:opacity-80`}
                    onClick={() => {
                      setSelectedInspection(item);
                      setIsDetailModalOpen(true);
                    }}
                  >
                    {item.status}
                  </Badge>
                </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.setId}</TableCell>
                <TableCell className="text-center text-sm">{item.lotCount || "-"}</TableCell>
                <TableCell className="text-center text-sm">{item.totalQty}</TableCell>
                <TableCell className="text-center text-sm">{item.requestDate}</TableCell>
                <TableCell className="text-center text-sm">{item.scheduledDate}</TableCell>
                <TableCell className="text-center text-sm">{item.inspectionDate}</TableCell>
                <TableCell className="text-center text-sm">{item.deliveryRate}</TableCell>
                <TableCell className="text-center text-sm">{item.finalJudgment}</TableCell>
                <TableCell className="text-center text-sm">{item.updateDate}</TableCell>
                <TableCell className="text-center text-sm text-blue-600 cursor-pointer">
                  {item.note}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      {/* 모바일 카드 */}
      <div className="lg:hidden space-y-3">
        {inspectionData.map((item) => (
          <Card key={item.no}>
            <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">
                    <Checkbox />
                    <span className="text-xs text-muted-foreground">No. {item.no}</span>
                    <Badge 
                      className={`${getStatusColor(item.status)} border-0 text-xs cursor-pointer hover:opacity-80`}
                      onClick={() => {
                        setSelectedInspection(item);
                        setIsDetailModalOpen(true);
                      }}
                    >
                      {item.status}
                    </Badge>
                  </div>
                  <div className="font-semibold">{item.siteName}</div>
                  <div className="text-sm text-muted-foreground">{item.buyer}</div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-2 text-sm">
                <div>
                  <span className="text-muted-foreground">Set ID: </span>
                  <span className="font-medium">{item.setId || "-"}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">로트수: </span>
                  <span className="font-medium">{item.lotCount || "-"}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">총개수: </span>
                  <span className="font-medium">{item.totalQty}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">전달율: </span>
                  <span className="font-medium">{item.deliveryRate || "-"}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">요청일: </span>
                  <span className="font-medium">{item.requestDate || "-"}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">예정일: </span>
                  <span className="font-medium">{item.scheduledDate || "-"}</span>
                </div>
              </div>

              {item.finalJudgment && (
                <div className="pt-2 border-t">
                  <span className="text-sm text-muted-foreground">최종판정: </span>
                  <span className="text-sm font-medium text-green-600">{item.finalJudgment}</span>
                </div>
              )}
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 페이지네이션 */}
      <div className="flex items-center justify-center gap-2 pt-4">
        <Button variant="ghost" size="sm">
          <ChevronLeft className="h-4 w-4" />
        </Button>
        <Button variant="ghost" size="sm" className="text-blue-600">1</Button>
        <Button variant="ghost" size="sm">2</Button>
        <Button variant="ghost" size="sm">3</Button>
        <Button variant="ghost" size="sm">4</Button>
        <span className="px-2">...</span>
        <Button variant="ghost" size="sm">9</Button>
        <Button variant="ghost" size="sm">10</Button>
        <Button variant="ghost" size="sm">
          <ChevronRight className="h-4 w-4" />
        </Button>
      </div>

      {/* 하단 버튼 그룹 */}
      <div className="flex flex-wrap items-center justify-end gap-3 pt-4 border-t">
        <Button 
          variant="outline" 
          className="h-9"
          onClick={() => setIsRequestModalOpen(true)}
        >
          요청등록/수정
        </Button>
        <Button 
          variant="outline" 
          className="h-9"
          onClick={() => setIsDeliveryConfirmOpen(true)}
        >
          남품확인서 발행
        </Button>
        <Button 
          variant="outline" 
          className="h-9"
          onClick={() => setIsScheduleModalOpen(true)}
        >
          검사입장등록
        </Button>
        <Button 
          variant="outline" 
          className="h-9"
          onClick={() => setIsTestReportOpen(true)}
        >
          검사성적서
        </Button>
      </div>

      {/* 검사 상세 정보 모달 */}
      <InspectionDetailModal 
        open={isDetailModalOpen}
        onOpenChange={setIsDetailModalOpen}
        inspection={selectedInspection}
      />

      {/* 요청서 작성 모달 */}
      <InspectionRequestModal 
        open={isRequestModalOpen}
        onOpenChange={setIsRequestModalOpen}
      />

      {/* 납품확인서 모달 */}
      <DeliveryConfirmationModal 
        open={isDeliveryConfirmOpen}
        onOpenChange={setIsDeliveryConfirmOpen}
      />

      {/* 검사일정등록 모달 */}
      <InspectionScheduleModal 
        open={isScheduleModalOpen}
        onOpenChange={setIsScheduleModalOpen}
      />

      {/* 검사성적서 모달 */}
      <TestReportModal 
        open={isTestReportOpen}
        onOpenChange={setIsTestReportOpen}
      />
    </div>
  );
}

// 검사 상세 정보 모달
interface InspectionDetailModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  inspection: any;
}

function InspectionDetailModal({ open, onOpenChange, inspection }: InspectionDetailModalProps) {
  if (!inspection) return null;

  // 로트 목록 데이터
  const lotList = [
    { no: 1, lotNo: "KD-SS-250703-03", deliveryDate: "7/5", qty: 20, itemType: "KSS02" },
    { no: 2, lotNo: "KD-SS-250716-04", deliveryDate: "7/20", qty: 20, itemType: "KSS02" },
    { no: 3, lotNo: "KD-ST-250720-01", deliveryDate: "7/22", qty: 10, itemType: "KQTS01" }
  ];

  // 로트별 품 구성 데이터
  const lotProducts = [
    {
      lotName: "로트1",
      lotNo: "KD-SS-250703-03",
      items: [
        { lotNo: "KD-SS-250703-03-01", openWidth: 3000, openHeight: 3000, estWidth: 3000, estHeight: 2700, status: "(수정) (재청)" },
        { lotNo: "KD-SS-250703-03-02", openWidth: 5500, openHeight: 4000, estWidth: 5500, estHeight: 4000, status: "(수정) (재청)" }
      ]
    },
    {
      lotName: "로트2",
      lotNo: "KD-SS-250716-04",
      items: [
        { lotNo: "KD-SS-250716-04-01", openWidth: 4000, openHeight: 4000, estWidth: 4000, estHeight: 4000, status: "(수정) (재청)" }
      ]
    }
  ];

  // 요청서 모약 데이터
  const requestSummary = [
    { requestDate: "08/20", changeReason: "검사일 변경요청", attachment: "📎" }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] max-h-[95vh] overflow-y-auto p-0">
        <DialogHeader className="px-6 pt-6 pb-4 border-b sticky top-0 bg-background z-10">
          <DialogTitle className="text-2xl">{inspection.siteName} - 검사 상세정보</DialogTitle>
          <DialogDescription className="sr-only">
            검사 요청의 상세 정보, 로트 목록, 문서 및 활동 로그를 확인할 수 있습니다.
          </DialogDescription>
        </DialogHeader>

        <div className="px-6 pb-6 space-y-6">
          {/* 1. 현장 기본정보 */}
          <div className="border rounded-lg p-4">
            <h3 className="font-semibold mb-3">1. 현장 기본정보</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="border rounded p-3">
                <div className="text-sm text-muted-foreground mb-1">주소</div>
                <div className="font-medium">광성도 양산시 56-3</div>
              </div>
              <div className="border rounded p-3">
                <div className="text-sm text-muted-foreground mb-1">발주처</div>
                <div className="font-medium">{inspection.buyer}</div>
              </div>
            </div>
          </div>

          {/* 2. 로트목록 */}
          <div className="border rounded-lg p-4">
            <h3 className="font-semibold mb-3">2. 로트목록</h3>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/50">
                    <TableHead className="text-center w-16">번호</TableHead>
                    <TableHead className="text-center">LOT NO.</TableHead>
                    <TableHead className="text-center w-24">납품일</TableHead>
                    <TableHead className="text-center w-20">개수</TableHead>
                    <TableHead className="text-center w-32">품목유형</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {lotList.map((lot) => (
                    <TableRow key={lot.no}>
                      <TableCell className="text-center">{lot.no}</TableCell>
                      <TableCell className="text-center text-sm">{lot.lotNo}</TableCell>
                      <TableCell className="text-center">{lot.deliveryDate}</TableCell>
                      <TableCell className="text-center">{lot.qty}</TableCell>
                      <TableCell className="text-center">{lot.itemType}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>

          {/* 3. 로트별품 구성 */}
          <div className="border rounded-lg p-4">
            <h3 className="font-semibold mb-3">3. 로트별품 구성</h3>
            <div className="space-y-4">
              {lotProducts.map((lot, idx) => (
                <div key={idx}>
                  <div className="bg-orange-100 px-3 py-2 font-medium text-sm mb-2 rounded">
                    {lot.lotName}
                  </div>
                  <div className="bg-orange-50 px-3 py-1 text-sm mb-2">
                    {lot.lotNo}
                  </div>
                  <div className="overflow-x-auto">
                    <Table>
                      <TableHeader>
                        <TableRow className="bg-muted/50">
                          <TableHead className="text-center w-12">
                            <X className="h-4 w-4 mx-auto" />
                          </TableHead>
                          <TableHead className="text-center">LOT NO.</TableHead>
                          <TableHead className="text-center" colSpan={2}>오픈사이즈</TableHead>
                          <TableHead className="text-center" colSpan={2}>추정사이즈</TableHead>
                          <TableHead className="text-center w-32">수정</TableHead>
                        </TableRow>
                        <TableRow className="bg-muted/30">
                          <TableHead></TableHead>
                          <TableHead></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></TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {lot.items.map((item, itemIdx) => (
                          <TableRow key={itemIdx}>
                            <TableCell className="text-center">
                              <X className="h-4 w-4 mx-auto cursor-pointer text-muted-foreground hover:text-red-600" />
                            </TableCell>
                            <TableCell className="text-center text-sm">{item.lotNo}</TableCell>
                            <TableCell className="text-center">{item.openWidth}</TableCell>
                            <TableCell className="text-center">{item.openHeight}</TableCell>
                            <TableCell className="text-center">{item.estWidth}</TableCell>
                            <TableCell className="text-center">{item.estHeight}</TableCell>
                            <TableCell className="text-center text-xs text-muted-foreground">
                              {item.status}
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 4. 요청서 모약 */}
          <div className="border rounded-lg p-4">
            <h3 className="font-semibold mb-3">4. 요청서 모약</h3>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/50">
                    <TableHead className="text-center w-32">요청일</TableHead>
                    <TableHead className="text-center">변경사유 여부</TableHead>
                    <TableHead className="text-center w-20">첨부</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {requestSummary.map((req, idx) => (
                    <TableRow key={idx}>
                      <TableCell className="text-center">{req.requestDate}</TableCell>
                      <TableCell className="text-center">{req.changeReason}</TableCell>
                      <TableCell className="text-center">
                        <Upload className="h-4 w-4 mx-auto cursor-pointer text-blue-600" />
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>

          {/* 5. 문서 */}
          <div className="border rounded-lg p-4">
            <h3 className="font-semibold mb-3">5. 문서</h3>
            <div className="flex flex-wrap gap-2">
              <Button variant="link" className="text-blue-600 p-0 h-auto">
                납품확인서 PDF ↓
              </Button>
              <span>|</span>
              <Button variant="link" className="text-blue-600 p-0 h-auto">
                납품확인서 재발행
              </Button>
              <span>|</span>
              <Button variant="link" className="text-blue-600 p-0 h-auto">
                검사성적서 양식보기
              </Button>
            </div>
          </div>

          {/* 6. 일정 */}
          <div className="border rounded-lg p-4">
            <h3 className="font-semibold mb-3">6. 일정</h3>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <Label className="text-sm text-muted-foreground mb-2 block">예정일</Label>
                <Select defaultValue="08-16">
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="08-16">08-16</SelectItem>
                    <SelectItem value="08-17">08-17</SelectItem>
                    <SelectItem value="08-18">08-18</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label className="text-sm text-muted-foreground mb-2 block">검사원</Label>
                <Select defaultValue="김검사">
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="김검사">김검사</SelectItem>
                    <SelectItem value="이검사">이검사</SelectItem>
                    <SelectItem value="박검사">박검사</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label className="text-sm text-muted-foreground mb-2 block">캘린더</Label>
                <Button variant="outline" className="w-full">
                  <Calendar className="h-4 w-4 mr-2" />
                  날짜 선택
                </Button>
              </div>
            </div>
          </div>

          {/* 7. 활동로그 */}
          <div className="border rounded-lg p-4">
            <h3 className="font-semibold mb-3">7. 활동로그</h3>
            <Textarea 
              placeholder="활동 내역이 여기에 표시됩니다..."
              className="min-h-[100px]"
              disabled
            />
          </div>

          {/* 하단 버튼 */}
          <div className="flex items-center justify-end gap-3 pt-4 border-t">
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              닫기
            </Button>
            <Button variant="outline">
              저장
            </Button>
            <Button className="bg-blue-600 hover:bg-blue-700">
              검사 확정
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 요청서 작성 모달
interface InspectionRequestModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

function InspectionRequestModal({ open, onOpenChange }: InspectionRequestModalProps) {
  const [selectedLots, setSelectedLots] = useState<string[]>([]);
  const [selectedProducts, setSelectedProducts] = useState<string[]>(["SS-250720-01-01"]);

  // 로트 선택 데이터
  const lotOptions = [
    { id: "lot1", label: "KD-SS-250720-01(10)", value: "KD-SS-250720-01" },
    { id: "lot2", label: "KD-SS-250730-04(10)", value: "KD-SS-250730-04" },
    { id: "lot3", label: "KD-SS-250731-01(30)", value: "KD-SS-250731-01" }
  ];

  // 제품 정보 데이터
  const productData = [
    { 
      id: "SS-250720-01-01", 
      lotNo: "SS-250720-01-01",
      sameSize: true,
      deliveryWidth: 3000,
      deliveryHeight: 3000,
      modifiedWidth: 3000,
      modifiedHeight: 3000,
      changeReason: ""
    },
    { 
      id: "SS-250720-01-02", 
      lotNo: "SS-250720-01-02",
      sameSize: false,
      deliveryWidth: 3000,
      deliveryHeight: 3000,
      modifiedWidth: 3000,
      modifiedHeight: 2500,
      changeReason: "설계등고 출어동"
    }
  ];

  // 주체 정보 데이터
  const participantData = [
    { role: "자재유통업자", name: "", company: "", address: "", phone: "" },
    { role: "시공자(감사상)", name: "", company: "", address: "", phone: "" },
    { role: "감리자", name: "", company: "", address: "", phone: "" },
    { role: "공사장", name: "현장명", company: "대지위치", address: "", phone: "지번" }
  ];

  const toggleLot = (lotId: string) => {
    setSelectedLots(prev => 
      prev.includes(lotId) 
        ? prev.filter(id => id !== lotId)
        : [...prev, lotId]
    );
  };

  const toggleProduct = (productId: string) => {
    setSelectedProducts(prev => 
      prev.includes(productId) 
        ? prev.filter(id => id !== productId)
        : [...prev, productId]
    );
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] max-h-[95vh] overflow-y-auto p-0">
        <DialogHeader className="px-6 pt-6 pb-4 border-b sticky top-0 bg-background z-10">
          <div className="flex items-center justify-between">
            <DialogTitle className="text-2xl">제품검사 요청서 작성</DialogTitle>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => onOpenChange(false)}
              className="h-8 w-8"
            >
              <X className="h-4 w-4" />
            </Button>
          </div>
          <DialogDescription className="sr-only">
            제품검사 요청서를 작성합니다. 기본 정보, 제품 정보, 주체 정보, 파일을 입력하세요.
          </DialogDescription>
        </DialogHeader>

        <div className="px-6 pb-6 space-y-6">
          {/* 1. 기본 정보 */}
          <div className="border rounded-lg p-4">
            <h3 className="font-semibold mb-3 text-lg">1. 기본 정보</h3>
            <div className="space-y-4">
              {/* 현장명 & 제품명 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label className="text-sm mb-2 block">현장명 :</Label>
                  <Input defaultValue="양산중학교" />
                </div>
                <div>
                  <Label className="text-sm mb-2 block">제품명 :</Label>
                  <Select defaultValue="KSS02">
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="KSS02">KSS02</SelectItem>
                      <SelectItem value="KQTS01">KQTS01</SelectItem>
                      <SelectItem value="KSS01">KSS01</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {/* 로드선택 */}
              <div>
                <div className="flex items-center gap-2 mb-2">
                  <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
                    1
                  </div>
                  <Label className="text-sm">로드선택 :</Label>
                  <Button variant="link" className="text-blue-600 p-0 h-auto text-sm">
                    생성
                  </Button>
                </div>
                <div className="flex flex-wrap gap-3 border rounded-md p-3">
                  {lotOptions.map((lot) => (
                    <div key={lot.id} className="flex items-center space-x-2">
                      <Checkbox 
                        id={lot.id}
                        checked={selectedLots.includes(lot.value)}
                        onCheckedChange={() => toggleLot(lot.value)}
                      />
                      <label
                        htmlFor={lot.id}
                        className="text-sm cursor-pointer"
                      >
                        {lot.label}
                      </label>
                    </div>
                  ))}
                </div>
              </div>

              {/* 로트묶음 번호 & 총 개수 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label className="text-sm mb-2 block">로트묶음 번호 :</Label>
                  <Input defaultValue="SET-250814-01" />
                </div>
                <div>
                  <Label className="text-sm mb-2 block">총 개수 :</Label>
                  <Input type="number" defaultValue="50" />
                </div>
              </div>
            </div>
          </div>

          {/* 2. 제품 정보 */}
          <div className="border rounded-lg p-4">
            <h3 className="font-semibold mb-3 text-lg">2. 제품 정보</h3>
            
            {/* 요청일 */}
            <div className="mb-4">
              <div className="flex items-center gap-2 mb-2">
                <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
                  2
                </div>
                <Label className="text-sm">요청일</Label>
              </div>
              <Input 
                type="date" 
                defaultValue="2025-08-14"
                className="max-w-xs"
              />
            </div>

            {/* 제품 정보 테이블 */}
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/50">
                    <TableHead className="text-center w-32">검사로트</TableHead>
                    <TableHead className="text-center w-32">
                      <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold mx-auto mb-1">
                        3
                      </div>
                      오픈사이즈<br/>동일여부
                    </TableHead>
                    <TableHead className="text-center" colSpan={2}>납품사이즈</TableHead>
                    <TableHead className="text-center" colSpan={2}>수정(시공중)사이즈</TableHead>
                    <TableHead className="text-center w-40">변경사유</TableHead>
                  </TableRow>
                  <TableRow className="bg-muted/30">
                    <TableHead></TableHead>
                    <TableHead></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></TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {productData.map((product) => (
                    <TableRow key={product.id}>
                      <TableCell className="text-center">
                        <div className="flex items-center gap-2">
                          <Checkbox 
                            checked={selectedProducts.includes(product.id)}
                            onCheckedChange={() => toggleProduct(product.id)}
                          />
                          <span className="text-sm">{product.lotNo}</span>
                        </div>
                      </TableCell>
                      <TableCell className="text-center">
                        <Checkbox checked={product.sameSize} />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input 
                          type="number" 
                          defaultValue={product.deliveryWidth}
                          className="h-8 w-20 text-center"
                        />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input 
                          type="number" 
                          defaultValue={product.deliveryHeight}
                          className="h-8 w-20 text-center"
                        />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input 
                          type="number" 
                          defaultValue={product.modifiedWidth}
                          className="h-8 w-20 text-center"
                        />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input 
                          type="number" 
                          defaultValue={product.modifiedHeight}
                          className="h-8 w-20 text-center"
                        />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input 
                          defaultValue={product.changeReason}
                          placeholder="변경사유 입력"
                          className="h-8 text-sm"
                        />
                      </TableCell>
                    </TableRow>
                  ))}
                  {/* 빈 행들 */}
                  {[1, 2, 3].map((i) => (
                    <TableRow key={`empty-${i}`}>
                      <TableCell className="text-center">
                        <Checkbox />
                      </TableCell>
                      <TableCell className="text-center">
                        <Checkbox />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input className="h-8 w-20 text-center" />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input className="h-8 w-20 text-center" />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input className="h-8 w-20 text-center" />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input className="h-8 w-20 text-center" />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input className="h-8 text-sm" />
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>

          {/* 3. 주체 정보 */}
          <div className="border rounded-lg p-4">
            <h3 className="font-semibold mb-3 text-lg">3. 주체 정보</h3>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/50">
                    <TableHead className="text-center w-32"></TableHead>
                    <TableHead className="text-center">성명</TableHead>
                    <TableHead className="text-center">회사명</TableHead>
                    <TableHead className="text-center">주소</TableHead>
                    <TableHead className="text-center">전화</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {participantData.map((participant, idx) => (
                    <TableRow key={idx} className={idx === participantData.length - 1 ? "bg-muted/30" : ""}>
                      <TableCell className="font-medium text-center">
                        {participant.role}
                      </TableCell>
                      <TableCell className="text-center">
                        <Input 
                          defaultValue={participant.name}
                          placeholder={participant.name || "입력"}
                          className="h-8"
                        />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input 
                          defaultValue={participant.company}
                          placeholder={participant.company || "입력"}
                          className="h-8"
                        />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input 
                          defaultValue={participant.address}
                          placeholder="입력"
                          className="h-8"
                        />
                      </TableCell>
                      <TableCell className="text-center">
                        <Input 
                          defaultValue={participant.phone}
                          placeholder={participant.phone || "입력"}
                          className="h-8"
                        />
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>

          {/* 4. 파일 */}
          <div className="border rounded-lg p-4">
            <div className="flex items-center gap-2 mb-3">
              <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
                4
              </div>
              <h3 className="font-semibold text-lg">4. 파일</h3>
              <Button variant="outline" size="sm" className="ml-auto">
                <Upload className="h-4 w-4 mr-2" />
                파일 업로드
              </Button>
            </div>
            <div className="border-2 border-dashed rounded-lg p-8 text-center text-muted-foreground">
              파일을 드래그하거나 업로드 버튼을 클릭하세요
            </div>
          </div>

          {/* 하단 버튼 */}
          <div className="flex items-center justify-end gap-3 pt-4 border-t">
            <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold mr-2">
              5
            </div>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              취소
            </Button>
            <Button className="bg-blue-600 hover:bg-blue-700">
              저장
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 납품확인서 모달
interface DeliveryConfirmationModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

function DeliveryConfirmationModal({ open, onOpenChange }: DeliveryConfirmationModalProps) {
  // 스크린 데이터
  const screenData = [
    {
      no: 1,
      type: "실리카",
      code: "FSS-01",
      openWidth: 6800,
      openHeight: 2700,
      width: 6960,
      height: 3050,
      guideType: "벽면형",
      shaft: 5,
      caseSize: "500*380",
      caseSpec: "380*180",
      motor: "300K",
      capacity: "SUS마감"
    },
    {
      no: 2,
      type: "실리카",
      code: "FSS-02",
      openWidth: 5000,
      openHeight: 2700,
      width: 5160,
      height: 3050,
      guideType: "벽면형",
      shaft: 4,
      caseSize: "500*380",
      caseSpec: "380*180",
      motor: "150K",
      capacity: "SUS마감"
    }
  ];

  // 케이스(서터박스) 데이터
  const caseData = [
    { no: 1, code: "FSS-01", size1219: "", size2438: 1, size3000: "", size3500: "", size4000: "", size4150: 1, quantity: 5, total: 6 },
    { no: 2, code: "FSS-02", size1219: 1, size2438: "", size3000: "", size3500: "", size4000: "", size4150: 1, quantity: 4, total: 5 }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] max-h-[95vh] overflow-y-auto p-0" aria-describedby="delivery-confirmation-description">
        <DialogHeader className="sr-only">
          <DialogTitle>납품확인서</DialogTitle>
          <DialogDescription id="delivery-confirmation-description">
            납품확인서 문서를 확인하고 발행할 수 있습니다.
          </DialogDescription>
        </DialogHeader>
        
        <div className="sticky top-0 bg-white z-10 border-b">
          {/* 상단 버튼 그룹 */}
          <div className="flex items-center justify-center gap-3 p-4">
            <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
              2
            </div>
            <Button variant="outline">
              PDF 미리보기
            </Button>
            <Button variant="outline">
              저장 & 발행
            </Button>
            <Button variant="outline">
              이메일보내기
            </Button>
            <Button variant="outline">
              재발행
            </Button>
          </div>
        </div>

        {/* 문서 컨텐츠 */}
        <div className="px-8 pb-8 bg-white">
          {/* 헤더 */}
          <div className="border-2 border-black mb-4">
            <div className="grid grid-cols-3 border-b-2 border-black">
              <div className="flex items-center justify-center p-4 border-r-2 border-black">
                <div className="text-center">
                  <div className="text-blue-600 font-bold text-2xl">KD</div>
                  <div className="text-xs">경동기업</div>
                </div>
              </div>
              <div className="flex items-center justify-center p-4 border-r-2 border-black">
                <h1 className="text-3xl font-bold">납 품 확 인 서</h1>
              </div>
              <div className="p-2">
                <div className="text-right mb-2">
                  <div className="text-xs">로드번호</div>
                  <div className="text-blue-600 font-bold">KD-SA-250717-01</div>
                </div>
                <div className="border border-black p-2">
                  <div className="text-center mb-1">
                    <div className="text-xs">결 재</div>
                    <div className="font-bold">경동기업</div>
                  </div>
                  <div className="flex items-center justify-center">
                    <div className="w-16 h-16 rounded-full border-2 border-red-500 flex items-center justify-center text-red-500 text-xs">
                      도장
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* 연락처 정보 */}
            <div className="text-center py-2 text-xs border-b border-black">
              전화 : 031-983-5130 | 팩스 : 02-6911-6315 | 이메일 : kd5130@naver.com
            </div>

            {/* 상품명 섹션 */}
            <div className="relative">
              <div className="absolute -left-8 top-8 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
                1
              </div>
              <div className="grid grid-cols-5 bg-gray-200">
                <div className="p-2 text-center font-semibold border-r border-black">상 품 명</div>
                <div className="p-2 text-center font-semibold border-r border-black">국민방재 스크린 센터</div>
                <div className="p-2 text-center font-semibold border-r border-black">제품명</div>
                <div className="p-2 text-center font-semibold border-r border-black">KSS02</div>
                <div className="p-2 text-center font-semibold">인결번호</div>
              </div>
              <div className="grid grid-cols-5 border-t border-black">
                <div className="p-2 text-center font-semibold border-r border-black"></div>
                <div className="p-2 text-center font-semibold border-r border-black"></div>
                <div className="p-2 text-center font-semibold border-r border-black"></div>
                <div className="p-2 text-center font-semibold border-r border-black"></div>
                <div className="p-2 text-center text-blue-600 font-bold">FDS-OTS25-0318-2</div>
              </div>
            </div>

            {/* 신청업체 & 신청내용 & 납품정보 */}
            <div className="border-t-2 border-black">
              <div className="grid grid-cols-3 bg-gray-200 border-b border-black">
                <div className="p-2 text-center font-semibold border-r border-black">신청업체</div>
                <div className="p-2 text-center font-semibold border-r border-black">신청내용</div>
                <div className="p-2 text-center font-semibold">납품정보</div>
              </div>

              <div className="grid grid-cols-6 text-sm">
                <div className="p-2 border-r border-b border-black bg-gray-100">발주일</div>
                <div className="p-2 border-r border-b border-black">2025년 7월 17일 목요일</div>
                <div className="p-2 border-r border-b border-black bg-gray-100">현장명</div>
                <div className="p-2 border-r border-b border-black text-blue-600">미정</div>
                <div className="p-2 border-r border-b border-black"></div>
                <div className="p-2 border-b border-black"></div>
              </div>

              <div className="grid grid-cols-6 text-sm">
                <div className="p-2 border-r border-b border-black bg-gray-100">발주처</div>
                <div className="p-2 border-r border-b border-black">중앙샷다</div>
                <div className="p-2 border-r border-b border-black bg-gray-100">납기요청일</div>
                <div className="p-2 border-r border-b border-black text-blue-600">2025년 8월 18일 월요일</div>
                <div className="p-2 border-r border-b border-black bg-gray-100">인수담당자</div>
                <div className="p-2 border-b border-black text-blue-600">손금주</div>
              </div>

              <div className="grid grid-cols-6 text-sm">
                <div className="p-2 border-r border-b border-black bg-gray-100">발주 담당자</div>
                <div className="p-2 border-r border-b border-black">손금주</div>
                <div className="p-2 border-r border-b border-black bg-gray-100">출고일</div>
                <div className="p-2 border-r border-b border-black text-blue-600">2025년 7월 17일 목요일</div>
                <div className="p-2 border-r border-b border-black bg-gray-100">인수자연락처</div>
                <div className="p-2 border-b border-black text-blue-600">010-7756-9069</div>
              </div>

              <div className="grid grid-cols-6 text-sm">
                <div className="p-2 border-r border-b border-black bg-gray-100">담당자 연락처</div>
                <div className="p-2 border-r border-b border-black">010-7756-9069</div>
                <div className="p-2 border-r border-b border-black bg-gray-100">세터홀수량</div>
                <div className="p-2 border-r border-b border-black">2 (개소)</div>
                <div className="p-2 border-r border-b border-black bg-gray-100">배 송 방 법</div>
                <div className="p-2 border-b border-black">상차(선불)</div>
              </div>

              <div className="p-2 border-b border-black bg-gray-100">
                배송지 주소
              </div>
            </div>
          </div>

          {/* 1. 스크린 */}
          <div className="mb-6">
            <h3 className="font-bold mb-2">1. 스크린</h3>
            <div className="border-2 border-black overflow-x-auto">
              <table className="w-full text-xs">
                <thead>
                  <tr className="bg-yellow-100">
                    <th rowSpan={2} className="border border-black p-1">원견<br/>번호</th>
                    <th rowSpan={2} className="border border-black p-1">종류</th>
                    <th rowSpan={2} className="border border-black p-1">종 부 호</th>
                    <th colSpan={2} className="border border-black p-1">
                      <div>오픈(mm)</div>
                      <div className="text-red-600 text-xs">*해당 너비 120</div>
                    </th>
                    <th colSpan={2} className="border border-black p-1">제작사이즈(mm)</th>
                    <th rowSpan={2} className="border border-black p-1">가이드레일<br/>유형</th>
                    <th rowSpan={2} className="border border-black p-1">샤프트<br/>(인치)</th>
                    <th rowSpan={2} className="border border-black p-1">케이스<br/>(규격)</th>
                    <th colSpan={2} className="border border-black p-1">모터</th>
                    <th rowSpan={2} className="border border-black p-1">마감</th>
                  </tr>
                  <tr className="bg-yellow-100">
                    <th className="border border-black p-1">가로</th>
                    <th className="border border-black p-1">세로</th>
                    <th className="border border-black p-1 text-red-600">가로<br/>(오픈+160)</th>
                    <th className="border border-black p-1 text-red-600">세로<br/>(오픈+350)</th>
                    <th className="border border-black p-1">보라켓<br/>W80</th>
                    <th className="border border-black p-1">용량<br/>(KG)</th>
                  </tr>
                </thead>
                <tbody>
                  {screenData.map((item) => (
                    <tr key={item.no}>
                      <td className="border border-black p-1 text-center">{item.no}</td>
                      <td className="border border-black p-1 text-center">{item.type}</td>
                      <td className="border border-black p-1 text-center">{item.code}</td>
                      <td className="border border-black p-1 text-center">{item.openWidth}</td>
                      <td className="border border-black p-1 text-center">{item.openHeight}</td>
                      <td className="border border-black p-1 text-center">{item.width}</td>
                      <td className="border border-black p-1 text-center">{item.height}</td>
                      <td className="border border-black p-1 text-center">{item.guideType}</td>
                      <td className="border border-black p-1 text-center">{item.shaft}</td>
                      <td className="border border-black p-1 text-center">{item.caseSize}</td>
                      <td className="border border-black p-1 text-center">{item.caseSpec}</td>
                      <td className="border border-black p-1 text-center">{item.motor}</td>
                      <td className="border border-black p-1 text-center">{item.capacity}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* 2. 부호별 절곡, 무자재 내역 */}
          <div className="mb-6">
            <h3 className="font-bold mb-2">2. 부호별 절곡, 무자재 내역</h3>
            
            {/* 2-1. 가이드레일 */}
            <div className="mb-4">
              <div className="bg-blue-100 p-2 font-semibold text-sm mb-2">
                2-1. 가이드레일 - EGI 1.55T + 마감재 EGI 1.15T + 볼드마감재 SUS 1.15T
              </div>
              <div className="border-2 border-black overflow-x-auto">
                <table className="w-full text-xs">
                  <thead>
                    <tr className="bg-blue-100">
                      <th rowSpan={2} className="border border-black p-1">원견<br/>번호</th>
                      <th rowSpan={2} className="border border-black p-1">종 부호</th>
                      <th colSpan={6} className="border border-black p-1">케이스(세터박스)</th>
                      <th rowSpan={2} className="border border-black p-1">케이스홈<br/>연기반단재<br/>W80</th>
                      <th rowSpan={2} className="border border-black p-1">상부덮개<br/>(1219<br/>*380)</th>
                    </tr>
                    <tr className="bg-blue-100">
                      <th className="border border-black p-1">1219</th>
                      <th className="border border-black p-1">2438</th>
                      <th className="border border-black p-1">3000</th>
                      <th className="border border-black p-1">3500</th>
                      <th className="border border-black p-1">4000</th>
                      <th className="border border-black p-1">4150</th>
                    </tr>
                  </thead>
                  <tbody>
                    {caseData.map((item) => (
                      <tr key={item.no}>
                        <td className="border border-black p-1 text-center">{item.no}</td>
                        <td className="border border-black p-1 text-center">{item.code}</td>
                        <td className="border border-black p-1 text-center">{item.size1219 || ""}</td>
                        <td className="border border-black p-1 text-center">{item.size2438 || ""}</td>
                        <td className="border border-black p-1 text-center">{item.size3000 || ""}</td>
                        <td className="border border-black p-1 text-center">{item.size3500 || ""}</td>
                        <td className="border border-black p-1 text-center">{item.size4000 || ""}</td>
                        <td className="border border-black p-1 text-center">{item.size4150 || ""}</td>
                        <td className="border border-black p-1 text-center">{item.quantity}</td>
                        <td className="border border-black p-1 text-center">{item.total}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          {/* 닫기 버튼 */}
          <div className="flex justify-center mt-6">
            <Button onClick={() => onOpenChange(false)} className="w-32">
              닫기
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 검사일정등록 모달 (검사원 배정 & 일정확정)
interface InspectionScheduleModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

function InspectionScheduleModal({ open, onOpenChange }: InspectionScheduleModalProps) {
  const [selectedInspector, setSelectedInspector] = useState("김검사");
  const [inspectionDate, setInspectionDate] = useState("2018-08-12");
  const [inspectionLocation, setInspectionLocation] = useState("");
  const [autoGenerateReport, setAutoGenerateReport] = useState(false);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-xl">
        <DialogHeader className="border-b pb-4">
          <DialogTitle className="text-2xl">검사원 배정 & 일정확정</DialogTitle>
          <DialogDescription>
            검사원을 배정하고 검사 일정을 확정합니다.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6 py-6">
          {/* 검사원 선택 */}
          <div className="grid grid-cols-[120px_1fr] items-center gap-4">
            <Label className="text-right">검사원 :</Label>
            <Select value={selectedInspector} onValueChange={setSelectedInspector}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="김검사">김검사</SelectItem>
                <SelectItem value="이검사">이검사</SelectItem>
                <SelectItem value="박검사">박검사</SelectItem>
                <SelectItem value="최검사">최검사</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* 검사날짜 */}
          <div className="grid grid-cols-[120px_1fr] items-center gap-4">
            <Label className="text-right">검사날짜 :</Label>
            <Input 
              type="date" 
              value={inspectionDate}
              onChange={(e) => setInspectionDate(e.target.value)}
              className="max-w-md"
            />
          </div>

          {/* 검사장소 */}
          <div className="grid grid-cols-[120px_1fr] items-center gap-4">
            <Label className="text-right">검사장소 :</Label>
            <div className="flex items-center gap-2">
              <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold flex-shrink-0">
                1
              </div>
              <Input 
                placeholder="네이버지도 링크"
                value={inspectionLocation}
                onChange={(e) => setInspectionLocation(e.target.value)}
              />
            </div>
          </div>

          {/* 성적서 자동생성 */}
          <div className="grid grid-cols-[120px_1fr] items-center gap-4">
            <div></div>
            <div className="flex items-center gap-2">
              <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold flex-shrink-0">
                2
              </div>
              <Checkbox 
                id="auto-generate"
                checked={autoGenerateReport}
                onCheckedChange={(checked) => setAutoGenerateReport(checked as boolean)}
              />
              <label
                htmlFor="auto-generate"
                className="text-sm text-muted-foreground cursor-pointer"
              >
                성적서 자동생성(개소 50)
              </label>
            </div>
          </div>
        </div>

        {/* 하단 버튼 */}
        <div className="flex items-center justify-end gap-3 border-t pt-4">
          <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold mr-2">
            3
          </div>
          <Button 
            variant="outline"
            onClick={() => onOpenChange(false)}
          >
            닫기
          </Button>
          <Button>
            저장
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 제품검사성적서 모달
interface TestReportModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

function TestReportModal({ open, onOpenChange }: TestReportModalProps) {
  const [currentPage, setCurrentPage] = useState(1);
  const [judgmentResult, setJudgmentResult] = useState("부적합");
  const [reinspectionDate, setReinspectionDate] = useState("2018-08-12");
  const [rejectionReason, setRejectionReason] = useState("");

  // 검사항목 데이터
  const inspectionItems = [
    {
      category: "결모양",
      items: [
        { type: "가공상태", standard: "사용상 해로운 결함이 없을 것", method: "", result: { pass: true, fail: false } },
        { type: "재봉상태", standard: "내화성에 의해 견고하게 접합되어야 함", method: "", result: { pass: true, fail: false } },
        { type: "조립상태", standard: "엔드바의 견고하게 조립되어야 함", method: "", result: { pass: true, fail: false } },
        { type: "연기차단재", standard: "연기차단재 철저여부(케이스 W80, 가이드레일 W50(양쪽설치))", method: "육안검사", result: { pass: true, fail: false } },
        { type: "화단마감재", standard: "내부 무개별성 설치 유무", method: "", result: { pass: true, fail: false } }
      ]
    },
    {
      category: "모터",
      items: [
        { type: "", standard: "안정적용과 동일상황", method: "", result: { pass: true, fail: false } }
      ]
    },
    {
      category: "재질",
      items: [
        { type: "", standard: "WY-SC780 인쇄상태 확인", method: "", result: { pass: true, fail: false } }
      ]
    },
    {
      category: "치수\n(오픈사이즈)",
      items: [
        { type: "길이", standard: "발주치수 ± 30mm", method: "", result: { pass: true, fail: false, value: "측정값(    )" } },
        { type: "높이", standard: "발주치수 ± 30mm", method: "", result: { pass: true, fail: false, value: "측정값(    )" } },
        { type: "가이드레일\n중간치", standard: "10 ± 5mm(측정부위 : ⓐ 높이 100 이내)", method: "제근검사", result: { pass: true, fail: false, value: "측정값(    )" } },
        { type: "허단마감재간격", standard: "간격 (ⓑ+ⓒ)", standard: "가이드레일과 허단마감재 틈새 25mm 이내", method: "", result: { pass: true, fail: false, value: "측정값(    )" } }
      ]
    },
    {
      category: "착동테스트",
      items: [
        { type: "개폐성능", standard: "착동 유무 확인(일부 및 전진테체)", method: "착동테스트", result: { pass: true, fail: false } }
      ]
    }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] max-h-[95vh] overflow-y-auto p-0">
        <DialogHeader className="sr-only">
          <DialogTitle>제품검사성적서</DialogTitle>
          <DialogDescription>
            제품검사 성적서를 확인하고 판정 결과를 입력할 수 있습니다.
          </DialogDescription>
        </DialogHeader>

        {/* 상단 페이지 네비게이션 */}
        <div className="sticky top-0 bg-white z-10 border-b px-6 py-4">
          <div className="flex items-center justify-between">
            <h2 className="text-xl font-bold">제품검사성적서</h2>
            <div className="flex items-center gap-2">
              <Button
                variant="ghost"
                size="icon"
                onClick={() => onOpenChange(false)}
                className="h-8 w-8"
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
          </div>
          
          {/* 페이지 네비게이션 */}
          <div className="flex items-center justify-center gap-2 mt-3">
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8"
              onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
              disabled={currentPage === 1}
            >
              <ChevronLeft className="h-4 w-4" />
            </Button>
            <span className="text-sm text-blue-600 font-medium">
              {currentPage} / 50
            </span>
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8"
              onClick={() => setCurrentPage(Math.min(50, currentPage + 1))}
              disabled={currentPage === 50}
            >
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>

        <div className="px-6 pb-6 space-y-6">
          {/* 기본정보 섹션 */}
          <div className="border-2 border-gray-300 rounded-lg overflow-hidden">
            <div className="bg-gray-50 px-4 py-2 border-b border-gray-300">
              <div className="flex items-center gap-2">
                <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
                  1
                </div>
                <h3 className="font-semibold">※ 기본정보</h3>
              </div>
            </div>

            <div className="p-0">
              <Table>
                <TableBody>
                  <TableRow>
                    <TableCell className="bg-gray-100 font-semibold w-32 text-center border">문서번호</TableCell>
                    <TableCell className="border italic">KDOS-03-01-001</TableCell>
                    <TableCell className="bg-gray-100 font-semibold w-32 text-center border">상품명(모델명)</TableCell>
                    <TableCell className="border italic">국민방화스 텐서더(KTE01)</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="bg-gray-100 font-semibold text-center border">개소별 LOT</TableCell>
                    <TableCell className="border italic">KD-TE-250303-01</TableCell>
                    <TableCell className="bg-gray-100 font-semibold text-center border">로트크기</TableCell>
                    <TableCell className="border italic">01/07</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="bg-gray-100 font-semibold text-center border">거래처</TableCell>
                    <TableCell className="border italic">(주)에스 디아이엔씨</TableCell>
                    <TableCell className="bg-gray-100 font-semibold text-center border">개소위치</TableCell>
                    <TableCell className="border">
                      <span className="text-blue-600 underline cursor-pointer">1층 계단(안보고유관)</span>
                    </TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="bg-gray-100 font-semibold text-center border">현장명</TableCell>
                    <TableCell colSpan={3} className="border italic">22-욱-00부대시설공사(1225)</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="bg-gray-100 font-semibold text-center border">검사일</TableCell>
                    <TableCell className="border">
                      <div className="flex items-center gap-2">
                        <Input type="date" defaultValue="2018-08-12" className="w-40 h-8" />
                        <Calendar className="h-4 w-4 text-muted-foreground" />
                      </div>
                    </TableCell>
                    <TableCell className="bg-gray-100 font-semibold text-center border">검사원</TableCell>
                    <TableCell className="border">
                      <Select defaultValue="inspector">
                        <SelectTrigger className="w-full h-8">
                          <SelectValue placeholder="검사자" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="inspector">검사자</SelectItem>
                          <SelectItem value="kim">김검사</SelectItem>
                          <SelectItem value="lee">이검사</SelectItem>
                        </SelectContent>
                      </Select>
                    </TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </div>
          </div>

          {/* 검사항목 테이블 */}
          <div className="border-2 border-gray-300 rounded-lg overflow-hidden">
            <div className="bg-blue-100 px-4 py-2 border-b border-gray-300">
              <div className="flex items-center gap-2">
                <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
                  2
                </div>
                <h3 className="font-semibold">검사항목</h3>
              </div>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full border-collapse text-sm">
                <thead>
                  <tr className="bg-blue-100">
                    <th className="border border-gray-400 p-2 text-center w-24">검사항목</th>
                    <th className="border border-gray-400 p-2 text-center w-32"></th>
                    <th className="border border-gray-400 p-2 text-center">검사기준</th>
                    <th className="border border-gray-400 p-2 text-center w-24">검사방법</th>
                    <th className="border border-gray-400 p-2 text-center w-32">판정</th>
                  </tr>
                </thead>
                <tbody>
                  {inspectionItems.map((section, sectionIdx) => (
                    <React.Fragment key={sectionIdx}>
                      {section.items.map((item, itemIdx) => (
                        <tr key={`${sectionIdx}-${itemIdx}`}>
                          {itemIdx === 0 && (
                            <td 
                              className="border border-gray-400 p-2 text-center font-semibold bg-gray-50 align-top whitespace-pre-line"
                              rowSpan={section.items.length}
                            >
                              {section.category}
                            </td>
                          )}
                          <td className="border border-gray-400 p-2 text-center whitespace-pre-line">{item.type}</td>
                          <td className="border border-gray-400 p-2">{item.standard}</td>
                          <td className="border border-gray-400 p-2 text-center">{item.method}</td>
                          <td className="border border-gray-400 p-2">
                            <div className="flex items-center justify-center gap-3">
                              <div className="flex items-center gap-1">
                                <Checkbox id={`pass-${sectionIdx}-${itemIdx}`} checked={item.result.pass} />
                                <label htmlFor={`pass-${sectionIdx}-${itemIdx}`} className="text-sm cursor-pointer">
                                  적합
                                </label>
                              </div>
                              <div className="flex items-center gap-1">
                                <Checkbox id={`fail-${sectionIdx}-${itemIdx}`} checked={item.result.fail} />
                                <label htmlFor={`fail-${sectionIdx}-${itemIdx}`} className="text-sm cursor-pointer">
                                  부적합
                                </label>
                              </div>
                            </div>
                            {item.result.value && (
                              <div className="mt-1 text-xs text-center text-muted-foreground">
                                {item.result.value}
                              </div>
                            )}
                          </td>
                        </tr>
                      ))}
                    </React.Fragment>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* 첨부 섹션 */}
          <div className="border-2 border-gray-300 rounded-lg overflow-hidden">
            <div className="bg-gray-50 px-4 py-2 border-b border-gray-300">
              <div className="flex items-center gap-2">
                <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
                  1
                </div>
                <h3 className="font-semibold">※ 첨부</h3>
              </div>
            </div>

            <div className="p-4">
              <div className="grid grid-cols-3 gap-4">
                {[1, 2, 3].map((idx) => (
                  <div 
                    key={idx}
                    className="border-2 border-dashed border-gray-300 rounded-lg aspect-video flex items-center justify-center bg-gray-50 hover:bg-gray-100 cursor-pointer transition-colors"
                  >
                    <div className="text-center text-muted-foreground">
                      <div className="w-12 h-12 mx-auto mb-2 border-2 border-gray-300 rounded flex items-center justify-center">
                        <Upload className="h-6 w-6" />
                      </div>
                      <div className="text-xs">이미지 업로드</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* 종합 판정 */}
          <div className="border-2 border-gray-300 rounded-lg overflow-hidden">
            <div className="bg-gray-50 px-4 py-2 border-b border-gray-300">
              <div className="flex items-center gap-2">
                <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
                  2
                </div>
                <h3 className="font-semibold">※ 종합 판정 :</h3>
                <span className="text-3xl font-bold text-red-600 ml-4">부 적 합</span>
                <span className="text-sm text-muted-foreground ml-2">(사유 :</span>
                <Input 
                  className="flex-1 h-8"
                  placeholder="사유 입력"
                  value={rejectionReason}
                  onChange={(e) => setRejectionReason(e.target.value)}
                />
                <span className="text-sm text-muted-foreground">)</span>
              </div>
            </div>
          </div>

          {/* 재검예정일 */}
          <div className="border-2 border-gray-300 rounded-lg overflow-hidden">
            <div className="bg-gray-50 px-4 py-2">
              <div className="flex items-center gap-2">
                <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
                  3
                </div>
                <h3 className="font-semibold">재검예정일 :</h3>
                <Input 
                  type="date"
                  className="w-48 h-8 ml-2"
                  value={reinspectionDate}
                  onChange={(e) => setReinspectionDate(e.target.value)}
                />
                <Calendar className="h-4 w-4 text-muted-foreground" />
              </div>
            </div>
          </div>

          {/* 하단 버튼 */}
          <div className="flex items-center justify-end gap-3 pt-4 border-t">
            <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold mr-2">
              4
            </div>
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              취소
            </Button>
            <Button className="bg-blue-600 hover:bg-blue-700">
              저장
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 월간 검사 일정 컴포넌트
function MonthlyInspectionSchedule() {
  const [currentDate, setCurrentDate] = useState(new Date(2025, 7, 1)); // 2025년 8월
  const [searchTerm, setSearchTerm] = useState("");
  const [viewMode, setViewMode] = useState<"calendar" | "list">("calendar");
  const [selectedStatus, setSelectedStatus] = useState("상태");
  const [selectedProduct, setSelectedProduct] = useState("재품명");
  const [selectedInspector, setSelectedInspector] = useState("검사원");
  const [selectedJudgment, setSelectedJudgment] = useState("판정결과");
  const [isRejectionModalOpen, setIsRejectionModalOpen] = useState(false);
  const [selectedRejection, setSelectedRejection] = useState<any>(null);
  const [isPassModalOpen, setIsPassModalOpen] = useState(false);
  const [selectedPass, setSelectedPass] = useState<any>(null);

  // 검사 일정 샘플 데이터 (달력용)
  const scheduleData = [
    { 
      date: new Date(2025, 7, 4), 
      buyer: "이경호기업", 
      siteName: "이경호기업",
      productName: "KSS02",
      inspector: "김검사",
      location: "김검사, 제주도 서귀포시",
      color: "bg-purple-600"
    },
    { 
      date: new Date(2025, 7, 7), 
      buyer: "김포도서관", 
      siteName: "김포도서관",
      productName: "KSS02",
      inspector: "김검사",
      location: "김검사, 경기도 김포시 감사동",
      color: "bg-blue-600"
    },
    { 
      date: new Date(2025, 7, 20), 
      buyer: "황산동학교", 
      siteName: "황산동학교",
      productName: "KSS02",
      inspector: "김검사",
      location: "김검사, 경상남도 양산시 감사동7",
      color: "bg-yellow-500"
    },
  ];

  // 검사 결과 리스트 데이터
  const inspectionList = [
    {
      no: 3,
      status: "송인대기",
      buyer: "주원기업",
      siteName: "중북교목도서관",
      setId: "SET-250808",
      totalCount: 10,
      inspectionDate: "8/15",
      inspector: "김검사",
      location: "중북 청주시 서원구 충렬로 19",
      judgment: "대기",
      remarks: ""
    },
    {
      no: 2,
      status: "반려",
      buyer: "주원기업",
      siteName: "이경호기업",
      setId: "SET-250812",
      totalCount: 50,
      inspectionDate: "08/12",
      inspector: "김검사",
      location: "제주시 구좌읍 행원리 940",
      judgment: "부적합",
      remarks: "[성세보기]"
    },
    {
      no: 1,
      status: "송인완료",
      buyer: "제일자동문",
      siteName: "황덕중학교",
      setId: "SET-250728",
      totalCount: 1,
      inspectionDate: "8/10",
      inspector: "김검사",
      location: "제주 제주시 조천읍 일주동로 1234",
      judgment: "합격",
      remarks: "[상세보기]"
    }
  ];

  // 월 변경
  const changeMonth = (delta: number) => {
    setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() + delta, 1));
  };

  // 달력 데이터 생성
  const calendarData = useMemo(() => {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    
    const startDate = new Date(firstDay);
    startDate.setDate(startDate.getDate() - startDate.getDay());
    
    const endDate = new Date(lastDay);
    endDate.setDate(endDate.getDate() + (6 - endDate.getDay()));
    
    const dates = [];
    const current = new Date(startDate);
    
    while (current <= endDate) {
      dates.push(new Date(current));
      current.setDate(current.getDate() + 1);
    }
    
    const weeks = [];
    for (let i = 0; i < dates.length; i += 7) {
      weeks.push(dates.slice(i, i + 7));
    }
    
    return weeks;
  }, [currentDate]);

  // 특정 날짜의 일정 가져오기
  const getSchedulesForDate = (date: Date) => {
    return scheduleData.filter(schedule => {
      return schedule.date.getDate() === date.getDate() &&
             schedule.date.getMonth() === date.getMonth() &&
             schedule.date.getFullYear() === date.getFullYear();
    }).filter(schedule => {
      if (!searchTerm) return true;
      return schedule.buyer.toLowerCase().includes(searchTerm.toLowerCase()) ||
             schedule.siteName.toLowerCase().includes(searchTerm.toLowerCase());
    });
  };

  const isCurrentMonth = (date: Date) => {
    return date.getMonth() === currentDate.getMonth();
  };

  const dayNames = ['일', '월', '화', '수', '목', '금', '토'];

  return (
    <div className="space-y-4">
      {/* 상단 컨트롤 */}
      <div className="flex flex-col gap-4">
        {/* 필터와 검색 */}
        <div className="flex flex-col md:flex-row gap-3 items-start md:items-center justify-between">
          {/* 왼쪽: 필터 드롭다운들 */}
          <div className="flex items-center gap-2 flex-wrap">
            <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
              {viewMode === "calendar" ? "4" : "1"}
            </div>
            
            {viewMode === "calendar" ? (
              <>
                <Select value={selectedStatus} onValueChange={setSelectedStatus}>
                  <SelectTrigger className="w-32 h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="상태">상태</SelectItem>
                    <SelectItem value="대기">대기</SelectItem>
                    <SelectItem value="완료">완료</SelectItem>
                  </SelectContent>
                </Select>

                <Select value={selectedProduct} onValueChange={setSelectedProduct}>
                  <SelectTrigger className="w-32 h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="재품명">재품명</SelectItem>
                    <SelectItem value="KSS02">KSS02</SelectItem>
                    <SelectItem value="KQTS01">KQTS01</SelectItem>
                  </SelectContent>
                </Select>

                <Select value={selectedInspector} onValueChange={setSelectedInspector}>
                  <SelectTrigger className="w-32 h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="검사원">검사원</SelectItem>
                    <SelectItem value="김검사">김검사</SelectItem>
                    <SelectItem value="이검사">이검사</SelectItem>
                  </SelectContent>
                </Select>
              </>
            ) : (
              <>
                <Select value={selectedStatus} onValueChange={setSelectedStatus}>
                  <SelectTrigger className="w-32 h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="상태">상태</SelectItem>
                    <SelectItem value="송인대기">송인대기</SelectItem>
                    <SelectItem value="반려">반려</SelectItem>
                    <SelectItem value="송인완료">송인완료</SelectItem>
                  </SelectContent>
                </Select>

                <Select value={selectedInspector} onValueChange={setSelectedInspector}>
                  <SelectTrigger className="w-32 h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="검사원">검사원</SelectItem>
                    <SelectItem value="김검사">김검사</SelectItem>
                    <SelectItem value="이검사">이검사</SelectItem>
                  </SelectContent>
                </Select>

                <Select value={selectedJudgment} onValueChange={setSelectedJudgment}>
                  <SelectTrigger className="w-32 h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="판정결과">판정결과</SelectItem>
                    <SelectItem value="합격">합격</SelectItem>
                    <SelectItem value="부적합">부적합</SelectItem>
                    <SelectItem value="대기">대기</SelectItem>
                  </SelectContent>
                </Select>
              </>
            )}
          </div>

          {/* 오른쪽: 월 네비게이션, 검색, 뷰 전환 버튼 */}
          <div className="flex items-center gap-3 flex-wrap">
            {/* 월 네비게이션 */}
            <div className="flex items-center gap-2 bg-blue-100 rounded-lg px-3 py-1">
              <Button
                variant="ghost"
                size="icon"
                className="h-7 w-7"
                onClick={() => changeMonth(-1)}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <div className="font-semibold px-2 min-w-[100px] text-center">
                {currentDate.getFullYear()}/{String(currentDate.getMonth() + 1).padStart(2, '0')}
              </div>
              <Button
                variant="ghost"
                size="icon"
                className="h-7 w-7"
                onClick={() => changeMonth(1)}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>

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

            {/* 뷰 전환 버튼 */}
            <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
              {viewMode === "calendar" ? "1" : ""}
            </div>
            <Button
              variant="outline"
              onClick={() => setViewMode(viewMode === "calendar" ? "list" : "calendar")}
              className="h-9"
            >
              <Calendar className="h-4 w-4 mr-2" />
              {viewMode === "calendar" ? "검사 결과리스트" : "일정달력보기"}
            </Button>
          </div>
        </div>
      </div>

      {/* 달력 뷰 또는 리스트 뷰 */}
      {viewMode === "calendar" ? (
        <div className="border rounded-lg overflow-hidden">
          {/* 요일 헤더 */}
          <div className="grid grid-cols-7 bg-blue-600 text-white">
            {dayNames.map((day, index) => (
              <div
                key={day}
                className={`py-3 text-center font-semibold ${
                  index === 0 ? 'text-red-200' : index === 6 ? 'text-blue-200' : ''
                }`}
              >
                {day}
              </div>
            ))}
          </div>

          {/* 날짜 그리드 */}
          <div className="bg-white">
            {calendarData.map((week, weekIndex) => (
              <div key={weekIndex} className="grid grid-cols-7 border-b last:border-b-0">
                {week.map((date, dayIndex) => {
                  const schedules = getSchedulesForDate(date);
                  const isCurrentMonthDate = isCurrentMonth(date);
                  const isSunday = dayIndex === 0;
                  const isSaturday = dayIndex === 6;

                  return (
                    <div
                      key={date.toISOString()}
                      className={`border-r last:border-r-0 min-h-[120px] p-2 ${
                        !isCurrentMonthDate ? 'bg-gray-50' : ''
                      }`}
                    >
                      <div
                        className={`text-sm mb-2 font-semibold ${
                          !isCurrentMonthDate
                            ? 'text-gray-400'
                            : isSunday
                            ? 'text-red-600'
                            : isSaturday
                            ? 'text-blue-600'
                            : 'text-gray-700'
                        }`}
                      >
                        {date.getDate()}
                      </div>
                      {isCurrentMonthDate && schedules.length > 0 && (
                        <div className="space-y-1">
                          {schedules.map((schedule, idx) => (
                            <div
                              key={idx}
                              className={`${schedule.color} text-white p-2 rounded text-xs cursor-pointer hover:opacity-90 transition-opacity`}
                            >
                              <div className="font-medium">{schedule.buyer}</div>
                              <div className="opacity-90">{schedule.productName}</div>
                              <div className="opacity-90">{schedule.inspector}</div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            ))}
          </div>
        </div>
      ) : (
        /* 리스트 뷰 */
        <div className="space-y-4">
          <Card>
            <CardContent className="p-0">
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-gray-100">
                      <TableHead className="text-center w-12">
                        <Checkbox />
                      </TableHead>
                      <TableHead className="text-center w-16">번호</TableHead>
                      <TableHead className="text-center w-24">상태</TableHead>
                      <TableHead className="text-center">발주처</TableHead>
                      <TableHead className="text-center">현장명</TableHead>
                      <TableHead className="text-center">Set.ID</TableHead>
                      <TableHead className="text-center w-20">총개소</TableHead>
                      <TableHead className="text-center w-24">검사일</TableHead>
                      <TableHead className="text-center w-24">검사원</TableHead>
                      <TableHead className="text-center">위치</TableHead>
                      <TableHead className="text-center w-24">판정</TableHead>
                      <TableHead className="text-center w-32">사전<br/>미리보기</TableHead>
                      <TableHead className="text-center w-24">비고</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {inspectionList.map((item) => (
                      <TableRow key={item.no}>
                        <TableCell className="text-center">
                          <Checkbox />
                        </TableCell>
                        <TableCell className="text-center">{item.no}</TableCell>
                        <TableCell className="text-center">
                          <Badge 
                            variant={
                              item.status === "송인완료" ? "default" :
                              item.status === "반려" ? "destructive" :
                              "secondary"
                            }
                          >
                            {item.status}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-center">{item.buyer}</TableCell>
                        <TableCell className="text-center">{item.siteName}</TableCell>
                        <TableCell className="text-center">{item.setId}</TableCell>
                        <TableCell className="text-center">{item.totalCount}</TableCell>
                        <TableCell className="text-center">{item.inspectionDate}</TableCell>
                        <TableCell className="text-center">{item.inspector}</TableCell>
                        <TableCell className="text-center text-sm">{item.location}</TableCell>
                        <TableCell className="text-center">
                          <Badge
                            variant={
                              item.judgment === "합격" ? "default" :
                              item.judgment === "부적합" ? "destructive" :
                              "secondary"
                            }
                          >
                            {item.judgment}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-center">
                          <Button variant="ghost" size="icon" className="h-8 w-8">
                            <FileText className="h-4 w-4" />
                          </Button>
                        </TableCell>
                        <TableCell className="text-center">
                          {item.remarks && (
                            <Button 
                              variant="link" 
                              className="text-blue-600 p-0 h-auto text-xs"
                              onClick={() => {
                                if (item.judgment === "합격") {
                                  setSelectedPass(item);
                                  setIsPassModalOpen(true);
                                } else {
                                  setSelectedRejection(item);
                                  setIsRejectionModalOpen(true);
                                }
                              }}
                            >
                              {item.remarks}
                            </Button>
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>

          {/* 하단 버튼 */}
          <div className="flex items-center gap-3">
            <div className="bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center text-sm font-bold">
              2
            </div>
            <Button variant="outline">
              승인
            </Button>
            <Button variant="outline">
              반려
            </Button>
          </div>
        </div>
      )}

      {/* 반려사유 및 재검일정 모달 */}
      <RejectionReasonModal 
        open={isRejectionModalOpen}
        onOpenChange={setIsRejectionModalOpen}
        inspection={selectedRejection}
      />

      {/* 합격 상세보기 모달 */}
      <PassDetailModal 
        open={isPassModalOpen}
        onOpenChange={setIsPassModalOpen}
        inspection={selectedPass}
      />
    </div>
  );
}

// 반려사유 및 재검일정 모달
interface RejectionReasonModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  inspection: any;
}

function RejectionReasonModal({ open, onOpenChange, inspection }: RejectionReasonModalProps) {
  const [rejectionData, setRejectionData] = useState([
    {
      no: 1,
      siteName: "이경호기업관",
      rejectionReason: "사이즈오류",
      reinspectionDate: "2018-08-12",
      inspector: "검사원"
    },
    {
      no: 2,
      siteName: "",
      rejectionReason: "",
      reinspectionDate: "",
      inspector: "검사원"
    }
  ]);

  const updateRejectionData = (index: number, field: string, value: string) => {
    const newData = [...rejectionData];
    newData[index] = { ...newData[index], [field]: value };
    setRejectionData(newData);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl">
        <DialogHeader className="border-b pb-4">
          <DialogTitle className="text-2xl">반려사유 및 재검 일정</DialogTitle>
          <DialogDescription>
            부적합 판정에 대한 반려 사유와 재검사 일정을 입력합니다.
          </DialogDescription>
        </DialogHeader>

        <div className="py-4">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow className="bg-gray-100">
                  <TableHead className="text-center w-20">번호</TableHead>
                  <TableHead className="text-center">현장명</TableHead>
                  <TableHead className="text-center">부적합사유</TableHead>
                  <TableHead className="text-center w-48">재검일정</TableHead>
                  <TableHead className="text-center w-40">검사자</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rejectionData.map((item, index) => (
                  <TableRow key={item.no}>
                    <TableCell className="text-center">{item.no}</TableCell>
                    <TableCell className="text-center">
                      <Input 
                        value={item.siteName}
                        onChange={(e) => updateRejectionData(index, 'siteName', e.target.value)}
                        className="h-9"
                        placeholder="현장명 입력"
                      />
                    </TableCell>
                    <TableCell className="text-center">
                      <Input 
                        value={item.rejectionReason}
                        onChange={(e) => updateRejectionData(index, 'rejectionReason', e.target.value)}
                        className="h-9"
                        placeholder="부적합사유 입력"
                      />
                    </TableCell>
                    <TableCell className="text-center">
                      <div className="flex items-center gap-2">
                        <Input 
                          type="date"
                          value={item.reinspectionDate}
                          onChange={(e) => updateRejectionData(index, 'reinspectionDate', e.target.value)}
                          className="h-9 flex-1"
                        />
                        <Calendar className="h-4 w-4 text-muted-foreground" />
                      </div>
                    </TableCell>
                    <TableCell className="text-center">
                      <Select 
                        value={item.inspector} 
                        onValueChange={(value) => updateRejectionData(index, 'inspector', value)}
                      >
                        <SelectTrigger className="h-9">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="검사원">검사원</SelectItem>
                          <SelectItem value="김검사">김검사</SelectItem>
                          <SelectItem value="이검사">이검사</SelectItem>
                          <SelectItem value="박검사">박검사</SelectItem>
                        </SelectContent>
                      </Select>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        </div>

        {/* 하단 버튼 */}
        <div className="flex items-center justify-end gap-3 border-t pt-4">
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button>
            저장
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// 합격 상세보기 모달
interface PassDetailModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  inspection: any;
}

function PassDetailModal({ open, onOpenChange, inspection }: PassDetailModalProps) {
  const [isTestReportOpen, setIsTestReportOpen] = useState(false);

  const passData = [
    {
      siteName: "이경호기업관",
      rejectionReason: "사이즈오류",
      reinspectionDate: "8/15",
      inspector: "김검사"
    }
  ];

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-4xl">
          <DialogHeader className="border-b pb-4">
            <DialogTitle className="text-2xl">상세보기</DialogTitle>
            <DialogDescription>
              검사 합격 항목의 상세 정보를 확인할 수 있습니다.
            </DialogDescription>
          </DialogHeader>

          <div className="py-4">
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-gray-100">
                    <TableHead className="text-center">현장명</TableHead>
                    <TableHead className="text-center">부적합사유</TableHead>
                    <TableHead className="text-center">재검일정</TableHead>
                    <TableHead className="text-center">검사자</TableHead>
                    <TableHead className="text-center">제품검사</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {passData.map((item, index) => (
                    <TableRow key={index}>
                      <TableCell className="text-center text-gray-400 italic">
                        {item.siteName}
                      </TableCell>
                      <TableCell className="text-center text-gray-400 italic">
                        {item.rejectionReason}
                      </TableCell>
                      <TableCell className="text-center text-gray-400 italic">
                        {item.reinspectionDate}
                      </TableCell>
                      <TableCell className="text-center text-gray-400 italic">
                        {item.inspector}
                      </TableCell>
                      <TableCell className="text-center">
                        <Button
                          variant="link"
                          className="text-blue-600 p-0 h-auto underline"
                          onClick={() => {
                            setIsTestReportOpen(true);
                          }}
                        >
                          성적서
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>

          {/* 하단 버튼 */}
          <div className="flex items-center justify-end gap-3 border-t pt-4">
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              닫기
            </Button>
          </div>
        </DialogContent>
      </Dialog>

      {/* 검사성적서 모달 */}
      <TestReportModal 
        open={isTestReportOpen}
        onOpenChange={setIsTestReportOpen}
      />
    </>
  );
}
