"use client";

import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Progress } from "@/components/ui/progress";
import { RefreshCw, Play, Pause, AlertCircle, CheckCircle, Clock } from "lucide-react";
import { toast } from "sonner";
import { BatchAPI, BatchMonitoring } from "@/lib/api/batch";

export default function MonitoringPage() {
  const [monitoring, setMonitoring] = useState<BatchMonitoring | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [autoRefresh, setAutoRefresh] = useState(false);

  useEffect(() => {
    loadMonitoringData();

    let interval: NodeJS.Timeout;
    if (autoRefresh) {
      interval = setInterval(loadMonitoringData, 30000); // 30초마다 자동 새로고침
    }

    return () => {
      if (interval) clearInterval(interval);
    };
  }, [autoRefresh]);

  const loadMonitoringData = async () => {
    setIsLoading(true);
    try {
      const data = await BatchAPI.getBatchMonitoring();
      setMonitoring(data);
    } catch (error) {
      console.error("모니터링 데이터 조회 오류:", error);
      toast.error("모니터링 데이터를 불러오는데 실패했습니다.");
    } finally {
      setIsLoading(false);
    }
  };

  const handleRefresh = () => {
    loadMonitoringData();
  };

  const toggleAutoRefresh = () => {
    setAutoRefresh(!autoRefresh);
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "completed":
        return <CheckCircle className="h-4 w-4 text-green-500" />;
      case "failed":
        return <AlertCircle className="h-4 w-4 text-red-500" />;
      case "running":
        return <Play className="h-4 w-4 text-blue-500" />;
      case "pending":
        return <Clock className="h-4 w-4 text-yellow-500" />;
      default:
        return <Clock className="h-4 w-4 text-gray-500" />;
    }
  };

  const getStatusBadge = (status: string) => {
    const variants = {
      completed: "bg-green-100 text-green-800",
      failed: "bg-destructive/20 text-red-800",
      running: "bg-primary/20 text-blue-800",
      pending: "bg-yellow-100 text-yellow-800",
      cancelled: "bg-gray-100 text-gray-800",
    };

    const labels = {
      completed: "완료",
      failed: "실패",
      running: "실행 중",
      pending: "대기 중",
      cancelled: "취소됨",
    };

    return (
      <Badge className={variants[status as keyof typeof variants] || variants.pending}>
        {labels[status as keyof typeof labels] || status}
      </Badge>
    );
  };

  const formatDuration = (ms: number) => {
    if (ms < 1000) return `${ms}ms`;
    if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
    return `${(ms / 60000).toFixed(1)}m`;
  };

  const getSuccessRate = () => {
    if (!monitoring) return 0;
    const total = monitoring.successful_jobs_today + monitoring.failed_jobs_today;
    if (total === 0) return 100;
    return Math.round((monitoring.successful_jobs_today / total) * 100);
  };

  if (!monitoring) {
    return (
      <div className="flex h-64 items-center justify-center">
        <div className="text-center">
          <RefreshCw className="mx-auto mb-2 h-8 w-8 animate-spin" />
          <p>모니터링 데이터를 불러오는 중...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="w-full max-w-none space-y-8 px-4 py-8">
        {/* 헤더 */}
        <div>
          <h1 className="text-2xl font-bold">모니터링</h1>
          <p className="text-muted-foreground">배치 작업 실행 상태를 실시간으로 모니터링합니다.</p>
        </div>

        {/* 모니터링 대시보드 */}
        <div className="space-y-6">
          {/* 헤더 */}
          <div className="flex items-center justify-between">
            <h2 className="text-2xl font-bold">배치 모니터링</h2>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={toggleAutoRefresh}
                className={autoRefresh ? "bg-accent text-primary" : ""}
              >
                {autoRefresh ? <Pause className="mr-1 h-4 w-4" /> : <Play className="mr-1 h-4 w-4" />}
                자동 새로고침
              </Button>
              <Button variant="outline" size="sm" onClick={handleRefresh} disabled={isLoading}>
                <RefreshCw className={`mr-1 h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
                새로고침
              </Button>
            </div>
          </div>

          {/* 통계 카드 */}
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">총 작업 수</CardTitle>
                <div className="text-2xl">📋</div>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold">{monitoring.total_jobs}</div>
                <p className="text-muted-foreground text-xs">활성: {monitoring.active_jobs}개</p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">실행 중</CardTitle>
                <div className="text-2xl">🔄</div>
              </CardHeader>
              <CardContent>
                <div className="text-primary text-2xl font-bold">{monitoring.running_jobs}</div>
                <p className="text-muted-foreground text-xs">현재 실행 중인 작업</p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">오늘 성공</CardTitle>
                <div className="text-2xl">✅</div>
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-green-600">{monitoring.successful_jobs_today}</div>
                <p className="text-muted-foreground text-xs">성공률: {getSuccessRate()}%</p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">오늘 실패</CardTitle>
                <div className="text-2xl">❌</div>
              </CardHeader>
              <CardContent>
                <div className="text-destructive text-2xl font-bold">{monitoring.failed_jobs_today}</div>
                <p className="text-muted-foreground text-xs">주의가 필요한 작업</p>
              </CardContent>
            </Card>
          </div>

          {/* 성공률 진행바 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">오늘 실행 성공률</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span>성공: {monitoring.successful_jobs_today}건</span>
                  <span>실패: {monitoring.failed_jobs_today}건</span>
                </div>
                <Progress value={getSuccessRate()} className="h-2" />
                <div className="text-muted-foreground text-center text-sm">{getSuccessRate()}% 성공률</div>
              </div>
            </CardContent>
          </Card>

          {/* 최근 실행 이력 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">최근 실행 이력</CardTitle>
            </CardHeader>
            <CardContent>
              {monitoring.recent_executions.length === 0 ? (
                <div className="text-muted-foreground py-8 text-center">최근 실행 이력이 없습니다.</div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>상태</TableHead>
                      <TableHead>작업 ID</TableHead>
                      <TableHead>시작 시간</TableHead>
                      <TableHead>완료 시간</TableHead>
                      <TableHead>실행 시간</TableHead>
                      <TableHead>오류 메시지</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {monitoring.recent_executions.map((execution) => (
                      <TableRow key={execution.id}>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            {getStatusIcon(execution.execution_status)}
                            {getStatusBadge(execution.execution_status)}
                          </div>
                        </TableCell>
                        <TableCell className="font-mono">#{execution.job_id}</TableCell>
                        <TableCell>
                          {execution.started_at ? new Date(execution.started_at).toLocaleString() : "-"}
                        </TableCell>
                        <TableCell>
                          {execution.completed_at ? new Date(execution.completed_at).toLocaleString() : "-"}
                        </TableCell>
                        <TableCell>
                          {execution.execution_time_ms ? formatDuration(execution.execution_time_ms) : "-"}
                        </TableCell>
                        <TableCell className="max-w-xs">
                          {execution.error_message ? (
                            <span className="text-destructive block truncate text-sm">{execution.error_message}</span>
                          ) : (
                            "-"
                          )}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
