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 { 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 { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } 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,
  Upload,
  Filter,
  TrendingUp,
  AlertTriangle,
  BarChart3,
  History
} from "lucide-react";

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

// 검사 기준 인터페이스
interface InspectionStandard {
  id: string;
  품목코드: string;
  품목명: string;
  검사항목: string;
  규격: string;
  기준값: string;
  허용오차: string;
  측정방법: string;
  측정도구: string;
  필수여부: boolean;
}

// 검사 이력 인터페이스
interface InspectionHistory {
  id: string;
  검사일자: string;
  품목코드: string;
  품목명: string;
  검사자: string;
  검사결과: "합격" | "불합격" | "보류";
  총수량: number;
  불량수량: number;
  불량률: number;
  불량유형: string[];
  조치사항?: string;
}

export function QualityItemInspectionEnhanced() {
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedStatus, setSelectedStatus] = useState("전체");
  const [selectedWorkType, setSelectedWorkType] = 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 [isStandardModalOpen, setIsStandardModalOpen] = useState(false);
  const [isHistoryModalOpen, setIsHistoryModalOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState<ItemInspectionData | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [currentTab, setCurrentTab] = useState("list");
  const itemsPerPage = 20;

  // Mock 검사 기준 데이터
  const mockInspectionStandards: InspectionStandard[] = [
    {
      id: "1",
      품목코드: "PT-SCR-001",
      품목명: "스크린 프레임 A",
      검사항목: "치수",
      규격: "길이 1000mm",
      기준값: "1000mm",
      허용오차: "±2mm",
      측정방법: "버니어캘리퍼스",
      측정도구: "디지털 캘리퍼스",
      필수여부: true
    },
    {
      id: "2",
      품목코드: "PT-SCR-001",
      품목명: "스크린 프레임 A",
      검사항목: "외관",
      규격: "표면 결함 없음",
      기준값: "무결함",
      허용오차: "경미한 스크래치 1개 이하",
      측정방법: "육안 검사",
      측정도구: "확대경",
      필수여부: true
    },
    {
      id: "3",
      품목코드: "PT-SCR-001",
      품목명: "스크린 프레임 A",
      검사항목: "도금 두께",
      규격: "10μm 이상",
      기준값: "10μm",
      허용오차: "-2μm",
      측정방법: "두께 측정기",
      측정도구: "전자식 두께 측정기",
      필수여부: false
    }
  ];

  // Mock 검사 이력 데이터
  const mockInspectionHistory: InspectionHistory[] = [
    {
      id: "1",
      검사일자: "2025-07-23",
      품목코드: "PT-SCR-001",
      품목명: "스크린 프레임 A",
      검사자: "김검사",
      검사결과: "합격",
      총수량: 138,
      불량수량: 2,
      불량률: 1.45,
      불량유형: ["표면 스크래치"],
      조치사항: "재작업 완료"
    },
    {
      id: "2",
      검사일자: "2025-07-22",
      품목코드: "PT-SCR-001",
      품목명: "스크린 프레임 A",
      검사자: "이검사",
      검사결과: "불합격",
      총수량: 100,
      불량수량: 12,
      불량률: 12.0,
      불량유형: ["치수 불량", "도금 불량"],
      조치사항: "재작업 예정"
    },
    {
      id: "3",
      검사일자: "2025-07-21",
      품목코드: "PT-SCR-001",
      품목명: "스크린 프레임 A",
      검사자: "박검사",
      검사결과: "합격",
      총수량: 150,
      불량수량: 0,
      불량률: 0,
      불량유형: [],
      조치사항: "-"
    }
  ];

  // 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",
      검사자: "김검사",
      불량수량: 0,
      검사기준: "치수, 외관",
      검사방법: "샘플링검사(10%)"
    },
    {
      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",
      검사자: "박검사",
      불량수량: 3,
      검사기준: "치수, 외관, 도금",
      검사방법: "전수검사",
      불량유형: ["표면 스크래치"]
    },
    {
      id: "5",
      순번: 5,
      등록일: "2025-07-20",
      작업명: "장방",
      대분류: "인반",
      인반외주: "1단(아연도금)",
      공정: "1단(아연도금)",
      제품: "S1/5 1.2T",
      작업자: "",
      규격: "S1/5 1.2T",
      색상: "",
      비고: "297",
      품목코드: "PT-REC-002",
      품목명: "장방형 프레임",
      수량: 297,
      검사상태: "불합격",
      검사일자: "2025-07-22",
      검사자: "최검사",
      불량수량: 45,
      검사기준: "치수, 강도",
      검사방법: "전수검사",
      불량유형: ["치수 불량", "강도 부족"]
    }
  ];

  // 추가 Mock 데이터
  const extendedMockData = [
    ...mockItemInspections,
    ...Array.from({ length: 20 }, (_, i) => ({
      id: `${i + 6}`,
      순번: i + 6,
      등록일: "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["검사상태"],
      검사기준: "치수, 외관",
      검사방법: i % 2 === 0 ? "전수검사" : "샘플링검사"
    }))
  ];

  // 필터링된 데이터
  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;
      const matchesWorkType = selectedWorkType === "전체" || item.작업명 === selectedWorkType;
      
      return matchesSearch && matchesStatus && matchesWorkType;
    });
  }, [searchTerm, selectedStatus, selectedWorkType]);

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

  // 통계 계산
  const stats = 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 waiting = filteredData.filter(item => item.검사상태 === "대기").length;
    const passRate = total > 0 ? Math.round((passed / (passed + failed)) * 100 * 10) / 10 : 0;

    // 불량률 통계
    const inspectedItems = filteredData.filter(item => item.검사상태 === "합격" || item.검사상태 === "불합격");
    const totalInspectedQty = inspectedItems.reduce((sum, item) => sum + item.수량, 0);
    const totalDefectQty = inspectedItems.reduce((sum, item) => sum + (item.불량수량 || 0), 0);
    const defectRate = totalInspectedQty > 0 ? Math.round((totalDefectQty / totalInspectedQty) * 100 * 100) / 100 : 0;

    return {
      총검사품목: total,
      합격: passed,
      불합격: failed,
      진행중: inProgress,
      대기: waiting,
      합격률: passRate,
      불량률: defectRate,
      총검사수량: totalInspectedQty,
      총불량수량: totalDefectQty
    };
  }, [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);
  };

  // 검사 기준 보기
  const handleViewStandard = (item: ItemInspectionData) => {
    setSelectedItem(item);
    setIsStandardModalOpen(true);
  };

  // 검사 이력 보기
  const handleViewHistory = (item: ItemInspectionData) => {
    setSelectedItem(item);
    setIsHistoryModalOpen(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-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">
              <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">전체 품목 ({stats.총검사수량}개)</p>
          </CardContent>
        </Card>

        <Card className="border-0 shadow-sm hover:shadow-md transition-all duration-300">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-xs sm:text-sm font-medium text-muted-foreground">합격률</CardTitle>
            <div className="w-8 h-8 sm:w-10 sm:h-10 bg-gradient-to-br from-green-500 to-green-600 rounded-lg flex items-center justify-center">
              <TrendingUp className="h-4 w-4 sm:h-5 sm:w-5 text-white" />
            </div>
          </CardHeader>
          <CardContent>
            <div className="text-lg sm:text-2xl font-bold">{stats.합격률}%</div>
            <p className="text-xs text-muted-foreground mt-1">합격 {stats.합격}건 / 불합격 {stats.불합격}건</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">
              <AlertTriangle 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">불량 {stats.총불량수량}개</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">대기 {stats.대기}건</p>
          </CardContent>
        </Card>
      </div>

      {/* 탭 네비게이션 */}
      <Tabs value={currentTab} onValueChange={setCurrentTab} className="w-full">
        <TabsList className="w-full md:w-auto">
          <TabsTrigger value="list">검사 목록</TabsTrigger>
          <TabsTrigger value="statistics">통계 분석</TabsTrigger>
          <TabsTrigger value="defect-analysis">불량 분석</TabsTrigger>
        </TabsList>

        {/* 검사 목록 탭 */}
        <TabsContent value="list" className="space-y-4">
          {/* 필터 및 검색 영역 */}
          <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={selectedWorkType} onValueChange={setSelectedWorkType}>
                      <SelectTrigger className="w-32 h-9">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <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={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>
            <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">공정</TableHead>
                        <TableHead className="text-center w-32">품목코드</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-20">불량수</TableHead>
                        <TableHead className="text-center w-40">작업</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 font-mono">{item.품목코드}</TableCell>
                          <TableCell className="text-center text-sm">{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 text-sm">
                            {item.불량수량 ? (
                              <span className="text-red-600">{item.불량수량}</span>
                            ) : "-"}
                          </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)}
                                title="상세보기"
                              >
                                <Eye className="h-3.5 w-3.5" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-7 w-7 p-0"
                                onClick={() => handleInspection(item)}
                                title="검사처리"
                              >
                                <Edit className="h-3.5 w-3.5" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-7 w-7 p-0"
                                onClick={() => handleViewStandard(item)}
                                title="검사기준"
                              >
                                <FileText className="h-3.5 w-3.5" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-7 w-7 p-0"
                                onClick={() => handleViewHistory(item)}
                                title="검사이력"
                              >
                                <History 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>
                        {item.불량수량 && (
                          <div className="flex justify-between">
                            <span className="text-sm text-muted-foreground">불량수량:</span>
                            <span className="text-sm text-red-600">{item.불량수량}</span>
                          </div>
                        )}
                      </div>

                      <div className="grid grid-cols-2 gap-2 mt-3 pt-3 border-t">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleViewDetail(item)}
                        >
                          <Eye className="h-3.5 w-3.5 mr-1" />
                          상세
                        </Button>
                        <Button
                          size="sm"
                          onClick={() => handleInspection(item)}
                        >
                          <Edit className="h-3.5 w-3.5 mr-1" />
                          검사
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleViewStandard(item)}
                        >
                          <FileText className="h-3.5 w-3.5 mr-1" />
                          기준
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleViewHistory(item)}
                        >
                          <History 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>
        </TabsContent>

        {/* 통계 분석 탭 */}
        <TabsContent value="statistics" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>검사 통계 분석</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {/* 작업명별 통계 */}
                <div className="space-y-3">
                  <h3 className="font-medium">작업명별 합격률</h3>
                  <div className="space-y-2">
                    <div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                      <span>스크린</span>
                      <div className="flex items-center gap-2">
                        <div className="w-32 bg-gray-200 rounded-full h-2">
                          <div className="bg-green-500 h-2 rounded-full" style={{ width: "92%" }}></div>
                        </div>
                        <span className="text-sm font-medium w-12 text-right">92%</span>
                      </div>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                      <span>장방</span>
                      <div className="flex items-center gap-2">
                        <div className="w-32 bg-gray-200 rounded-full h-2">
                          <div className="bg-green-500 h-2 rounded-full" style={{ width: "88%" }}></div>
                        </div>
                        <span className="text-sm font-medium w-12 text-right">88%</span>
                      </div>
                    </div>
                  </div>
                </div>

                {/* 공정별 통계 */}
                <div className="space-y-3">
                  <h3 className="font-medium">공정별 불량률</h3>
                  <div className="space-y-2">
                    <div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                      <span>가타도제철</span>
                      <div className="flex items-center gap-2">
                        <div className="w-32 bg-gray-200 rounded-full h-2">
                          <div className="bg-red-500 h-2 rounded-full" style={{ width: "8%" }}></div>
                        </div>
                        <span className="text-sm font-medium w-12 text-right">8%</span>
                      </div>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                      <span>2단(아연도금)</span>
                      <div className="flex items-center gap-2">
                        <div className="w-32 bg-gray-200 rounded-full h-2">
                          <div className="bg-red-500 h-2 rounded-full" style={{ width: "12%" }}></div>
                        </div>
                        <span className="text-sm font-medium w-12 text-right">12%</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 불량 분석 탭 */}
        <TabsContent value="defect-analysis" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>불량 유형 분석</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <Card className="border">
                    <CardContent className="p-4">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-sm text-muted-foreground">치수 불량</span>
                        <Badge variant="destructive">45%</Badge>
                      </div>
                      <div className="text-2xl font-bold">27건</div>
                      <p className="text-xs text-muted-foreground mt-1">가장 많은 불량 유형</p>
                    </CardContent>
                  </Card>

                  <Card className="border">
                    <CardContent className="p-4">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-sm text-muted-foreground">외관 불량</span>
                        <Badge variant="destructive">30%</Badge>
                      </div>
                      <div className="text-2xl font-bold">18건</div>
                      <p className="text-xs text-muted-foreground mt-1">표면 스크래치 등</p>
                    </CardContent>
                  </Card>

                  <Card className="border">
                    <CardContent className="p-4">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-sm text-muted-foreground">도금 불량</span>
                        <Badge variant="destructive">25%</Badge>
                      </div>
                      <div className="text-2xl font-bold">15건</div>
                      <p className="text-xs text-muted-foreground mt-1">도금 두께 부족</p>
                    </CardContent>
                  </Card>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 검사 처리 모달 */}
      <Dialog open={isInspectionModalOpen} onOpenChange={setIsInspectionModalOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>품목 검사 처리</DialogTitle>
          </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>

              <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 className="grid grid-cols-2 gap-3">
                  <div>
                    <Label>검사일자</Label>
                    <Input type="date" defaultValue={new Date().toISOString().split('T')[0]} />
                  </div>
                  <div>
                    <Label>검사자</Label>
                    <Input placeholder="검사자 이름" />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <Label>검사 수량</Label>
                    <Input type="number" placeholder={selectedItem.수량.toString()} />
                  </div>
                  <div>
                    <Label>불량 수량</Label>
                    <Input type="number" placeholder="0" min="0" />
                  </div>
                </div>

                <div>
                  <Label>불량 유형 (불합격인 경우)</Label>
                  <div className="flex flex-wrap gap-2 mt-2">
                    {["치수 불량", "외관 불량", "도금 불량", "강도 부족", "표면 스크래치", "기타"].map((type) => (
                      <div key={type} className="flex items-center space-x-2">
                        <Checkbox id={`defect-${type}`} />
                        <label htmlFor={`defect-${type}`} className="text-sm cursor-pointer">
                          {type}
                        </label>
                      </div>
                    ))}
                  </div>
                </div>

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

                <div>
                  <Label>검사 사진 첨부</Label>
                  <div className="mt-2 border-2 border-dashed rounded-lg p-4 text-center hover:bg-muted/50 cursor-pointer transition-colors">
                    <Upload className="h-8 w-8 mx-auto text-muted-foreground mb-2" />
                    <p className="text-sm text-muted-foreground">클릭하거나 파일을 드래그하여 업로드</p>
                    <p className="text-xs text-muted-foreground mt-1">JPG, PNG (최대 10MB)</p>
                  </div>
                </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 max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>품목 상세 정보</DialogTitle>
          </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>{selectedItem.검사일자}</p>
                    </div>
                  )}
                  {selectedItem.검사자 && (
                    <div className="space-y-1">
                      <Label className="text-xs text-muted-foreground">검사자</Label>
                      <p>{selectedItem.검사자}</p>
                    </div>
                  )}
                  {selectedItem.불량수량 !== undefined && (
                    <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>

      {/* 검사 기준 모달 */}
      <Dialog open={isStandardModalOpen} onOpenChange={setIsStandardModalOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>검사 기준</DialogTitle>
          </DialogHeader>
          {selectedItem && (
            <div className="space-y-4">
              <div className="p-4 bg-muted/50 rounded-lg">
                <div className="grid grid-cols-2 gap-4">
                  <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>
              </div>

              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-12">필수</TableHead>
                    <TableHead>검사항목</TableHead>
                    <TableHead>규격</TableHead>
                    <TableHead>기준값</TableHead>
                    <TableHead>허용오차</TableHead>
                    <TableHead>측정방법</TableHead>
                    <TableHead>측정도구</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {mockInspectionStandards.map((standard) => (
                    <TableRow key={standard.id}>
                      <TableCell className="text-center">
                        {standard.필수여부 ? (
                          <Badge variant="destructive" className="text-xs">필수</Badge>
                        ) : (
                          <Badge variant="secondary" className="text-xs">선택</Badge>
                        )}
                      </TableCell>
                      <TableCell className="font-medium">{standard.검사항목}</TableCell>
                      <TableCell>{standard.규격}</TableCell>
                      <TableCell>{standard.기준값}</TableCell>
                      <TableCell>{standard.허용오차}</TableCell>
                      <TableCell>{standard.측정방법}</TableCell>
                      <TableCell>{standard.측정도구}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

              <DialogFooter>
                <Button variant="outline" onClick={() => setIsStandardModalOpen(false)}>
                  닫기
                </Button>
              </DialogFooter>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 검사 이력 모달 */}
      <Dialog open={isHistoryModalOpen} onOpenChange={setIsHistoryModalOpen}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>검사 이력</DialogTitle>
          </DialogHeader>
          {selectedItem && (
            <div className="space-y-4">
              <div className="p-4 bg-muted/50 rounded-lg">
                <div className="grid grid-cols-2 gap-4">
                  <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>
              </div>

              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>검사일자</TableHead>
                    <TableHead>검사자</TableHead>
                    <TableHead>검사결과</TableHead>
                    <TableHead className="text-right">총수량</TableHead>
                    <TableHead className="text-right">불량수량</TableHead>
                    <TableHead className="text-right">불량률</TableHead>
                    <TableHead>불량유형</TableHead>
                    <TableHead>조치사항</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {mockInspectionHistory.map((history) => (
                    <TableRow key={history.id}>
                      <TableCell>{history.검사일자}</TableCell>
                      <TableCell>{history.검사자}</TableCell>
                      <TableCell>
                        <Badge 
                          className={`${getStatusColor(history.검사결과)} border-0 text-xs`}
                        >
                          {history.검사결과}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">{history.총수량}</TableCell>
                      <TableCell className="text-right text-red-600">{history.불량수량}</TableCell>
                      <TableCell className="text-right">{history.불량률}%</TableCell>
                      <TableCell>
                        <div className="flex flex-wrap gap-1">
                          {history.불량유형.map((type, idx) => (
                            <Badge key={idx} variant="outline" className="text-xs">
                              {type}
                            </Badge>
                          ))}
                        </div>
                      </TableCell>
                      <TableCell className="text-sm">{history.조치사항}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

              <DialogFooter>
                <Button variant="outline" onClick={() => setIsHistoryModalOpen(false)}>
                  닫기
                </Button>
                <Button>
                  <Download className="h-4 w-4 mr-2" />
                  이력 다운로드
                </Button>
              </DialogFooter>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
