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, 
  Car, 
  Fuel, 
  AlertTriangle, 
  Activity, 
  MapPin, 
  Clock, 
  Calendar,
  Eye,
  Edit,
  BarChart3,
  TrendingUp,
  User,
  RefreshCw,
  ClipboardCheck,
  Wrench,
  FileText,
  DollarSign
} 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 VehicleManagement() {
  const [activeTab, setActiveTab] = useState("vehicles");
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedType, setSelectedType] = useState("all");
  const [selectedStatus, setSelectedStatus] = useState("all");
  const [isAddVehicleOpen, setIsAddVehicleOpen] = useState(false);
  const [isDriveLogOpen, setIsDriveLogOpen] = useState(false);

  // 차량 현황 데이터
  const vehicleData = [
    {
      id: "V001",
      vehicleNumber: "12가3456",
      vehicleName: "화물차 #1",
      type: "화물차",
      model: "포터2",
      manufacturer: "현대",
      year: 2022,
      purpose: "자재운반",
      status: "운행중",
      mileage: 45320,
      fuelEfficiency: 9.8,
      lastMaintenance: "2024-12-10",
      nextMaintenance: "2025-03-10",
      driver: "김운전",
      insurance: "2025-06-30",
      registration: "2025-08-15",
      monthlyDistance: 2850,
      fuelCost: 320000
    },
    {
      id: "V002",
      vehicleNumber: "34나5678",
      vehicleName: "승용차 #1",
      type: "승용차",
      model: "그랜저",
      manufacturer: "현대",
      year: 2023,
      purpose: "영업용",
      status: "정비중",
      mileage: 28500,
      fuelEfficiency: 11.2,
      lastMaintenance: "2024-12-28",
      nextMaintenance: "2025-06-28",
      driver: "박영업",
      insurance: "2025-05-20",
      registration: "2025-07-10",
      monthlyDistance: 1920,
      fuelCost: 180000
    },
    {
      id: "V003",
      vehicleNumber: "56다7890",
      vehicleName: "밴 #1",
      type: "밴",
      model: "스타렉스",
      manufacturer: "현대",
      year: 2021,
      purpose: "자재/인력운송",
      status: "운행가능",
      mileage: 67800,
      fuelEfficiency: 8.5,
      lastMaintenance: "2024-11-20",
      nextMaintenance: "2025-02-20",
      driver: "최운송",
      insurance: "2025-04-15",
      registration: "2025-06-25",
      monthlyDistance: 3200,
      fuelCost: 420000
    },
    {
      id: "V004",
      vehicleNumber: "78라1234",
      vehicleName: "지게차 #1",
      type: "특수차량",
      model: "D30S-5",
      manufacturer: "두산",
      year: 2020,
      purpose: "창고작업",
      status: "운행중",
      mileage: 1250,
      fuelEfficiency: 0,
      lastMaintenance: "2024-12-05",
      nextMaintenance: "2025-03-05",
      driver: "이지게",
      insurance: "2025-07-10",
      registration: "2025-08-20",
      monthlyDistance: 80,
      fuelCost: 0
    }
  ];

  // 운행 관리 데이터
  const driveLogData = [
    {
      id: "DL001",
      vehicleNumber: "12가3456",
      driver: "김운전",
      date: "2025-01-15",
      startTime: "08:00",
      endTime: "18:00",
      startMileage: 45100,
      endMileage: 45320,
      distance: 220,
      purpose: "자재운반",
      destination: "서울 → 인천",
      fuelAmount: 35,
      fuelCost: 52500,
      status: "완료"
    },
    {
      id: "DL002",
      vehicleNumber: "34나5678",
      driver: "박영업",
      date: "2025-01-14",
      startTime: "09:00",
      endTime: "17:00",
      startMileage: 28350,
      endMileage: 28500,
      distance: 150,
      purpose: "거래처 방문",
      destination: "서울 → 수원",
      fuelAmount: 18,
      fuelCost: 27000,
      status: "완료"
    },
    {
      id: "DL003",
      vehicleNumber: "56다7890",
      driver: "최운송",
      date: "2025-01-15",
      startTime: "07:30",
      endTime: "19:00",
      startMileage: 67500,
      endMileage: 67800,
      distance: 300,
      purpose: "자재 배송",
      destination: "서울 → 대전",
      fuelAmount: 45,
      fuelCost: 67500,
      status: "완료"
    }
  ];

  // 정비 관리 데이터
  const maintenanceData = [
    {
      id: "M001",
      vehicleNumber: "12가3456",
      date: "2024-12-10",
      type: "정기점검",
      description: "엔진오일 교환, 타이어 교체",
      cost: 350000,
      vendor: "현대서비스센터",
      nextDate: "2025-03-10",
      technician: "정비사 A",
      status: "완료"
    },
    {
      id: "M002",
      vehicleNumber: "34나5678",
      date: "2024-12-28",
      type: "고장수리",
      description: "브레이크 패드 교체",
      cost: 280000,
      vendor: "현대서비스센터",
      nextDate: "2025-06-28",
      technician: "정비사 B",
      status: "완료"
    },
    {
      id: "M003",
      vehicleNumber: "56다7890",
      date: "2024-11-20",
      type: "정기점검",
      description: "종합점검",
      cost: 420000,
      vendor: "현대서비스센터",
      nextDate: "2025-02-20",
      technician: "정비사 C",
      status: "완료"
    }
  ];

  // 월별 운행 통계 데이터
  const monthlyStats = [
    { month: "7월", distance: 8500, fuel: 950000, maintenance: 0 },
    { month: "8월", distance: 9200, fuel: 1020000, maintenance: 350000 },
    { month: "9월", distance: 8800, fuel: 980000, maintenance: 0 },
    { month: "10월", distance: 9500, fuel: 1050000, maintenance: 280000 },
    { month: "11월", distance: 9100, fuel: 1010000, maintenance: 420000 },
    { month: "12월", distance: 8700, fuel: 960000, maintenance: 0 }
  ];

  // 차량별 운행거리 데이터
  const vehicleDistanceData = [
    { name: "화물차 #1", value: 2850 },
    { name: "승용차 #1", value: 1920 },
    { name: "밴 #1", value: 3200 },
    { name: "지게차 #1", value: 80 }
  ];

  // 통계 카드 데이터
  const stats = [
    {
      title: "총 차량",
      value: "4",
      change: 0,
      icon: Car,
      description: "전체 보유 차량"
    },
    {
      title: "운행중",
      value: "2",
      change: 0,
      icon: Activity,
      description: "현재 운행중인 차량"
    },
    {
      title: "이번달 운행거리",
      value: "8,050km",
      change: -5.2,
      icon: MapPin,
      description: "전월 대비"
    },
    {
      title: "이번달 연료비",
      value: "₩920,000",
      change: -3.8,
      icon: Fuel,
      description: "전월 대비"
    }
  ];

  // 필터링된 차량 데이터
  const filteredVehicles = vehicleData.filter(vehicle => {
    const matchesSearch = vehicle.vehicleName.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         vehicle.vehicleNumber.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesType = selectedType === "all" || vehicle.type === selectedType;
    const matchesStatus = selectedStatus === "all" || vehicle.status === selectedStatus;
    return matchesSearch && matchesType && matchesStatus;
  });

  // 필터링된 운행일지 데이터
  const filteredDriveLogs = driveLogData.filter(log => {
    return log.vehicleNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
           log.driver.toLowerCase().includes(searchTerm.toLowerCase());
  });

  // 필터링된 정비 데이터
  const filteredMaintenance = maintenanceData.filter(item => {
    return item.vehicleNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
           item.description.toLowerCase().includes(searchTerm.toLowerCase());
  });

  // 상태 배지 색상
  const getStatusColor = (status: string) => {
    switch (status) {
      case "운행중": return "default";
      case "운행가능": return "secondary";
      case "정비중": return "destructive";
      default: return "outline";
    }
  };

  return (
    <PageLayout>
      <PageHeader
        title="차량관리"
        description="회사 보유 차량의 운행 및 정비 이력을 관리합니다"
        icon={Car}
        actions={
          <>
            <Button variant="outline">
              <Download className="w-4 h-4 mr-2" />
              보고서 다운로드
            </Button>
            <Button>
              <RefreshCw 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="vehicles">
            <Car className="w-4 h-4 mr-2" />
            <span className="hidden sm:inline">차량 현황</span>
            <span className="sm:hidden">차량</span>
          </TabsTrigger>
          <TabsTrigger value="drivelog">
            <MapPin 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="insurance">
            <FileText className="w-4 h-4 mr-2" />
            <span className="hidden sm:inline">보험/등록</span>
            <span className="sm:hidden">보험</span>
          </TabsTrigger>
          <TabsTrigger value="statistics">
            <BarChart3 className="w-4 h-4 mr-2" />
            <span className="hidden sm:inline">통계</span>
            <span className="sm:hidden">통계</span>
          </TabsTrigger>
        </TabsList>

        {/* 차량 현황 탭 */}
        <TabsContent value="vehicles" className="space-y-4 md:space-y-6">
          <Card>
            <CardHeader className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
              <CardTitle>차량 목록</CardTitle>
              <Dialog open={isAddVehicleOpen} onOpenChange={setIsAddVehicleOpen}>
                <DialogTrigger asChild>
                  <Button>
                    <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="vehicleNumber">차량번호</Label>
                        <Input id="vehicleNumber" placeholder="예: 12가3456" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="vehicleName">차량명</Label>
                        <Input id="vehicleName" placeholder="차량명 입력" />
                      </div>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="type">차량유형</Label>
                        <Select>
                          <SelectTrigger>
                            <SelectValue placeholder="차량유형 선택" />
                          </SelectTrigger>
                          <SelectContent>
                            <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="year">연식</Label>
                        <Input id="year" type="number" placeholder="2024" />
                      </div>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="purpose">용도</Label>
                        <Input id="purpose" placeholder="차량 용도" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="mileage">현재 주행거리 (km)</Label>
                        <Input id="mileage" type="number" placeholder="0" />
                      </div>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="insurance">보험 만료일</Label>
                        <Input id="insurance" type="date" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="registration">차량등록증 만료일</Label>
                        <Input id="registration" type="date" />
                      </div>
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="notes">비고</Label>
                      <Textarea id="notes" placeholder="추가 정보를 입력하세요" />
                    </div>
                  </div>
                  <div className="flex justify-end gap-2 pt-4">
                    <Button variant="outline" onClick={() => setIsAddVehicleOpen(false)}>
                      취소
                    </Button>
                    <Button onClick={() => setIsAddVehicleOpen(false)}>
                      등록
                    </Button>
                  </div>
                </DialogContent>
              </Dialog>
            </CardHeader>
            <CardContent>
              <SearchFilter
                searchTerm={searchTerm}
                onSearchChange={setSearchTerm}
                filters={[
                  {
                    label: "차량유형",
                    value: selectedType,
                    onChange: setSelectedType,
                    options: [
                      { value: "all", label: "전체" },
                      { value: "화물차", label: "화물차" },
                      { value: "승용차", label: "승용차" },
                      { value: "밴", label: "밴" },
                      { value: "특수차량", label: "특수차량" }
                    ]
                  },
                  {
                    label: "상태",
                    value: selectedStatus,
                    onChange: setSelectedStatus,
                    options: [
                      { value: "all", label: "전체" },
                      { value: "운행중", label: "운행중" },
                      { value: "운행가능", label: "운행가능" },
                      { value: "정비중", label: "정비중" }
                    ]
                  }
                ]}
              />

              {/* 데스크톱 테이블 */}
              <div className="hidden md:block rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <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>
                    {filteredVehicles.map((vehicle) => (
                      <TableRow key={vehicle.id}>
                        <TableCell>{vehicle.vehicleNumber}</TableCell>
                        <TableCell>{vehicle.vehicleName}</TableCell>
                        <TableCell>{vehicle.type}</TableCell>
                        <TableCell>{vehicle.model}</TableCell>
                        <TableCell>{vehicle.purpose}</TableCell>
                        <TableCell>
                          <Badge variant={getStatusColor(vehicle.status)}>
                            {vehicle.status}
                          </Badge>
                        </TableCell>
                        <TableCell>{vehicle.mileage.toLocaleString()}km</TableCell>
                        <TableCell>{vehicle.fuelEfficiency > 0 ? `${vehicle.fuelEfficiency}km/L` : '-'}</TableCell>
                        <TableCell>{vehicle.driver}</TableCell>
                        <TableCell>{vehicle.nextMaintenance}</TableCell>
                        <TableCell className="text-right">
                          <Button variant="ghost" size="sm">
                            <Eye className="w-4 h-4" />
                          </Button>
                          <Button variant="ghost" size="sm">
                            <Edit className="w-4 h-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* 모바일 카드 */}
              <div className="md:hidden space-y-4">
                {filteredVehicles.map((vehicle) => (
                  <MobileCard
                    key={vehicle.id}
                    title={vehicle.vehicleName}
                    subtitle={vehicle.vehicleNumber}
                    badge={{
                      label: vehicle.status,
                      variant: getStatusColor(vehicle.status)
                    }}
                    fields={[
                      { label: "차종", value: vehicle.type },
                      { label: "모델", value: vehicle.model },
                      { label: "용도", value: vehicle.purpose },
                      { label: "주행거리", value: `${vehicle.mileage.toLocaleString()}km` },
                      { label: "연비", value: vehicle.fuelEfficiency > 0 ? `${vehicle.fuelEfficiency}km/L` : '-' },
                      { label: "운전자", value: vehicle.driver },
                      { label: "다음정비", value: vehicle.nextMaintenance }
                    ]}
                    actions={[
                      {
                        label: "상세",
                        icon: Eye,
                        variant: "outline",
                        onClick: () => {}
                      },
                      {
                        label: "수정",
                        icon: Edit,
                        variant: "outline",
                        onClick: () => {}
                      }
                    ]}
                  />
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 운행 관리 탭 */}
        <TabsContent value="drivelog" className="space-y-4 md:space-y-6">
          <Card>
            <CardHeader className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0">
              <CardTitle>운행일지</CardTitle>
              <Dialog open={isDriveLogOpen} onOpenChange={setIsDriveLogOpen}>
                <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="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="logVehicle">차량번호</Label>
                        <Select>
                          <SelectTrigger>
                            <SelectValue placeholder="차량 선택" />
                          </SelectTrigger>
                          <SelectContent>
                            {vehicleData.map((v) => (
                              <SelectItem key={v.id} value={v.vehicleNumber}>
                                {v.vehicleNumber} - {v.vehicleName}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="logDriver">운전자</Label>
                        <Input id="logDriver" placeholder="운전자명" />
                      </div>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="logDate">운행일자</Label>
                        <Input id="logDate" type="date" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="logPurpose">운행목적</Label>
                        <Input id="logPurpose" placeholder="운행 목적" />
                      </div>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="startTime">출발시간</Label>
                        <Input id="startTime" type="time" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="endTime">도착시간</Label>
                        <Input id="endTime" type="time" />
                      </div>
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="startMileage">출발 주행거리</Label>
                        <Input id="startMileage" type="number" placeholder="km" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="endMileage">도착 주행거리</Label>
                        <Input id="endMileage" type="number" placeholder="km" />
                      </div>
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="destination">출발지 → 도착지</Label>
                      <Input id="destination" placeholder="예: 서울 → 인천" />
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label htmlFor="fuelAmount">주유량 (L)</Label>
                        <Input id="fuelAmount" type="number" placeholder="0" />
                      </div>
                      <div className="space-y-2">
                        <Label htmlFor="fuelCost">주유비용 (원)</Label>
                        <Input id="fuelCost" type="number" placeholder="0" />
                      </div>
                    </div>
                  </div>
                  <div className="flex justify-end gap-2 pt-4">
                    <Button variant="outline" onClick={() => setIsDriveLogOpen(false)}>
                      취소
                    </Button>
                    <Button onClick={() => setIsDriveLogOpen(false)}>
                      등록
                    </Button>
                  </div>
                </DialogContent>
              </Dialog>
            </CardHeader>
            <CardContent>
              <SearchFilter
                searchTerm={searchTerm}
                onSearchChange={setSearchTerm}
              />

              {/* 데스크톱 테이블 */}
              <div className="hidden md:block rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>차량번호</TableHead>
                      <TableHead>운전자</TableHead>
                      <TableHead>일자</TableHead>
                      <TableHead>운행시간</TableHead>
                      <TableHead>주행거리</TableHead>
                      <TableHead>목적</TableHead>
                      <TableHead>목적지</TableHead>
                      <TableHead>주유량</TableHead>
                      <TableHead>주유비용</TableHead>
                      <TableHead>상태</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredDriveLogs.map((log) => (
                      <TableRow key={log.id}>
                        <TableCell>{log.vehicleNumber}</TableCell>
                        <TableCell>{log.driver}</TableCell>
                        <TableCell>{log.date}</TableCell>
                        <TableCell>{log.startTime} - {log.endTime}</TableCell>
                        <TableCell>{log.distance}km</TableCell>
                        <TableCell>{log.purpose}</TableCell>
                        <TableCell>{log.destination}</TableCell>
                        <TableCell>{log.fuelAmount}L</TableCell>
                        <TableCell>₩{log.fuelCost.toLocaleString()}</TableCell>
                        <TableCell>
                          <Badge variant="secondary">{log.status}</Badge>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* 모바일 카드 */}
              <div className="md:hidden space-y-4">
                {filteredDriveLogs.map((log) => (
                  <MobileCard
                    key={log.id}
                    title={log.vehicleNumber}
                    subtitle={`${log.driver} · ${log.date}`}
                    badge={{
                      label: log.status,
                      variant: "secondary"
                    }}
                    fields={[
                      { label: "운행시간", value: `${log.startTime} - ${log.endTime}` },
                      { label: "주행거리", value: `${log.distance}km` },
                      { label: "목적", value: log.purpose },
                      { label: "목적지", value: log.destination },
                      { label: "주유량", value: `${log.fuelAmount}L` },
                      { label: "주유비용", value: `₩${log.fuelCost.toLocaleString()}` }
                    ]}
                  />
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 정비 관리 탭 */}
        <TabsContent value="maintenance" className="space-y-4 md:space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>정비 이력</CardTitle>
            </CardHeader>
            <CardContent>
              <SearchFilter
                searchTerm={searchTerm}
                onSearchChange={setSearchTerm}
              />

              {/* 데스크톱 테이블 */}
              <div className="hidden md:block rounded-md border">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>차량번호</TableHead>
                      <TableHead>정비일자</TableHead>
                      <TableHead>정비유형</TableHead>
                      <TableHead>내용</TableHead>
                      <TableHead>비용</TableHead>
                      <TableHead>정비소</TableHead>
                      <TableHead>다음정비일</TableHead>
                      <TableHead>상태</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredMaintenance.map((item) => (
                      <TableRow key={item.id}>
                        <TableCell>{item.vehicleNumber}</TableCell>
                        <TableCell>{item.date}</TableCell>
                        <TableCell>{item.type}</TableCell>
                        <TableCell>{item.description}</TableCell>
                        <TableCell>₩{item.cost.toLocaleString()}</TableCell>
                        <TableCell>{item.vendor}</TableCell>
                        <TableCell>{item.nextDate}</TableCell>
                        <TableCell>
                          <Badge variant="secondary">{item.status}</Badge>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* 모바일 카드 */}
              <div className="md:hidden space-y-4">
                {filteredMaintenance.map((item) => (
                  <MobileCard
                    key={item.id}
                    title={item.vehicleNumber}
                    subtitle={`${item.type} · ${item.date}`}
                    badge={{
                      label: item.status,
                      variant: "secondary"
                    }}
                    fields={[
                      { label: "내용", value: item.description },
                      { label: "비용", value: `₩${item.cost.toLocaleString()}` },
                      { label: "정비소", value: item.vendor },
                      { label: "담당자", value: item.technician },
                      { label: "다음정비일", value: item.nextDate }
                    ]}
                  />
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 보험/등록 탭 */}
        <TabsContent value="insurance" className="space-y-4 md:space-y-6">
          <div className="grid gap-4 md:gap-6 grid-cols-1 lg:grid-cols-2">
            {vehicleData.map((vehicle) => (
              <Card key={vehicle.id}>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div>
                      <CardTitle>{vehicle.vehicleName}</CardTitle>
                      <p className="text-sm text-muted-foreground mt-1">{vehicle.vehicleNumber}</p>
                    </div>
                    <Badge variant={getStatusColor(vehicle.status)}>
                      {vehicle.status}
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="space-y-3">
                    <div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                      <div className="flex items-center gap-2">
                        <FileText className="w-4 h-4 text-muted-foreground" />
                        <span className="text-sm">보험 만료일</span>
                      </div>
                      <span className="font-medium">{vehicle.insurance}</span>
                    </div>
                    <div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                      <div className="flex items-center gap-2">
                        <FileText className="w-4 h-4 text-muted-foreground" />
                        <span className="text-sm">등록증 만료일</span>
                      </div>
                      <span className="font-medium">{vehicle.registration}</span>
                    </div>
                  </div>
                  <div className="pt-2">
                    <Button variant="outline" className="w-full">
                      <Edit className="w-4 h-4 mr-2" />
                      정보 수정
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 통계 탭 */}
        <TabsContent value="statistics" className="space-y-4 md:space-y-6">
          <div className="grid gap-4 md:gap-6 grid-cols-1 lg:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle>월별 운행 통계</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300} minHeight={300}>
                  <BarChart data={monthlyStats}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="month" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="distance" fill="#8884d8" name="운행거리(km)" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>월별 비용 분석</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300} minHeight={300}>
                  <BarChart data={monthlyStats}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="month" />
                    <YAxis />
                    <Tooltip />
                    <Legend />
                    <Bar dataKey="fuel" fill="#82ca9d" name="연료비(원)" />
                    <Bar dataKey="maintenance" fill="#ffc658" name="정비비(원)" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>차량별 월간 운행거리</CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300} minHeight={300}>
                  <BarChart data={vehicleDistanceData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="name" />
                    <YAxis />
                    <Tooltip />
                    <Bar dataKey="value" fill="#8884d8" name="운행거리(km)" />
                  </BarChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>정비 일정</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {vehicleData.map((vehicle) => {
                    const daysUntilMaintenance = Math.floor((new Date(vehicle.nextMaintenance).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24));
                    const isUrgent = daysUntilMaintenance <= 30;
                    
                    return (
                      <div key={vehicle.id} className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                        <div>
                          <p className="font-medium">{vehicle.vehicleName}</p>
                          <p className="text-sm text-muted-foreground">{vehicle.vehicleNumber}</p>
                        </div>
                        <div className="text-right">
                          <p className={`text-sm font-medium ${isUrgent ? 'text-destructive' : ''}`}>
                            {vehicle.nextMaintenance}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            {daysUntilMaintenance > 0 ? `${daysUntilMaintenance}일 남음` : '정비 필요'}
                          </p>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>
    </PageLayout>
  );
}