import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { Progress } from "./ui/progress";
import { 
  Server, 
  Database, 
  Users, 
  Shield, 
  Activity, 
  AlertTriangle, 
  CheckCircle, 
  TrendingUp,
  TrendingDown,
  Clock,
  HardDrive,
  Cpu,
  MemoryStick,
  Network,
  Wifi,
  FileText,
  RefreshCw,
  Eye,
  Settings,
  UserCheck,
  UserX,
  Lock,
  Unlock
} from "lucide-react";
import { LineChart, Line, AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from "recharts";

export function SystemAdminDashboard() {
  // 시스템 상태 데이터
  const systemStatus = {
    servers: {
      total: 8,
      online: 7,
      offline: 1,
      warning: 2
    },
    database: {
      connections: 45,
      maxConnections: 100,
      queryPerformance: 98.5,
      backupStatus: "완료",
      lastBackup: "2024-12-30 02:00"
    },
    users: {
      total: 125,
      active: 89,
      inactive: 36,
      newToday: 3,
      loginToday: 67
    },
    security: {
      threatLevel: "낮음",
      blockedAttacks: 12,
      securityEvents: 3,
      lastScan: "2024-12-30 08:00"
    }
  };

  // 서버 리소스 데이터
  const serverResources = [
    { name: "WEB-01", cpu: 45, memory: 62, disk: 78, status: "정상" },
    { name: "DB-01", cpu: 78, memory: 85, disk: 45, status: "주의" },
    { name: "APP-01", cpu: 32, memory: 48, disk: 67, status: "정상" },
    { name: "API-01", cpu: 89, memory: 92, disk: 56, status: "경고" },
    { name: "FILE-01", cpu: 23, memory: 34, disk: 89, status: "정상" },
    { name: "BACKUP-01", cpu: 15, memory: 28, disk: 95, status: "주의" }
  ];

  // 시스템 사용량 트렌드
  const usageTrend = [
    { time: "00:00", cpu: 25, memory: 40, network: 15 },
    { time: "04:00", cpu: 20, memory: 35, network: 10 },
    { time: "08:00", cpu: 65, memory: 70, network: 45 },
    { time: "12:00", cpu: 85, memory: 80, network: 65 },
    { time: "16:00", cpu: 90, memory: 85, network: 70 },
    { time: "20:00", cpu: 75, memory: 75, network: 55 },
    { time: "23:59", cpu: 45, memory: 55, network: 35 }
  ];

  // 사용자 활동 분석
  const userActivity = [
    { name: "로그인", value: 245, color: "#1428A0" },
    { name: "작업", value: 189, color: "#00D084" },
    { name: "보고서", value: 156, color: "#FF6B35" },
    { name: "승인", value: 89, color: "#8B5FBF" },
    { name: "시스템", value: 45, color: "#FF4444" }
  ];

  // 보안 이벤트 로그
  const securityEvents = [
    { time: "09:15", event: "성공적인 로그인", user: "김대표", ip: "192.168.1.100", severity: "정보" },
    { time: "09:12", event: "비정상 접근 차단", user: "Unknown", ip: "203.142.15.23", severity: "경고" },
    { time: "08:45", event: "권한 변경", user: "최시스템", ip: "192.168.1.105", severity: "정보" },
    { time: "08:30", event: "다중 로그인 실패", user: "이생산", ip: "192.168.1.110", severity: "주의" },
    { time: "08:15", event: "백업 완료", user: "System", ip: "Local", severity: "정보" }
  ];

  // 데이터베이스 성능 지표
  const dbPerformance = [
    { metric: "평균 응답시간", value: "12ms", status: "excellent" },
    { metric: "동시 연결", value: "45/100", status: "good" },
    { metric: "쿼리 처리량", value: "1,250/분", status: "good" },
    { metric: "인덱스 효율성", value: "98.5%", status: "excellent" },
    { metric: "캐시 적중률", value: "94.2%", status: "excellent" },
    { metric: "디스크 I/O", value: "2.3MB/s", status: "good" }
  ];

  const getStatusColor = (status: string) => {
    switch (status) {
      case "정상": return "bg-green-500";
      case "주의": return "bg-yellow-500";
      case "경고": return "bg-orange-500";
      case "오프라인": return "bg-red-500";
      default: return "bg-muted";
    }
  };

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case "정보": return "text-blue-600 bg-blue-50";
      case "주의": return "text-yellow-600 bg-yellow-50";
      case "경고": return "text-orange-600 bg-orange-50";
      case "위험": return "text-red-600 bg-red-50";
      default: return "text-muted-foreground bg-muted/50";
    }
  };

  return (
    <div className="p-6 space-y-6 bg-background min-h-screen">
      {/* 헤더 */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-foreground">시스템 관리 대시보드</h1>
          <p className="text-muted-foreground mt-1">SAM 시스템 전체 현황 및 관리</p>
        </div>
        <div className="flex space-x-3">
          <Button size="sm" className="samsung-button">
            <RefreshCw className="w-4 h-4 mr-2" />
            새로고침
          </Button>
          <Button size="sm" variant="outline">
            <Settings className="w-4 h-4 mr-2" />
            설정
          </Button>
        </div>
      </div>

      {/* 시스템 상태 개요 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card className="samsung-card">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">서버 상태</CardTitle>
            <Server className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between">
              <div>
                <div className="text-2xl font-bold text-green-600">
                  {systemStatus.servers.online}/{systemStatus.servers.total}
                </div>
                <p className="text-xs text-muted-foreground">온라인/전체</p>
              </div>
              <div className="text-right">
                <Badge className="bg-green-500 text-white mb-1">
                  {systemStatus.servers.online}대 정상
                </Badge>
                {systemStatus.servers.warning > 0 && (
                  <Badge className="bg-yellow-500 text-white block">
                    {systemStatus.servers.warning}대 주의
                  </Badge>
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="samsung-card">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">데이터베이스</CardTitle>
            <Database className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <span className="text-2xl font-bold text-blue-600">
                  {systemStatus.database.connections}
                </span>
                <span className="text-sm text-muted-foreground">
                  /{systemStatus.database.maxConnections} 연결
                </span>
              </div>
              <Progress 
                value={(systemStatus.database.connections / systemStatus.database.maxConnections) * 100} 
                className="h-2" 
              />
              <p className="text-xs text-muted-foreground">
                성능: {systemStatus.database.queryPerformance}%
              </p>
            </div>
          </CardContent>
        </Card>

        <Card className="samsung-card">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">사용자 현황</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              <div className="flex justify-between">
                <span className="text-2xl font-bold text-primary">
                  {systemStatus.users.active}
                </span>
                <span className="text-sm text-muted-foreground">
                  /{systemStatus.users.total} 활성
                </span>
              </div>
              <div className="flex justify-between text-xs">
                <span className="text-green-600">
                  <UserCheck className="w-3 h-3 inline mr-1" />
                  오늘 로그인: {systemStatus.users.loginToday}
                </span>
              </div>
              <div className="text-xs text-muted-foreground">
                신규 가입: {systemStatus.users.newToday}명
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="samsung-card">
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">보안 상태</CardTitle>
            <Shield className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <Badge className="bg-green-500 text-white">
                  {systemStatus.security.threatLevel}
                </Badge>
                <CheckCircle className="h-5 w-5 text-green-500" />
              </div>
              <div className="text-xs space-y-1">
                <div className="flex justify-between">
                  <span>차단된 공격:</span>
                  <span className="font-medium">{systemStatus.security.blockedAttacks}</span>
                </div>
                <div className="flex justify-between">
                  <span>보안 이벤트:</span>
                  <span className="font-medium">{systemStatus.security.securityEvents}</span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 시스템 리소스 및 성능 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card className="samsung-card">
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Activity className="w-5 h-5" />
              <span>시스템 사용량 트렌드</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300} minHeight={300}>
              <AreaChart data={usageTrend}>
                <CartesianGrid strokeDasharray="3 3" stroke="#e0e0e0" />
                <XAxis dataKey="time" stroke="#666" />
                <YAxis stroke="#666" />
                <Tooltip />
                <Area type="monotone" dataKey="cpu" stackId="1" stroke="#1428A0" fill="#1428A0" name="CPU %" />
                <Area type="monotone" dataKey="memory" stackId="1" stroke="#00D084" fill="#00D084" name="메모리 %" />
                <Area type="monotone" dataKey="network" stackId="1" stroke="#FF6B35" fill="#FF6B35" name="네트워크 %" />
                <Legend />
              </AreaChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <Card className="samsung-card">
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Users className="w-5 h-5" />
              <span>사용자 활동 분석</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300} minHeight={300}>
              <PieChart>
                <Pie
                  data={userActivity}
                  cx="50%"
                  cy="50%"
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                >
                  {userActivity.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      {/* 서버 리소스 상세 */}
      <Card className="samsung-card">
        <CardHeader>
          <CardTitle className="flex items-center space-x-2">
            <Server className="w-5 h-5" />
            <span>서버 리소스 현황</span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {serverResources.map((server) => (
              <div key={server.name} className="p-4 border rounded-2xl bg-muted/50 dark:bg-muted/20">
                <div className="flex justify-between items-center mb-3">
                  <h4 className="font-semibold">{server.name}</h4>
                  <Badge className={getStatusColor(server.status)}>
                    {server.status}
                  </Badge>
                </div>
                <div className="space-y-3">
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="flex items-center">
                        <Cpu className="w-3 h-3 mr-1" />
                        CPU
                      </span>
                      <span>{server.cpu}%</span>
                    </div>
                    <Progress value={server.cpu} className="h-2" />
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="flex items-center">
                        <MemoryStick className="w-3 h-3 mr-1" />
                        메모리
                      </span>
                      <span>{server.memory}%</span>
                    </div>
                    <Progress value={server.memory} className="h-2" />
                  </div>
                  <div>
                    <div className="flex justify-between text-sm mb-1">
                      <span className="flex items-center">
                        <HardDrive className="w-3 h-3 mr-1" />
                        디스크
                      </span>
                      <span>{server.disk}%</span>
                    </div>
                    <Progress value={server.disk} className="h-2" />
                  </div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 데이터베이스 성능 및 보안 로그 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Card className="samsung-card">
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Database className="w-5 h-5" />
              <span>데이터베이스 성능</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {dbPerformance.map((item, index) => (
                <div key={index} className="flex justify-between items-center p-3 bg-muted/50 dark:bg-muted/20 rounded-lg">
                  <span className="font-medium">{item.metric}</span>
                  <div className="flex items-center space-x-2">
                    <span className="font-semibold">{item.value}</span>
                    {item.status === "excellent" && <CheckCircle className="w-4 h-4 text-green-500" />}
                    {item.status === "good" && <CheckCircle className="w-4 h-4 text-blue-500" />}
                    {item.status === "warning" && <AlertTriangle className="w-4 h-4 text-yellow-500" />}
                  </div>
                </div>
              ))}
            </div>
            <div className="mt-4 p-3 bg-blue-50 rounded-lg">
              <div className="flex items-center justify-between">
                <span className="text-sm font-medium">마지막 백업</span>
                <span className="text-sm text-blue-600">{systemStatus.database.lastBackup}</span>
              </div>
              <Badge className="bg-green-500 text-white mt-2">
                {systemStatus.database.backupStatus}
              </Badge>
            </div>
          </CardContent>
        </Card>

        <Card className="samsung-card">
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Shield className="w-5 h-5" />
              <span>보안 이벤트 로그</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3 max-h-80 overflow-y-auto custom-scrollbar">
              {securityEvents.map((event, index) => (
                <div key={index} className="flex justify-between items-start p-3 border rounded-lg">
                  <div className="flex-1">
                    <div className="flex items-center space-x-2 mb-1">
                      <span className="text-sm font-medium">{event.event}</span>
                      <Badge className={`text-xs ${getSeverityColor(event.severity)}`}>
                        {event.severity}
                      </Badge>
                    </div>
                    <div className="text-xs text-muted-foreground space-y-1">
                      <div>사용자: {event.user}</div>
                      <div>IP: {event.ip}</div>
                    </div>
                  </div>
                  <div className="text-xs text-muted-foreground flex items-center">
                    <Clock className="w-3 h-3 mr-1" />
                    {event.time}
                  </div>
                </div>
              ))}
            </div>
            <div className="mt-4 flex space-x-2">
              <Button size="sm" variant="outline" className="flex-1">
                <Eye className="w-4 h-4 mr-2" />
                전체 로그 보기
              </Button>
              <Button size="sm" variant="outline">
                <RefreshCw className="w-4 h-4" />
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 시스템 알림 및 작업 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <Card className="samsung-card">
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <AlertTriangle className="w-5 h-5" />
              <span>시스템 알림</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="p-3 bg-yellow-50 border-l-4 border-yellow-400 rounded">
                <div className="flex justify-between items-start">
                  <div>
                    <p className="font-medium text-sm">DB-01 메모리 사용량 높음</p>
                    <p className="text-xs text-muted-foreground mt-1">85% 사용 중 - 주의 필요</p>
                  </div>
                  <Badge className="bg-yellow-500 text-white text-xs">주의</Badge>
                </div>
              </div>
              <div className="p-3 bg-orange-50 border-l-4 border-orange-400 rounded">
                <div className="flex justify-between items-start">
                  <div>
                    <p className="font-medium text-sm">API-01 CPU 과부하</p>
                    <p className="text-xs text-muted-foreground mt-1">89% 사용 중 - 확인 필요</p>
                  </div>
                  <Badge className="bg-orange-500 text-white text-xs">경고</Badge>
                </div>
              </div>
              <div className="p-3 bg-green-50 border-l-4 border-green-400 rounded">
                <div className="flex justify-between items-start">
                  <div>
                    <p className="font-medium text-sm">백업 완료</p>
                    <p className="text-xs text-muted-foreground mt-1">오늘 02:00 자동 백업 성공</p>
                  </div>
                  <Badge className="bg-green-500 text-white text-xs">정보</Badge>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="samsung-card">
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Settings className="w-5 h-5" />
              <span>빠른 작업</span>
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <Button variant="outline" className="w-full justify-start">
              <Users className="w-4 h-4 mr-2" />
              사용자 관리
            </Button>
            <Button variant="outline" className="w-full justify-start">
              <Database className="w-4 h-4 mr-2" />
              데이터베이스 백업
            </Button>
            <Button variant="outline" className="w-full justify-start">
              <Shield className="w-4 h-4 mr-2" />
              보안 스캔 실행
            </Button>
            <Button variant="outline" className="w-full justify-start">
              <FileText className="w-4 h-4 mr-2" />
              시스템 로그 내보내기
            </Button>
            <Button variant="outline" className="w-full justify-start">
              <RefreshCw className="w-4 h-4 mr-2" />
              서비스 재시작
            </Button>
          </CardContent>
        </Card>

        <Card className="samsung-card">
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Activity className="w-5 h-5" />
              <span>시스템 상태 요약</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="flex justify-between items-center">
                <span className="text-sm">전체 서버</span>
                <div className="flex items-center space-x-2">
                  <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                  <span className="text-sm font-medium">87.5% 정상</span>
                </div>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm">데이터베이스</span>
                <div className="flex items-center space-x-2">
                  <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                  <span className="text-sm font-medium">98.5% 성능</span>
                </div>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm">보안 상태</span>
                <div className="flex items-center space-x-2">
                  <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                  <span className="text-sm font-medium">안전</span>
                </div>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm">사용자 활동</span>
                <div className="flex items-center space-x-2">
                  <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                  <span className="text-sm font-medium">71% 활성</span>
                </div>
              </div>
              <div className="pt-3 border-t">
                <div className="text-xs text-muted-foreground text-center">
                  마지막 업데이트: {new Date().toLocaleTimeString()}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}