import React, { useState, useMemo } 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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Checkbox } from "./ui/checkbox";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "./ui/dialog";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { 
  Search, 
  Download, 
  Calendar, 
  Plus,
  ChevronLeft,
  ChevronRight,
  FileText,
  ClipboardCheck,
  CheckCircle,
  XCircle,
  Clock,
  Package,
  Edit,
  Eye
} from "lucide-react";
import exampleImage from 'figma:asset/4064da92fb00c5a64f22f9beb2ec5da485744757.png';

// 품목 검사 데이터 인터페이스
interface ItemInspectionData {
  id: string;
  순번: number;
  등록일: string;
  작업명: string;
  대분류: string;
  인반외주: string;
  공정: string;
  제품: string;
  작업자: string;
  규격: string;
  색상: string;
  비고: string;
  품목코드: string;
  품목명: string;
  수량: number;
  검사상태: "대기" | "진행중" | "합격" | "불합격" | "보류";
  검사일자?: string;
  검사자?: string;
  불량수량?: number;
}

// 대시보드 통계 데이터
interface DashboardStats {
  총검사품목: number;
  합격: number;
  불합격: number;
  진행중: number;
  합격률: number;
}

export function QualityItemInspection() {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedStatus, setSelectedStatus] = useState("전체");
  const [selectedDateType, setSelectedDateType] = useState("등록일");
  const [startDate, setStartDate] = useState("2025-07-20");
  const [endDate, setEndDate] = useState("2025-07-30");
  const [isInspectionModalOpen, setIsInspectionModalOpen] = useState(false);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState<ItemInspectionData | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // Mock 데이터 - 이미지 참고
  const mockItemInspections: ItemInspectionData[] = [
    {
      id: "1",
      순번: 1,
      등록일: "2025-07-20",
      작업명: "스크린",
      대분류: "인반",
      인반외주: "가타도제철",
      공정: "4단(가타)아연도금",
      제품: "E01 1.55T",
      작업자: "",
      규격: "S1/5 1.2T",
      색상: "8",
      비고: "138",
      품목코드: "PT-SCR-001",
      품목명: "스크린 프레임 A",
      수량: 138,
      검사상태: "대기"
    },
    {
      id: "2",
      순번: 2,
      등록일: "2025-07-20",
      작업명: "스크린",
      대분류: "인반",
      인반외주: "가타도제철",
      공정: "가타도제철",
      제품: "E01 1.55T",
      작업자: "",
      규격: "S1/5 1.2T",
      색상: "",
      비고: "138",
      품목코드: "PT-SCR-002",
      품목명: "스크린 패널 B",
      수량: 138,
      검사상태: "합격",
      검사일자: "2025-07-21",
      검사자: "김검사"
    },
    {
      id: "3",
      순번: 3,
      등록일: "2025-07-20",
      작업명: "스크린",
      대분류: "인반",
      인반외주: "TPW(화도공감)",
      공정: "2단(아연도금)",
      제품: "E01 1.55T",
      작업자: "",
      규격: "S1/5 1.2T",
      색상: "",
      비고: "85",
      품목코드: "PT-SCR-003",
      품목명: "스크린 지지대 C",
      수량: 85,
      검사상태: "진행중",
      검사일자: "2025-07-22",
      검사자: "이검사"
    },
    {
      id: "4",
      순번: 4,
      등록일: "2025-07-20",
      작업명: "장방",
      대분류: "인반",
      인반외주: "60(제팬도금)",
      공정: "60(제팬도금)",
      제품: "E01 1.55T",
      작업자: "",
      규격: "S1/5 1.2T",
      색상: "",
      비고: "145",
      품목코드: "PT-REC-001",
      품목명: "장방형 패널",
      수량: 145,
      검사상태: "합격",
      검사일자: "2025-07-21",
      검사자: "박검사"
    },
    {
      id: "5",
      순번: 5,
      등록일: "2025-07-20",
      작업명: "장방",
      대분류: "인반",
      인반외주: "1단(아연도금)",
      공정: "1단(아연도금)",
      제품: "S1/5 1.2T",
      작업자: "",
      규격: "S1/5 1.2T",
      색상: "",
      비고: "297",
      품목코드: "PT-REC-002",
      품목명: "장방형 프레임",
      수량: 297,
      검사상태: "불합격",
      검사일자: "2025-07-22",
      검사자: "최검사",
      불량수량: 12
    },
    {
      id: "6",
      순번: 6,
      등록일: "2025-07-20",
      작업명: "장방",
      대분류: "인반",
      인반외주: "가타도제철",
      공정: "가타도제철",
      제품: "S1/5 1.2T",
      작업자: "",
      규격: "S1/5 1.2T",
      색상: "",
      비고: "169",
      품목코드: "PT-REC-003",
      품목명: "장방형 연결재",
      수량: 169,
      검사상태: "대기"
    },
    {
      id: "7",
      순번: 7,
      등록일: "2025-07-20",
      작업명: "장방",
      대분류: "인반",
      인반외주: "50(제팬도금(신))",
      공정: "50(제팬도금(신))",
      제품: "E01 1.55T",
      작업자: "",
      규격: "S1/5 1.2T",
      색상: "",
      비고: "190",
      품목코드: "PT-REC-004",
      품목명: "장방형 마감재",
      수량: 190,
      검사상태: "합격",
      검사일자: "2025-07-21",
      검사자: "김검사"
    },
    {
      id: "8",
      순번: 8,
      등록일: "2025-07-20",
      작업명: "장방",
      대분류: "인반",
      인반외주: "2단(아연도금)",
      공정: "2단(아연도금)",
      제품: "E01 1.55T",
      작업자: "",
      규격: "E01 1.55T",
      색상: "1",
      비고: "104",
      품목코드: "PT-REC-005",
      품목명: "장방형 고정재",
      수량: 104,
      검사상태: "진행중",
      검사일자: "2025-07-23",
      검사자: "이검사"
    }
  ];

  // 추가 Mock 데이터 (더 많은 항목)
  const extendedMockData = [
    ...mockItemInspections,
    ...Array.from({ length: 20 }, (_, i) => ({
      id: `${i + 9}`,
      순번: i + 9,
      등록일: "2025-07-20",
      작업명: i % 2 === 0 ? "스크린" : "장방",
      대분류: "인반",
      인반외주: ["가타도제철", "TPW(화도공감)", "60(제팬도금)"][i % 3],
      공정: ["가타도제철", "2단(아연도금)", "4단(가타)아연도금"][i % 3],
      제품: "E01 1.55T",
      작업자: "",
      규격: "S1/5 1.2T",
      색상: i % 5 === 0 ? "8" : "",
      비고: String(100 + i),
      품목코드: `PT-${i % 2 === 0 ? "SCR" : "REC"}-${String(i).padStart(3, "0")}`,
      품목명: `${i % 2 === 0 ? "스크린" : "장방형"} 부품 ${i}`,
      수량: 100 + i * 10,
      검사상태: ["대기", "진행중", "합격", "불합격"][i % 4] as ItemInspectionData["검사상태"]
    }))
  ];

  // 필터링된 데이터
  const filteredData = useMemo(() => {
    return extendedMockData.filter(item => {
      const matchesSearch = searchTerm === "" || 
        item.작업명.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.품목명.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.품목코드.toLowerCase().includes(searchTerm.toLowerCase()) ||
        item.공정.toLowerCase().includes(searchTerm.toLowerCase());
      
      const matchesStatus = selectedStatus === "전체" || item.검사상태 === selectedStatus;
      
      return matchesSearch && matchesStatus;
    });
  }, [searchTerm, selectedStatus]);

  // 페이지네이션
  const totalPages = Math.ceil(filteredData.length / itemsPerPage);
  const paginatedData = filteredData.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  // 통계 계산
  const stats: DashboardStats = useMemo(() => {
    const total = filteredData.length;
    const passed = filteredData.filter(item => item.검사상태 === "합격").length;
    const failed = filteredData.filter(item => item.검사상태 === "불합격").length;
    const inProgress = filteredData.filter(item => item.검사상태 === "진행중").length;
    const passRate = total > 0 ? Math.round((passed / total) * 100 * 10) / 10 : 0;

    return {
      총검사품목: total,
      합격: passed,
      불합격: failed,
      진행중: inProgress,
      합격률: passRate
    };
  }, [filteredData]);

  // 검사 상태별 색상
  const getStatusColor = (status: ItemInspectionData["검사상태"]) => {
    const colors = {
      "대기": "bg-gray-100 text-gray-700",
      "진행중": "bg-yellow-100 text-yellow-700",
      "합격": "bg-green-100 text-green-700",
      "불합격": "bg-red-100 text-red-700",
      "보류": "bg-orange-100 text-orange-700"
    };
    return colors[status];
  };

  // 검사 처리 핸들러
  const handleInspection = (item: ItemInspectionData) => {
    setSelectedItem(item);
    setIsInspectionModalOpen(true);
  };

  // 상세보기 핸들러
  const handleViewDetail = (item: ItemInspectionData) => {
    setSelectedItem(item);
    setIsDetailModalOpen(true);
  };

  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>
            <Button className="bg-gradient-to-r from-green-500 to-green-600">
              <Plus className="h-4 w-4 mr-2" />
              검사 등록
            </Button>
          </div>
        </div>
      </div>

      {/* 통계 대시보드 */}
      <div className="grid grid-cols-2 lg:grid-cols-5 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">
              <Package 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">{stats.총검사품목}건</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">{stats.합격}건</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">{stats.불합격}건</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">{stats.진행중}건</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-purple-500 to-purple-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">{stats.합격률}%</div>
            <p className="text-xs text-muted-foreground mt-1">검사 합격률</p>
          </CardContent>
        </Card>
      </div>

      {/* 필터 및 검색 영역 */}
      <Card>
        <CardContent className="p-6">
          <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">
                <Label className="text-xs text-muted-foreground">검사 상태</Label>
                <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>
                    <SelectItem value="보류">보류</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* 날짜 타입 선택 */}
              <div className="space-y-1">
                <Label className="text-xs text-muted-foreground">날짜 구분</Label>
                <Select value={selectedDateType} onValueChange={setSelectedDateType}>
                  <SelectTrigger className="w-32 h-9">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="등록일">등록일</SelectItem>
                    <SelectItem value="검사일">검사일</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* 날짜 범위 */}
              <div className="flex items-center gap-2">
                <div className="space-y-1">
                  <Label className="text-xs text-muted-foreground">시작일</Label>
                  <div className="flex items-center gap-2 border rounded-md px-3 py-1.5 h-9">
                    <Input 
                      type="date" 
                      value={startDate}
                      onChange={(e) => setStartDate(e.target.value)}
                      className="border-0 p-0 h-auto focus-visible:ring-0 w-32 text-sm"
                    />
                  </div>
                </div>
                <span className="text-muted-foreground mt-5">~</span>
                <div className="space-y-1">
                  <Label className="text-xs text-muted-foreground">종료일</Label>
                  <div className="flex items-center gap-2 border rounded-md px-3 py-1.5 h-9">
                    <Input 
                      type="date" 
                      value={endDate}
                      onChange={(e) => setEndDate(e.target.value)}
                      className="border-0 p-0 h-auto focus-visible:ring-0 w-32 text-sm"
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* 검색 */}
            <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>
        </CardContent>
      </Card>

      {/* 참고 이미지 (개발 단계에서만 표시) */}
      <Card className="border-green-200 bg-green-50/50">
        <CardHeader>
          <CardTitle className="text-sm">참고: 품목 검사 리스트 예시</CardTitle>
        </CardHeader>
        <CardContent>
          <img src={exampleImage} alt="품목 검사 리스트 예시" className="w-full rounded-lg border" />
        </CardContent>
      </Card>

      {/* 데이터 테이블 */}
      <Card>
        <CardContent className="p-6">
          {/* 데스크톱 테이블 */}
          <div className="hidden lg:block border rounded-lg overflow-hidden">
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/50">
                    <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 w-24">작업명</TableHead>
                    <TableHead className="text-center w-20">인반/외주</TableHead>
                    <TableHead className="text-center">공정</TableHead>
                    <TableHead className="text-center w-32">제품</TableHead>
                    <TableHead className="text-center w-24">규격</TableHead>
                    <TableHead className="text-center w-16">색상</TableHead>
                    <TableHead className="text-center w-20">비고</TableHead>
                    <TableHead className="text-center w-32">품목코드</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-32">작업</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {paginatedData.map((item) => (
                    <TableRow key={item.id} className="hover:bg-muted/30">
                      <TableCell className="text-center">
                        <Checkbox />
                      </TableCell>
                      <TableCell className="text-center text-sm">{item.순번}</TableCell>
                      <TableCell className="text-center text-sm">{item.등록일}</TableCell>
                      <TableCell className="text-center text-sm">{item.작업명}</TableCell>
                      <TableCell className="text-center text-sm">{item.대분류}</TableCell>
                      <TableCell className="text-center text-sm">{item.공정}</TableCell>
                      <TableCell className="text-center text-sm">{item.제품}</TableCell>
                      <TableCell className="text-center text-sm">{item.규격}</TableCell>
                      <TableCell className="text-center text-sm">{item.색상}</TableCell>
                      <TableCell className="text-center text-sm">{item.비고}</TableCell>
                      <TableCell className="text-center text-sm font-mono">{item.품목코드}</TableCell>
                      <TableCell className="text-center text-sm">{item.수량}</TableCell>
                      <TableCell className="text-center">
                        <Badge 
                          className={`${getStatusColor(item.검사상태)} border-0 text-xs cursor-pointer hover:opacity-80`}
                          onClick={() => handleInspection(item)}
                        >
                          {item.검사상태}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-center text-sm">{item.검사자 || "-"}</TableCell>
                      <TableCell className="text-center">
                        <div className="flex items-center justify-center gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-7 w-7 p-0"
                            onClick={() => handleViewDetail(item)}
                          >
                            <Eye className="h-3.5 w-3.5" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            className="h-7 w-7 p-0"
                            onClick={() => handleInspection(item)}
                          >
                            <Edit className="h-3.5 w-3.5" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>

          {/* 모바일 카드 */}
          <div className="lg:hidden space-y-3">
            {paginatedData.map((item) => (
              <Card key={item.id} className="border shadow-sm">
                <CardContent className="p-4">
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center gap-2">
                      <Checkbox />
                      <Badge className="text-xs">#{item.순번}</Badge>
                    </div>
                    <Badge className={`${getStatusColor(item.검사상태)} border-0 text-xs`}>
                      {item.검사상태}
                    </Badge>
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">작업명:</span>
                      <span className="text-sm font-medium">{item.작업명}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">품목코드:</span>
                      <span className="text-sm font-mono">{item.품목코드}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">품목명:</span>
                      <span className="text-sm">{item.품목명}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">공정:</span>
                      <span className="text-sm">{item.공정}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">수량:</span>
                      <span className="text-sm">{item.수량}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-sm text-muted-foreground">등록일:</span>
                      <span className="text-sm">{item.등록일}</span>
                    </div>
                    {item.검사자 && (
                      <div className="flex justify-between">
                        <span className="text-sm text-muted-foreground">검사자:</span>
                        <span className="text-sm">{item.검사자}</span>
                      </div>
                    )}
                  </div>

                  <div className="flex gap-2 mt-3 pt-3 border-t">
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      onClick={() => handleViewDetail(item)}
                    >
                      <Eye className="h-3.5 w-3.5 mr-1" />
                      상세
                    </Button>
                    <Button
                      size="sm"
                      className="flex-1"
                      onClick={() => handleInspection(item)}
                    >
                      <Edit className="h-3.5 w-3.5 mr-1" />
                      검사
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* 페이지네이션 */}
          <div className="flex items-center justify-between mt-6">
            <div className="text-sm text-muted-foreground">
              총 {filteredData.length}개 중 {((currentPage - 1) * itemsPerPage) + 1}-{Math.min(currentPage * itemsPerPage, filteredData.length)}개 표시
            </div>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                disabled={currentPage === 1}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <div className="flex items-center gap-1">
                {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                  let pageNum;
                  if (totalPages <= 5) {
                    pageNum = i + 1;
                  } else if (currentPage <= 3) {
                    pageNum = i + 1;
                  } else if (currentPage >= totalPages - 2) {
                    pageNum = totalPages - 4 + i;
                  } else {
                    pageNum = currentPage - 2 + i;
                  }
                  return (
                    <Button
                      key={pageNum}
                      variant={currentPage === pageNum ? "default" : "outline"}
                      size="sm"
                      onClick={() => setCurrentPage(pageNum)}
                      className="w-8 h-8 p-0"
                    >
                      {pageNum}
                    </Button>
                  );
                })}
              </div>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                disabled={currentPage === totalPages}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 검사 처리 모달 */}
      <Dialog open={isInspectionModalOpen} onOpenChange={setIsInspectionModalOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>품목 검사 처리</DialogTitle>
            <DialogDescription>품목의 검사 결과를 입력하고 처리합니다.</DialogDescription>
          </DialogHeader>
          {selectedItem && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4 p-4 bg-muted/50 rounded-lg">
                <div>
                  <Label className="text-xs text-muted-foreground">품목코드</Label>
                  <p className="font-mono">{selectedItem.품목코드}</p>
                </div>
                <div>
                  <Label className="text-xs text-muted-foreground">품목명</Label>
                  <p>{selectedItem.품목명}</p>
                </div>
                <div>
                  <Label className="text-xs text-muted-foreground">작업명</Label>
                  <p>{selectedItem.작업명}</p>
                </div>
                <div>
                  <Label className="text-xs text-muted-foreground">수량</Label>
                  <p>{selectedItem.수량}</p>
                </div>
                <div>
                  <Label className="text-xs text-muted-foreground">공정</Label>
                  <p>{selectedItem.공정}</p>
                </div>
                <div>
                  <Label className="text-xs text-muted-foreground">현재 상태</Label>
                  <Badge className={`${getStatusColor(selectedItem.검사상태)} border-0`}>
                    {selectedItem.검사상태}
                  </Badge>
                </div>
              </div>

              <div className="space-y-3">
                <div>
                  <Label>검사 결과</Label>
                  <Select defaultValue="합격">
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="합격">합격</SelectItem>
                      <SelectItem value="불합격">불합격</SelectItem>
                      <SelectItem value="보류">보류</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div>
                  <Label>검사일자</Label>
                  <Input type="date" defaultValue={new Date().toISOString().split('T')[0]} />
                </div>

                <div>
                  <Label>검사자</Label>
                  <Input placeholder="검사자 이름" />
                </div>

                <div>
                  <Label>불량 수량 (불합격인 경우)</Label>
                  <Input type="number" placeholder="0" min="0" />
                </div>

                <div>
                  <Label>검사 의견</Label>
                  <Textarea 
                    placeholder="검사 결과에 대한 상세 의견을 입력하세요..."
                    rows={4}
                  />
                </div>
              </div>

              <DialogFooter>
                <Button variant="outline" onClick={() => setIsInspectionModalOpen(false)}>
                  취소
                </Button>
                <Button onClick={() => {
                  // 검사 처리 로직
                  setIsInspectionModalOpen(false);
                }}>
                  저장
                </Button>
              </DialogFooter>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 상세보기 모달 */}
      <Dialog open={isDetailModalOpen} onOpenChange={setIsDetailModalOpen}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle>품목 상세 정보</DialogTitle>
            <DialogDescription>품목의 상세 정보를 확인합니다.</DialogDescription>
          </DialogHeader>
          {selectedItem && (
            <div className="space-y-6">
              {/* 기본 정보 */}
              <div>
                <h3 className="font-medium mb-3">기본 정보</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">순번</Label>
                    <p>{selectedItem.순번}</p>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">등록일</Label>
                    <p>{selectedItem.등록일}</p>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">품목코드</Label>
                    <p className="font-mono">{selectedItem.품목코드}</p>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">품목명</Label>
                    <p>{selectedItem.품목명}</p>
                  </div>
                </div>
              </div>

              {/* 작업 정보 */}
              <div>
                <h3 className="font-medium mb-3">작업 정���</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">작업명</Label>
                    <p>{selectedItem.작업명}</p>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">대분류</Label>
                    <p>{selectedItem.대분류}</p>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">인반/외주</Label>
                    <p>{selectedItem.인반외주}</p>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">공정</Label>
                    <p>{selectedItem.공정}</p>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">제품</Label>
                    <p>{selectedItem.제품}</p>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">규격</Label>
                    <p>{selectedItem.규격}</p>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">색상</Label>
                    <p>{selectedItem.색상 || "-"}</p>
                  </div>
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">수량</Label>
                    <p>{selectedItem.수량}</p>
                  </div>
                </div>
              </div>

              {/* 검사 정보 */}
              <div>
                <h3 className="font-medium mb-3">검사 정보</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <Label className="text-xs text-muted-foreground">검사 상태</Label>
                    <Badge className={`${getStatusColor(selectedItem.검사상태)} border-0`}>
                      {selectedItem.검사상태}
                    </Badge>
                  </div>
                  {selectedItem.검사일자 && (
                    <div className="space-y-1">
                      <Label className="text-xs text-muted-foreground">검사일자</Label>
                      <p>{selectedItem.검사일자}</p>
                    </div>
                  )}
                  {selectedItem.검사자 && (
                    <div className="space-y-1">
                      <Label className="text-xs text-muted-foreground">검사자</Label>
                      <p>{selectedItem.검사자}</p>
                    </div>
                  )}
                  {selectedItem.불량수량 && (
                    <div className="space-y-1">
                      <Label className="text-xs text-muted-foreground">불량 수량</Label>
                      <p className="text-red-600">{selectedItem.불량수량}개</p>
                    </div>
                  )}
                </div>
              </div>

              {/* 비고 */}
              {selectedItem.비고 && (
                <div>
                  <h3 className="font-medium mb-3">비고</h3>
                  <p className="text-sm text-muted-foreground">{selectedItem.비고}</p>
                </div>
              )}

              <DialogFooter>
                <Button variant="outline" onClick={() => setIsDetailModalOpen(false)}>
                  닫기
                </Button>
                <Button onClick={() => {
                  setIsDetailModalOpen(false);
                  handleInspection(selectedItem);
                }}>
                  <Edit className="h-4 w-4 mr-2" />
                  검사 처리
                </Button>
              </DialogFooter>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}