"use client";

import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import {
  Brain,
  Activity,
  AlertTriangle,
  CheckCircle,
  TrendingUp,
  TrendingDown,
  Battery,
  Thermometer,
  RefreshCw,
  ChevronRight,
  Zap,
  Shield,
} from "lucide-react";

interface DevicePrediction {
  device_id: string;
  device_name: string;
  prediction_available: boolean;
  health_score: number;
  risk_level: "low" | "medium" | "high";
  battery_level?: number;
  battery_trend?: string;
  battery_days_remaining?: number;
  risk_factors: Array<{
    factor: string;
    value: number;
    impact: string;
    recommendation: string;
  }>;
  recommendations: string[];
}

interface FleetHealth {
  total_devices: number;
  healthy: number;
  warning: number;
  critical: number;
  unknown: number;
  average_health_score: number;
  devices_needing_attention: Array<{
    device_id: string;
    health_score: number;
    risk_level: string;
  }>;
}

interface Device {
  id: string;
  name: string;
  device_type: string;
  is_online: boolean;
}

export default function PredictionsPage() {
  const API_URL = process.env.NEXT_PUBLIC_API_URL || "https://smart-life.online";
  const [fleetHealth, setFleetHealth] = useState<FleetHealth | null>(null);
  const [devices, setDevices] = useState<Device[]>([]);
  const [selectedDevice, setSelectedDevice] = useState<string | null>(null);
  const [devicePrediction, setDevicePrediction] = useState<DevicePrediction | null>(null);
  const [loading, setLoading] = useState(true);
  const [predictionLoading, setPredictionLoading] = useState(false);

  const fetchData = async () => {
    try {
      api.loadToken();
      const token = localStorage.getItem("token");

      const [devicesRes, healthRes] = await Promise.all([
        api.getDevices({ page_size: 100 }),
        fetch(`${API_URL}/api/v1/predictions/fleet-health`, {
          headers: { Authorization: `Bearer ${token}` }
        }).then(r => r.ok ? r.json() : null).catch(() => null),
      ]);
      
      setDevices(devicesRes.items || []);
      if (healthRes) {
        setFleetHealth(healthRes);
      }
    } catch (error) {
      console.error("Failed to fetch data:", error);
    } finally {
      setLoading(false);
    }
  };

  const fetchDevicePrediction = async (deviceId: string) => {
    setPredictionLoading(true);
    try {
      const token = localStorage.getItem("token");
      const res = await fetch(`${API_URL}/api/v1/predictions/device/${deviceId}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      if (res.ok) {
        const prediction = await res.json();
        setDevicePrediction(prediction);
      } else {
        setDevicePrediction(null);
      }
    } catch (error) {
      console.error("Failed to fetch prediction:", error);
      setDevicePrediction(null);
    } finally {
      setPredictionLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  useEffect(() => {
    if (selectedDevice) {
      fetchDevicePrediction(selectedDevice);
    }
  }, [selectedDevice]);

  const getHealthColor = (score: number) => {
    if (score >= 80) return "text-green-600";
    if (score >= 50) return "text-yellow-600";
    return "text-red-600";
  };

  const getHealthBg = (score: number) => {
    if (score >= 80) return "bg-green-100 dark:bg-green-900/30";
    if (score >= 50) return "bg-yellow-100 dark:bg-yellow-900/30";
    return "bg-red-100 dark:bg-red-900/30";
  };

  const getRiskBadge = (level: string) => {
    const styles = {
      low: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
      medium: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",
      high: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",
    };
    const labels = { low: "منخفض", medium: "متوسط", high: "عالي" };
    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${styles[level as keyof typeof styles] || styles.low}`}>
        {labels[level as keyof typeof labels] || level}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
            <Brain className="w-7 h-7 text-purple-600" />
            توقعات AI والتحليل الذكي
          </h1>
          <p className="text-gray-500 dark:text-gray-400 mt-1">
            تحليل صحة الأجهزة وتوقع الأعطال باستخدام الذكاء الاصطناعي
          </p>
        </div>
        <button
          onClick={fetchData}
          className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50"
        >
          <RefreshCw className="w-4 h-4" />
          تحديث
        </button>
      </div>

      {/* Fleet Health Overview */}
      {fleetHealth && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
            <div className="flex items-center gap-3">
              <div className="p-3 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
                <Activity className="w-6 h-6 text-blue-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">معدل الصحة</p>
                <p className={`text-2xl font-bold ${getHealthColor(fleetHealth.average_health_score)}`}>
                  {fleetHealth.average_health_score}%
                </p>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
            <div className="flex items-center gap-3">
              <div className="p-3 bg-green-100 dark:bg-green-900/30 rounded-lg">
                <CheckCircle className="w-6 h-6 text-green-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">أجهزة سليمة</p>
                <p className="text-2xl font-bold text-green-600">{fleetHealth.healthy}</p>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
            <div className="flex items-center gap-3">
              <div className="p-3 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg">
                <AlertTriangle className="w-6 h-6 text-yellow-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">تحتاج مراقبة</p>
                <p className="text-2xl font-bold text-yellow-600">{fleetHealth.warning}</p>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
            <div className="flex items-center gap-3">
              <div className="p-3 bg-red-100 dark:bg-red-900/30 rounded-lg">
                <Zap className="w-6 h-6 text-red-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">حرجة</p>
                <p className="text-2xl font-bold text-red-600">{fleetHealth.critical}</p>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-gray-800 rounded-xl p-4 border border-gray-200 dark:border-gray-700">
            <div className="flex items-center gap-3">
              <div className="p-3 bg-gray-100 dark:bg-gray-700 rounded-lg">
                <Shield className="w-6 h-6 text-gray-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">إجمالي</p>
                <p className="text-2xl font-bold text-gray-900 dark:text-white">{fleetHealth.total_devices}</p>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Main Content */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Devices List */}
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <div className="p-4 border-b border-gray-200 dark:border-gray-700">
            <h2 className="font-semibold text-gray-900 dark:text-white">اختر جهازاً للتحليل</h2>
          </div>
          <div className="divide-y divide-gray-200 dark:divide-gray-700 max-h-[500px] overflow-y-auto">
            {devices.map((device) => (
              <button
                key={device.id}
                onClick={() => setSelectedDevice(device.id)}
                className={`w-full p-4 text-start hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors ${
                  selectedDevice === device.id ? "bg-primary/5 border-r-2 border-primary" : ""
                }`}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className={`w-2 h-2 rounded-full ${device.is_online ? "bg-green-500" : "bg-red-500"}`} />
                    <div>
                      <p className="font-medium text-gray-900 dark:text-white">{device.name}</p>
                      <p className="text-xs text-gray-500">{device.device_type}</p>
                    </div>
                  </div>
                  <ChevronRight className="w-4 h-4 text-gray-400" />
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* Device Prediction */}
        <div className="lg:col-span-2 space-y-4">
          {!selectedDevice ? (
            <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-8 text-center">
              <Brain className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                اختر جهازاً لعرض التحليل
              </h3>
              <p className="text-gray-500">
                اختر جهازاً من القائمة لعرض تحليل صحته وتوقعات الأعطال
              </p>
            </div>
          ) : predictionLoading ? (
            <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-8 text-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
              <p className="text-gray-500 mt-4">جاري التحليل...</p>
            </div>
          ) : devicePrediction ? (
            <>
              {/* Health Score Card */}
              <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                    {devicePrediction.device_name}
                  </h3>
                  {getRiskBadge(devicePrediction.risk_level)}
                </div>

                <div className="flex items-center gap-6">
                  {/* Health Score Gauge */}
                  <div className="relative w-32 h-32">
                    <svg className="w-full h-full transform -rotate-90">
                      <circle
                        cx="64"
                        cy="64"
                        r="56"
                        stroke="currentColor"
                        strokeWidth="12"
                        fill="none"
                        className="text-gray-200 dark:text-gray-700"
                      />
                      <circle
                        cx="64"
                        cy="64"
                        r="56"
                        stroke="currentColor"
                        strokeWidth="12"
                        fill="none"
                        strokeDasharray={`${(devicePrediction.health_score / 100) * 352} 352`}
                        className={getHealthColor(devicePrediction.health_score)}
                      />
                    </svg>
                    <div className="absolute inset-0 flex items-center justify-center">
                      <span className={`text-2xl font-bold ${getHealthColor(devicePrediction.health_score)}`}>
                        {devicePrediction.health_score}%
                      </span>
                    </div>
                  </div>

                  <div className="flex-1 space-y-3">
                    {/* نسبة البطارية الفعلية */}
                    {devicePrediction.battery_level !== undefined && devicePrediction.battery_level !== null && (
                      <div className="flex items-center gap-3">
                        <Battery className={`w-5 h-5 ${
                          devicePrediction.battery_level < 20 ? "text-red-500" :
                          devicePrediction.battery_level < 50 ? "text-yellow-500" : "text-green-500"
                        }`} />
                        <div className="flex-1">
                          <div className="flex items-center justify-between">
                            <p className="text-sm text-gray-500">مستوى البطارية</p>
                            <span className={`text-lg font-bold ${
                              devicePrediction.battery_level < 20 ? "text-red-500" :
                              devicePrediction.battery_level < 50 ? "text-yellow-500" : "text-green-500"
                            }`}>
                              {devicePrediction.battery_level}%
                            </span>
                          </div>
                          <div className="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-full mt-1">
                            <div 
                              className={`h-full rounded-full ${
                                devicePrediction.battery_level < 20 ? "bg-red-500" :
                                devicePrediction.battery_level < 50 ? "bg-yellow-500" : "bg-green-500"
                              }`}
                              style={{ width: `${devicePrediction.battery_level}%` }}
                            />
                          </div>
                        </div>
                      </div>
                    )}
                    
                    {/* اتجاه البطارية */}
                    {devicePrediction.battery_trend && (
                      <div className="flex items-center gap-3">
                        {devicePrediction.battery_trend === "decreasing" ? (
                          <TrendingDown className="w-5 h-5 text-red-500" />
                        ) : devicePrediction.battery_trend === "charging" ? (
                          <TrendingUp className="w-5 h-5 text-green-500" />
                        ) : (
                          <Activity className="w-5 h-5 text-blue-500" />
                        )}
                        <div>
                          <p className="text-sm text-gray-500">اتجاه البطارية</p>
                          <p className="font-medium text-gray-900 dark:text-white">
                            {devicePrediction.battery_trend === "decreasing" ? "تتناقص" :
                             devicePrediction.battery_trend === "charging" ? "تشحن" : "مستقرة"}
                            {devicePrediction.battery_days_remaining && (
                              <span className="text-sm text-orange-500 mr-2">
                                (متبقي ~{devicePrediction.battery_days_remaining} يوم)
                              </span>
                            )}
                          </p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>

              {/* Risk Factors */}
              {devicePrediction.risk_factors && devicePrediction.risk_factors.length > 0 && (
                <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                    عوامل الخطر
                  </h3>
                  <div className="space-y-3">
                    {devicePrediction.risk_factors.map((factor, index) => (
                      <div
                        key={index}
                        className={`p-4 rounded-lg ${
                          factor.impact === "high" ? "bg-red-50 dark:bg-red-900/20" :
                          factor.impact === "medium" ? "bg-yellow-50 dark:bg-yellow-900/20" :
                          "bg-blue-50 dark:bg-blue-900/20"
                        }`}
                      >
                        <div className="flex items-start justify-between">
                          <div>
                            <p className="font-medium text-gray-900 dark:text-white">
                              {factor.factor.replace(/_/g, " ")}
                            </p>
                            <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                              {factor.recommendation}
                            </p>
                          </div>
                          <span className={`text-sm font-medium ${
                            factor.impact === "high" ? "text-red-600" :
                            factor.impact === "medium" ? "text-yellow-600" : "text-blue-600"
                          }`}>
                            {factor.value}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Recommendations */}
              {devicePrediction.recommendations && devicePrediction.recommendations.length > 0 && (
                <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6">
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                    التوصيات
                  </h3>
                  <ul className="space-y-2">
                    {devicePrediction.recommendations.map((rec, index) => (
                      <li key={index} className="flex items-start gap-2">
                        <CheckCircle className="w-5 h-5 text-green-500 mt-0.5 flex-shrink-0" />
                        <span className="text-gray-700 dark:text-gray-300">{rec}</span>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </>
          ) : (
            <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-8 text-center">
              <AlertTriangle className="w-16 h-16 text-yellow-500 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                لا تتوفر بيانات كافية
              </h3>
              <p className="text-gray-500">
                لا تتوفر بيانات كافية لتحليل هذا الجهاز. يرجى الانتظار حتى يتم جمع المزيد من القراءات.
              </p>
            </div>
          )}
        </div>
      </div>

      {/* Devices Needing Attention */}
      {fleetHealth && fleetHealth.devices_needing_attention.length > 0 && (
        <div className="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
          <div className="p-4 border-b border-gray-200 dark:border-gray-700">
            <h2 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
              <AlertTriangle className="w-5 h-5 text-yellow-500" />
              أجهزة تحتاج إلى اهتمام
            </h2>
          </div>
          <div className="p-4">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {fleetHealth.devices_needing_attention.map((device) => (
                <button
                  key={device.device_id}
                  onClick={() => setSelectedDevice(device.device_id)}
                  className="p-4 border border-gray-200 dark:border-gray-700 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700/50 text-start"
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-medium text-gray-900 dark:text-white">
                      {devices.find(d => d.id === device.device_id)?.name || device.device_id.slice(0, 8)}
                    </span>
                    {getRiskBadge(device.risk_level)}
                  </div>
                  <div className="flex items-center gap-2">
                    <div className={`h-2 flex-1 rounded-full ${getHealthBg(device.health_score)}`}>
                      <div
                        className={`h-full rounded-full ${
                          device.health_score >= 80 ? "bg-green-500" :
                          device.health_score >= 50 ? "bg-yellow-500" : "bg-red-500"
                        }`}
                        style={{ width: `${device.health_score}%` }}
                      />
                    </div>
                    <span className={`text-sm font-medium ${getHealthColor(device.health_score)}`}>
                      {device.health_score}%
                    </span>
                  </div>
                </button>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
