import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "./ui/dialog";
import { Progress } from "./ui/progress";
import { Textarea } from "./ui/textarea";
import { 
  Plus, 
  Download, 
  Settings, 
  Wrench, 
  AlertTriangle, 
  Activity, 
  Zap, 
  Clock, 
  Calendar,
  Eye,
  Edit,
  PlayCircle,
  BarChart3,
  TrendingUp,
  Thermometer,
  Gauge,
  User,
  MapPin,
  RefreshCw,
  ClipboardCheck
} from "lucide-react";
import { LineChart, Line, AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from "recharts";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { StatCards } from "./organisms/StatCards";
import { SearchFilter } from "./organisms/SearchFilter";
import { MobileCard } from "./organisms/MobileCard";

export function EquipmentManagement() {
  const [activeTab, setActiveTab] = useState("equipment");
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [selectedStatus, setSelectedStatus] = useState("all");
  const [isAddEquipmentOpen, setIsAddEquipmentOpen] = useState(false);
  const [isMaintenanceOpen, setIsMaintenanceOpen] = useState(false);

  // 설비 현황 데이터
  const equipmentData = [
    {
      id: "EQ001",
      equipmentCode: "CNC-001",
      equipmentName: "CNC 가공기 #1",
      category: "가공장비",
      model: "HAAS VF-2SS",
      manufacturer: "HAAS",
      location: "생산라인 A",
      status: "가동중",
      operationRate: 85.5,
      efficiency: 92.3,
      lastMaintenance: "2024-12-15",
      nextMaintenance: "2025-01-15",
      operator: "이작업",
      temperature: 45,
      vibration: 2.3,
      power: 15.2,
      totalRuntime: 2850,
      mtbf: 320,
      mttr: 4.5
    },
    {
      id: "EQ002",
      equipmentCode: "PRESS-001",
      equipmentName: "유압 프레스 #1",
      category: "프레스",
      model: "HP-500T",
      manufacturer: "현대위아",
      location: "생산라인 B",
      status: "정비중",
      operationRate: 0,
      efficiency: 0,
      lastMaintenance: "2024-12-30",
      nextMaintenance: "2025-02-28",
      operator: "정설비",
      temperature: 35,
      vibration: 0,
      power: 0,
      totalRuntime: 1920,
      mtbf: 280,
      mttr: 6.2
    },
    {
      id: "EQ003",
      equipmentCode: "ROBOT-001",
      equipmentName: "산업용 로봇 #1",
      category: "로봇",
      model: "UR10e",
      manufacturer: "Universal Robots",
      location: "생산라인 A",
      status: "가동중",
      operationRate: 95.2,
      efficiency: 98.1,
      lastMaintenance: "2024-12-20",
      nextMaintenance: "2025-01-20",
      operator: "박작업",
      temperature: 38,
      vibration: 1.1,
      power: 3.5,
      totalRuntime: 3200,
      mtbf: 450,
      mttr: 2.8
    },
    {
      id: "EQ004",
      equipmentCode: "CONV-001",
      equipmentName: "컨베이어 시스템 #1",
      category: "운반장비",
      model: "CS-2000",
      manufacturer: "대한컨베이어",
      location: "생산라인 전체",
      status: "경고",
      operationRate: 75.8,
      efficiency: 82.4,
      lastMaintenance: "2024-11-15",
      nextMaintenance: "2024-12-31",
      operator: "최설비",
      temperature: 42,
      vibration: 3.8,
      power: 8.7,
      totalRuntime: 4100,
      mtbf: 200,
      mttr: 8.5
    },
    {
      id: "EQ005",
      equipmentCode: "WELD-001",
      equipmentName: "자동 용접기 #1",
      category: "용접장비",
      model: "AW-300",
      manufacturer: "삼성웰딩",
      location: "용접부",
      status: "정지",
      operationRate: 0,
      efficiency: 0,
      lastMaintenance: "2024-12-25",
      nextMaintenance: "2025-01-25",
      operator: "김용접",
      temperature: 25,
      vibration: 0,
      power: 0,
      totalRuntime: 1650,
      mtbf: 350,
      mttr: 5.2
    }
  ];

  // 정비 이력 데이터
  const maintenanceHistory = [
    {
      id: "MH001",
      date: "2024-12-30",
      equipmentCode: "PRESS-001",
      equipmentName: "유압 프레스 #1",
      type: "예방정비",
      category: "정기점검",
      technician: "정설비",
      duration: 4,
      cost: 350000,
      description: "유압 오일 교체 및 시스템 점검",
      status: "완료",
      parts: ["유압오일", "필터", "씰"]
    },
    {
      id: "MH002",
      date: "2024-12-28",
      equipmentCode: "CONV-001",
      equipmentName: "컨베이어 시스템 #1",
      type: "고장정비",
      category: "긴급수리",
      technician: "최설비",
      duration: 2,
      cost: 150000,
      description: "모터 베어링 교체",
      status: "완료",
      parts: ["베어링", "그리스"]
    },
    {
      id: "MH003",
      date: "2024-12-25",
      equipmentCode: "WELD-001",
      equipmentName: "자동 용접기 #1",
      type: "예방정비",
      category: "정기점검",
      technician: "김용접",
      duration: 3,
      cost: 200000,
      description: "용접 토치 교체 및 캘리브레이션",
      status: "완료",
      parts: ["용접토치", "전극"]
    }
  ];

  // 정비 계획 데이터
  const maintenancePlan = [
    {
      id: "MP001",
      scheduledDate: "2024-12-31",
      equipmentCode: "CONV-001",
      equipmentName: "컨베이어 시스템 #1",
      type: "예방정비",
      category: "정기점검",
      assignedTo: "최설비",
      estimatedDuration: 6,
      estimatedCost: 400000,
      priority: "높음",
      description: "전체 시스템 점검 및 부품 교체",
      status: "예정"
    },
    {
      id: "MP002",
      scheduledDate: "2025-01-15",
      equipmentCode: "CNC-001",
      equipmentName: "CNC 가공기 #1",
      type: "예방정비",
      category: "정기점검",
      assignedTo: "정설비",
      estimatedDuration: 4,
      estimatedCost: 300000,
      priority: "보통",
      description: "스핀들 점검 및 냉각수 교체",
      status: "예정"
    },
    {
      id: "MP003",
      scheduledDate: "2025-01-20",
      equipmentCode: "ROBOT-001",
      equipmentName: "산업용 로봇 #1",
      type: "예방정비",
      category: "소프트웨어 업데이트",
      assignedTo: "박작업",
      estimatedDuration: 2,
      estimatedCost: 100000,
      priority: "낮음",
      description: "펌웨어 업데이트 및 캘리브레이션",
      status: "예정"
    }
  ];

  // 설비 성능 데이터
  const performanceData = [
    { time: "08:00", efficiency: 85, temperature: 38, vibration: 2.1 },
    { time: "10:00", efficiency: 92, temperature: 42, vibration: 2.3 },
    { time: "12:00", efficiency: 88, temperature: 45, vibration: 2.8 },
    { time: "14:00", efficiency: 95, temperature: 43, vibration: 2.2 },
    { time: "16:00", efficiency: 91, temperature: 41, vibration: 2.0 },
    { time: "18:00", efficiency: 87, temperature: 39, vibration: 1.9 }
  ];

  // 설비 통계
  const equipmentStats = {
    totalEquipment: equipmentData.length,
    operating: equipmentData.filter(eq => eq.status === "가동중").length,
    maintenance: equipmentData.filter(eq => eq.status === "정비중").length,
    stopped: equipmentData.filter(eq => eq.status === "정지").length,
    warning: equipmentData.filter(eq => eq.status === "경고").length,
    avgEfficiency: equipmentData.reduce((sum, eq) => sum + eq.efficiency, 0) / equipmentData.length,
    avgOperationRate: equipmentData.reduce((sum, eq) => sum + eq.operationRate, 0) / equipmentData.length
  };

  const stats = [
    {
      label: "총 설비",
      value: equipmentStats.totalEquipment,
      icon: Settings,
      iconColor: "text-blue-600"
    },
    {
      label: "가동 설비",
      value: equipmentStats.operating,
      icon: PlayCircle,
      iconColor: "text-green-600"
    },
    {
      label: "평균 효율",
      value: `${equipmentStats.avgEfficiency.toFixed(1)}%`,
      icon: TrendingUp,
      iconColor: "text-blue-600"
    },
    {
      label: "가동률",
      value: `${equipmentStats.avgOperationRate.toFixed(1)}%`,
      icon: Gauge,
      iconColor: "text-orange-600"
    }
  ];

  const getStatusColor = (status: string) => {
    switch (status) {
      case "가동중": return "default";
      case "정비중": return "secondary";
      case "정지": return "outline";
      case "경고": return "destructive";
      case "완료": return "default";
      case "진행중": return "secondary";
      case "예정": return "outline";
      default: return "outline";
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case "높음": return "destructive";
      case "보통": return "secondary";
      case "낮음": return "outline";
      default: return "outline";
    }
  };

  const filteredEquipment = equipmentData.filter(equipment => {
    const matchesSearch = equipment.equipmentName.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         equipment.equipmentCode.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesCategory = selectedCategory === "all" || equipment.category === selectedCategory;
    const matchesStatus = selectedStatus === "all" || equipment.status === selectedStatus;
    
    return matchesSearch && matchesCategory && matchesStatus;
  });

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader 
        title="설비 목록"
        description="생산설비 운영 및 정비 관리"
        icon={Wrench}
        actions={
          <>
            <Dialog open={isAddEquipmentOpen} onOpenChange={setIsAddEquipmentOpen}>
              <DialogTrigger asChild>
                <Button variant="outline">
                  <Plus className="w-4 h-4 mr-2" />
                  설비 등록
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-[95vw] sm:max-w-xl md:max-w-4xl max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                  <DialogTitle>신규 설비 등록</DialogTitle>
                  <DialogDescription>새로운 설비 정보를 입력합니다.</DialogDescription>
                </DialogHeader>
                <div className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="equipmentCode">설비 코드</Label>
                      <Input id="equipmentCode" placeholder="예: EQ-001" />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="equipmentName">설비명</Label>
                      <Input id="equipmentName" placeholder="설비명 입력" />
                    </div>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="category">카테고리</Label>
                      <Select>
                        <SelectTrigger>
                          <SelectValue placeholder="카테고리 선택" />
                        </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-2">
                      <Label htmlFor="manufacturer">제조사</Label>
                      <Input id="manufacturer" placeholder="제조사명" />
                    </div>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="model">모델명</Label>
                      <Input id="model" placeholder="모델명" />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="location">설치위치</Label>
                      <Input id="location" placeholder="설치위치" />
                    </div>
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="specifications">사양</Label>
                    <Textarea id="specifications" placeholder="설비 사양 및 특이사항" />
                  </div>
                  <div className="flex flex-col sm:flex-row gap-2 pt-4">
                    <Button className="flex-1" onClick={() => setIsAddEquipmentOpen(false)}>
                      등록
                    </Button>
                    <Button variant="outline" className="flex-1" onClick={() => setIsAddEquipmentOpen(false)}>
                      취소
                    </Button>
                  </div>
                </div>
              </DialogContent>
            </Dialog>
            <Button>
              <Wrench className="w-4 h-4 mr-2" />
              정비 계획
            </Button>
          </>
        }
      />

      {/* 통계 카드 */}
      <StatCards stats={stats} />

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4 md:space-y-6">
        <TabsList className="grid w-full grid-cols-2 md:grid-cols-5">
          <TabsTrigger value="equipment">
            <Settings className="w-4 h-4 mr-2" />
            <span className="hidden sm:inline">설비 현황</span>
            <span className="sm:hidden">설비</span>
          </TabsTrigger>
          <TabsTrigger value="maintenance">
            <Wrench className="w-4 h-4 mr-2" />
            <span className="hidden sm:inline">정비 관리</span>
            <span className="sm:hidden">정비</span>
          </TabsTrigger>
          <TabsTrigger value="plan" className="hidden md:flex">
            <Calendar className="w-4 h-4 mr-2" />
            정비 계획
          </TabsTrigger>
          <TabsTrigger value="monitoring" className="hidden md:flex">
            <Activity className="w-4 h-4 mr-2" />
            실시간 모니터링
          </TabsTrigger>
          <TabsTrigger value="analysis" className="hidden md:flex">
            <BarChart3 className="w-4 h-4 mr-2" />
            성능 분석
          </TabsTrigger>
        </TabsList>

        <TabsContent value="equipment" className="space-y-4 md:space-y-6">
          {/* 검색 및 필터 */}
          <Card>
            <CardContent className="p-4">
              <div className="flex flex-col md:flex-row gap-3">
                <SearchFilter 
                  searchValue={searchTerm}
                  onSearchChange={setSearchTerm}
                  searchPlaceholder="설비명, 설비코드로 검색..."
                  filterButton={false}
                />
                <div className="grid grid-cols-2 md:grid-cols-3 gap-2">
                  <Select value={selectedCategory} onValueChange={setSelectedCategory}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">전체 카테고리</SelectItem>
                      <SelectItem value="가공장비">가공장비</SelectItem>
                      <SelectItem value="프레스">프레스</SelectItem>
                      <SelectItem value="로봇">로봇</SelectItem>
                      <SelectItem value="운반장비">운반장비</SelectItem>
                      <SelectItem value="용접장비">용접장비</SelectItem>
                    </SelectContent>
                  </Select>
                  <Select value={selectedStatus} onValueChange={setSelectedStatus}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">전체 상태</SelectItem>
                      <SelectItem value="가동중">가동중</SelectItem>
                      <SelectItem value="정비중">정비중</SelectItem>
                      <SelectItem value="정지">정지</SelectItem>
                      <SelectItem value="경고">경고</SelectItem>
                    </SelectContent>
                  </Select>
                  <Button variant="outline" className="col-span-2 md:col-span-1">
                    <Download className="w-4 h-4 mr-2" />
                    엑셀
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 데스크톱 테이블 */}
          <Card className="hidden md:block">
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                <span>설비 현황 ({filteredEquipment.length}대)</span>
                <Button size="sm" variant="outline">
                  <RefreshCw className="w-4 h-4 mr-2" />
                  새로고침
                </Button>
              </CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>설비코드</TableHead>
                    <TableHead>설비명</TableHead>
                    <TableHead>카테고리</TableHead>
                    <TableHead>위치</TableHead>
                    <TableHead>상태</TableHead>
                    <TableHead>가동률</TableHead>
                    <TableHead>효율</TableHead>
                    <TableHead>온도</TableHead>
                    <TableHead>진동</TableHead>
                    <TableHead>전력</TableHead>
                    <TableHead>운전자</TableHead>
                    <TableHead className="text-right">작업</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredEquipment.map((equipment) => (
                    <TableRow key={equipment.id}>
                      <TableCell className="font-mono text-sm">{equipment.equipmentCode}</TableCell>
                      <TableCell className="font-medium">{equipment.equipmentName}</TableCell>
                      <TableCell>{equipment.category}</TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-1">
                          <MapPin className="w-3 h-3 text-muted-foreground" />
                          <span className="text-sm">{equipment.location}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant={getStatusColor(equipment.status)}>
                          {equipment.status}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="w-16">
                          <Progress value={equipment.operationRate} className="h-2" />
                          <span className="text-xs text-muted-foreground">
                            {equipment.operationRate.toFixed(1)}%
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="w-16">
                          <Progress value={equipment.efficiency} className="h-2" />
                          <span className="text-xs text-muted-foreground">
                            {equipment.efficiency.toFixed(1)}%
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-1">
                          <Thermometer className="w-3 h-3 text-red-500" />
                          <span className="text-sm">{equipment.temperature}°C</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-1">
                          <Activity className="w-3 h-3 text-blue-500" />
                          <span className="text-sm">{equipment.vibration}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-1">
                          <Zap className="w-3 h-3 text-yellow-500" />
                          <span className="text-sm">{equipment.power}kW</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-1">
                          <User className="w-3 h-3 text-muted-foreground" />
                          <span className="text-sm">{equipment.operator}</span>
                        </div>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex items-center justify-end gap-1">
                          <Button size="sm" variant="ghost">
                            <Eye className="w-4 h-4" />
                          </Button>
                          <Button size="sm" variant="ghost">
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button size="sm" variant="ghost">
                            <Wrench className="w-4 h-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>

          {/* 모바일 카드 */}
          <div className="md:hidden space-y-4">
            {filteredEquipment.map((equipment) => (
              <MobileCard 
                key={equipment.id}
                title={equipment.equipmentName}
                subtitle={`코드: ${equipment.equipmentCode}`}
                icon={<Settings className="w-4 h-4 text-blue-600" />}
                badge={{
                  label: equipment.status,
                  variant: getStatusColor(equipment.status)
                }}
                fields={[
                  { label: "카테고리", value: equipment.category },
                  { label: "위치", value: equipment.location },
                  { label: "가동률", value: `${equipment.operationRate.toFixed(1)}%` },
                  { label: "효율", value: `${equipment.efficiency.toFixed(1)}%` },
                  { label: "온도", value: `${equipment.temperature}°C` },
                  { label: "운전자", value: equipment.operator }
                ]}
                actions={[
                  {
                    label: "상세",
                    icon: Eye,
                    variant: "outline",
                    onClick: () => {}
                  },
                  {
                    label: "수정",
                    icon: Edit,
                    variant: "outline",
                    onClick: () => {}
                  },
                  {
                    label: "정비",
                    icon: Wrench,
                    variant: "outline",
                    onClick: () => {}
                  }
                ]}
              />
            ))}
          </div>
        </TabsContent>

        <TabsContent value="maintenance" className="space-y-4 md:space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                <span>정비 이력</span>
                <Dialog open={isMaintenanceOpen} onOpenChange={setIsMaintenanceOpen}>
                  <DialogTrigger asChild>
                    <Button>
                      <Plus className="w-4 h-4 mr-2" />
                      정비 등록
                    </Button>
                  </DialogTrigger>
                  <DialogContent className="max-w-[95vw] sm:max-w-lg md:max-w-3xl max-h-[90vh] overflow-y-auto">
                    <DialogHeader>
                      <DialogTitle>정비 작업 등록</DialogTitle>
                      <DialogDescription>설비 정비 작업 정보를 입력합니다.</DialogDescription>
                    </DialogHeader>
                    <div className="space-y-4">
                      <div className="space-y-2">
                        <Label htmlFor="equipment">설비 선택</Label>
                        <Select>
                          <SelectTrigger>
                            <SelectValue placeholder="설비를 선택하세요" />
                          </SelectTrigger>
                          <SelectContent>
                            {equipmentData.map(equipment => (
                              <SelectItem key={equipment.id} value={equipment.equipmentCode}>
                                {equipment.equipmentName} ({equipment.equipmentCode})
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="space-y-2">
                          <Label>정비 유형</Label>
                          <Select>
                            <SelectTrigger>
                              <SelectValue placeholder="유형 선택" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="예방정비">예방정비</SelectItem>
                              <SelectItem value="고장정비">고장정비</SelectItem>
                              <SelectItem value="개선정비">개선정비</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        <div className="space-y-2">
                          <Label>담당자</Label>
                          <Input placeholder="담당자명" />
                        </div>
                      </div>
                      <div className="space-y-2">
                        <Label>작업 내용</Label>
                        <Textarea placeholder="정비 작업 내용을 입력하세요" />
                      </div>
                      <div className="flex flex-col sm:flex-row gap-2 pt-4">
                        <Button className="flex-1" onClick={() => setIsMaintenanceOpen(false)}>
                          등록
                        </Button>
                        <Button variant="outline" className="flex-1" onClick={() => setIsMaintenanceOpen(false)}>
                          취소
                        </Button>
                      </div>
                    </div>
                  </DialogContent>
                </Dialog>
              </CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              {/* 데스크톱 테이블 */}
              <div className="hidden md:block">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>일자</TableHead>
                      <TableHead>설비코드</TableHead>
                      <TableHead>설비명</TableHead>
                      <TableHead>유형</TableHead>
                      <TableHead>분류</TableHead>
                      <TableHead>담당자</TableHead>
                      <TableHead>소요시간</TableHead>
                      <TableHead>비용</TableHead>
                      <TableHead>상태</TableHead>
                      <TableHead className="text-right">작업</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {maintenanceHistory.map((maint) => (
                      <TableRow key={maint.id}>
                        <TableCell>{maint.date}</TableCell>
                        <TableCell className="font-mono text-sm">{maint.equipmentCode}</TableCell>
                        <TableCell>{maint.equipmentName}</TableCell>
                        <TableCell>{maint.type}</TableCell>
                        <TableCell>{maint.category}</TableCell>
                        <TableCell>{maint.technician}</TableCell>
                        <TableCell>{maint.duration}시간</TableCell>
                        <TableCell>{maint.cost.toLocaleString()}원</TableCell>
                        <TableCell>
                          <Badge variant={getStatusColor(maint.status)}>
                            {maint.status}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-right">
                          <Button size="sm" variant="ghost">
                            <Eye className="w-4 h-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* 모바일 카드 */}
              <div className="md:hidden p-4 space-y-4">
                {maintenanceHistory.map((maint) => (
                  <MobileCard 
                    key={maint.id}
                    title={maint.equipmentName}
                    subtitle={`${maint.type} - ${maint.date}`}
                    icon={<ClipboardCheck className="w-4 h-4 text-blue-600" />}
                    badge={{
                      label: maint.status,
                      variant: getStatusColor(maint.status)
                    }}
                    fields={[
                      { label: "설비코드", value: maint.equipmentCode },
                      { label: "분류", value: maint.category },
                      { label: "담당자", value: maint.technician },
                      { label: "소요시간", value: `${maint.duration}시간` },
                      { label: "비용", value: `${maint.cost.toLocaleString()}원` }
                    ]}
                    actions={[
                      {
                        label: "상세보기",
                        icon: Eye,
                        variant: "outline",
                        onClick: () => {}
                      }
                    ]}
                  />
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="plan" className="space-y-4 md:space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>정비 계획</CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              {/* 데스크톱 테이블 */}
              <div className="hidden md:block">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>예정일</TableHead>
                      <TableHead>설비코드</TableHead>
                      <TableHead>설비명</TableHead>
                      <TableHead>유형</TableHead>
                      <TableHead>담당자</TableHead>
                      <TableHead>예상시간</TableHead>
                      <TableHead>예상비용</TableHead>
                      <TableHead>우선순위</TableHead>
                      <TableHead>상태</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {maintenancePlan.map((plan) => (
                      <TableRow key={plan.id}>
                        <TableCell>{plan.scheduledDate}</TableCell>
                        <TableCell className="font-mono text-sm">{plan.equipmentCode}</TableCell>
                        <TableCell>{plan.equipmentName}</TableCell>
                        <TableCell>{plan.type}</TableCell>
                        <TableCell>{plan.assignedTo}</TableCell>
                        <TableCell>{plan.estimatedDuration}시간</TableCell>
                        <TableCell>{plan.estimatedCost.toLocaleString()}원</TableCell>
                        <TableCell>
                          <Badge variant={getPriorityColor(plan.priority)}>
                            {plan.priority}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge variant={getStatusColor(plan.status)}>
                            {plan.status}
                          </Badge>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* 모바일 카드 */}
              <div className="md:hidden p-4 space-y-4">
                {maintenancePlan.map((plan) => (
                  <MobileCard 
                    key={plan.id}
                    title={plan.equipmentName}
                    subtitle={`${plan.type} - ${plan.scheduledDate}`}
                    icon={<Calendar className="w-4 h-4 text-orange-600" />}
                    badge={{
                      label: plan.priority,
                      variant: getPriorityColor(plan.priority)
                    }}
                    fields={[
                      { label: "설비코드", value: plan.equipmentCode },
                      { label: "담당자", value: plan.assignedTo },
                      { label: "예상시간", value: `${plan.estimatedDuration}시간` },
                      { label: "예상비용", value: `${plan.estimatedCost.toLocaleString()}원` },
                      { label: "상태", value: plan.status, badge: true, badgeVariant: getStatusColor(plan.status) }
                    ]}
                  />
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="monitoring" className="space-y-4 md:space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>실시간 모니터링</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-6">
                <div className="h-64 md:h-80 min-h-[16rem] md:min-h-[20rem]">
                  <ResponsiveContainer width="100%" height="100%" minHeight={320}>
                    <LineChart data={performanceData}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="time" />
                      <YAxis />
                      <Tooltip />
                      <Legend />
                      <Line type="monotone" dataKey="efficiency" stroke="#3b82f6" name="효율 (%)" />
                      <Line type="monotone" dataKey="temperature" stroke="#ef4444" name="온도 (°C)" />
                    </LineChart>
                  </ResponsiveContainer>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="analysis" className="space-y-4 md:space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>성능 분석</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="h-64 md:h-80 min-h-[16rem] md:min-h-[20rem]">
                <ResponsiveContainer width="100%" height="100%" minHeight={320}>
                  <BarChart data={equipmentData.slice(0, 5)}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="equipmentCode" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="efficiency" fill="#3b82f6" name="효율 (%)" />
                    <Bar dataKey="operationRate" fill="#10b981" name="가동률 (%)" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </PageLayout>
  );
}