"use client";

import React, { useState, useEffect } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { RefreshCw, AlertTriangle, Cloud, Construction } from "lucide-react";
import { apiClient } from "@/lib/api/client";
import { DashboardElement } from "@/components/admin/dashboard/types";

// 알림 타입
type AlertType = "accident" | "weather" | "construction";

// 알림 인터페이스
interface Alert {
  id: string;
  type: AlertType;
  severity: "high" | "medium" | "low";
  title: string;
  location: string;
  description: string;
  timestamp: string;
}

interface RiskAlertWidgetProps {
  element?: DashboardElement;
}

export default function RiskAlertWidget({ element }: RiskAlertWidgetProps) {
  const [alerts, setAlerts] = useState<Alert[]>([]);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [filter, setFilter] = useState<AlertType | "all">("all");
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const [newAlertIds, setNewAlertIds] = useState<Set<string>>(new Set());

  // 데이터 로드 (백엔드 통합 호출)
  const loadData = async () => {
    setIsRefreshing(true);
    try {
      // 백엔드 API 호출 (교통사고, 기상특보, 도로공사 통합)
      const response = await apiClient.get<{ 
        success: boolean; 
        data: Alert[]; 
        count: number;
        lastUpdated?: string;
        cached?: boolean;
      }>("/risk-alerts");

      if (response.data.success && response.data.data) {
        const newData = response.data.data;
        
        // 새로운 알림 감지
        const oldIds = new Set(alerts.map(a => a.id));
        const newIds = new Set<string>();
        newData.forEach(alert => {
          if (!oldIds.has(alert.id)) {
            newIds.add(alert.id);
          }
        });
        
        setAlerts(newData);
        setNewAlertIds(newIds);
        setLastUpdated(new Date());
        
        // 3초 후 새 알림 애니메이션 제거
        if (newIds.size > 0) {
          setTimeout(() => setNewAlertIds(new Set()), 3000);
        }
      } else {
        console.error("❌ 리스크 알림 데이터 로드 실패");
        setAlerts([]);
      }
    } catch (error: any) {
      console.error("❌ 리스크 알림 API 오류:", error.message);
      // API 오류 시 빈 배열 유지
      setAlerts([]);
    } finally {
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    loadData();
    // 1분마다 자동 새로고침 (60000ms)
    const interval = setInterval(loadData, 60000);
    return () => clearInterval(interval);
  }, []);

  // 필터링된 알림
  const filteredAlerts = filter === "all" ? alerts : alerts.filter((alert) => alert.type === filter);

  // 심각도별 색상
  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case "high":
        return "border-red-500";
      case "medium":
        return "border-yellow-500";
      case "low":
        return "border-blue-500";
      default:
        return "border-gray-500";
    }
  };

  // 심각도별 배지 색상
  const getSeverityBadge = (severity: string) => {
    switch (severity) {
      case "high":
        return "bg-red-100 text-red-700";
      case "medium":
        return "bg-yellow-100 text-yellow-700";
      case "low":
        return "bg-blue-100 text-blue-700";
      default:
        return "bg-gray-100 text-gray-700";
    }
  };

  // 알림 타입별 아이콘
  const getAlertIcon = (type: AlertType) => {
    switch (type) {
      case "accident":
        return <AlertTriangle className="h-5 w-5 text-red-600" />;
      case "weather":
        return <Cloud className="h-5 w-5 text-blue-600" />;
      case "construction":
        return <Construction className="h-5 w-5 text-yellow-600" />;
    }
  };

  // 알림 타입별 한글명
  const getAlertTypeName = (type: AlertType) => {
    switch (type) {
      case "accident":
        return "교통사고";
      case "weather":
        return "날씨특보";
      case "construction":
        return "도로공사";
    }
  };

  // 시간 포맷
  const formatTime = (isoString: string) => {
    const date = new Date(isoString);
    const now = new Date();
    const diffMinutes = Math.floor((now.getTime() - date.getTime()) / 60000);

    if (diffMinutes < 1) return "방금 전";
    if (diffMinutes < 60) return `${diffMinutes}분 전`;
    const diffHours = Math.floor(diffMinutes / 60);
    if (diffHours < 24) return `${diffHours}시간 전`;
    return `${Math.floor(diffHours / 24)}일 전`;
  };

  // 통계 계산
  const stats = {
    accident: alerts.filter((a) => a.type === "accident").length,
    weather: alerts.filter((a) => a.type === "weather").length,
    construction: alerts.filter((a) => a.type === "construction").length,
    high: alerts.filter((a) => a.severity === "high").length,
  };

  return (
    <div className="flex h-full w-full flex-col gap-3 overflow-hidden bg-slate-50 p-3">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <AlertTriangle className="h-5 w-5 text-red-600" />
          <h3 className="text-base font-semibold text-gray-900">{element?.customTitle || "리스크 / 알림"}</h3>
          {stats.high > 0 && (
            <Badge className="bg-red-100 text-red-700 hover:bg-red-100">긴급 {stats.high}건</Badge>
          )}
        </div>
        <div className="flex items-center gap-2">
          {lastUpdated && newAlertIds.size > 0 && (
            <Badge className="bg-blue-100 text-blue-700 text-xs animate-pulse">
              새 알림 {newAlertIds.size}건
            </Badge>
          )}
          {lastUpdated && (
            <span className="text-xs text-gray-500">
              {lastUpdated.toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' })}
            </span>
          )}
          <Button variant="ghost" size="sm" onClick={loadData} disabled={isRefreshing} className="h-8 px-2">
            <RefreshCw className={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />
          </Button>
        </div>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-3 gap-2">
        <Card
          className={`cursor-pointer border-l-4 border-red-500 p-2 transition-colors hover:bg-gray-50 ${filter === "accident" ? "bg-gray-100" : ""}`}
          onClick={() => setFilter(filter === "accident" ? "all" : "accident")}
        >
          <div className="text-xs text-gray-600">교통사고</div>
          <div className="text-lg font-bold text-gray-900">{stats.accident}건</div>
        </Card>
        <Card
          className={`cursor-pointer border-l-4 border-blue-500 p-2 transition-colors hover:bg-gray-50 ${filter === "weather" ? "bg-gray-100" : ""}`}
          onClick={() => setFilter(filter === "weather" ? "all" : "weather")}
        >
          <div className="text-xs text-gray-600">날씨특보</div>
          <div className="text-lg font-bold text-gray-900">{stats.weather}건</div>
        </Card>
        <Card
          className={`cursor-pointer border-l-4 border-yellow-500 p-2 transition-colors hover:bg-gray-50 ${filter === "construction" ? "bg-gray-100" : ""}`}
          onClick={() => setFilter(filter === "construction" ? "all" : "construction")}
        >
          <div className="text-xs text-gray-600">도로공사</div>
          <div className="text-lg font-bold text-gray-900">{stats.construction}건</div>
        </Card>
      </div>

      {/* 필터 상태 표시 */}
      {filter !== "all" && (
        <div className="flex items-center gap-2">
          <Badge variant="outline" className="text-xs">
            {getAlertTypeName(filter)} 필터 적용 중
          </Badge>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setFilter("all")}
            className="h-6 px-2 text-xs text-gray-600"
          >
            전체 보기
          </Button>
        </div>
      )}

      {/* 알림 목록 */}
      <div className="flex-1 space-y-2 overflow-y-auto">
        {filteredAlerts.length === 0 ? (
          <Card className="p-4 text-center">
            <div className="text-sm text-gray-500">알림이 없습니다</div>
          </Card>
        ) : (
          filteredAlerts.map((alert) => (
            <Card 
              key={alert.id} 
              className={`border-l-4 p-3 transition-all duration-300 ${getSeverityColor(alert.severity)} ${
                newAlertIds.has(alert.id) ? 'bg-blue-50/30 ring-1 ring-blue-200' : ''
              }`}
            >
              <div className="flex items-start justify-between gap-2">
                <div className="flex items-start gap-2">
                  {getAlertIcon(alert.type)}
                  <div className="flex-1">
                    <div className="flex items-center gap-2">
                      <h4 className="text-sm font-semibold text-gray-900">{alert.title}</h4>
                      {newAlertIds.has(alert.id) && (
                        <Badge className="bg-blue-100 text-blue-700 text-xs">
                          NEW
                        </Badge>
                      )}
                      <Badge className={`text-xs ${getSeverityBadge(alert.severity)}`}>
                        {alert.severity === "high" ? "긴급" : alert.severity === "medium" ? "주의" : "정보"}
                      </Badge>
                    </div>
                    <p className="mt-1 text-xs font-medium text-gray-700">{alert.location}</p>
                    <p className="mt-1 text-xs text-gray-600">{alert.description}</p>
                  </div>
                </div>
              </div>
              <div className="mt-2 text-right text-xs text-gray-500">{formatTime(alert.timestamp)}</div>
            </Card>
          ))
        )}
      </div>

      {/* 안내 메시지 */}
      <div className="border-t border-gray-200 pt-2 text-center text-xs text-gray-500">
        💡 1분마다 자동으로 업데이트됩니다
      </div>
    </div>
  );
}

