import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import {
  getCurrentISTTime,
  getCurrentISTDateTime,
} from "../../utils/timeUtils";
import {
  FaServer,
  FaDatabase,
  FaCheckCircle,
  FaExclamationTriangle,
  FaInfoCircle,
  FaNetworkWired,
  FaShieldAlt,
  FaHdd,
  FaClock,
} from "react-icons/fa";
import { buildApiUrl, API_ENDPOINTS } from "../../utils/config";

const DashboardStatus = () => {
  const { isLight } = useTheme();
  const [systemStatus, setSystemStatus] = useState({
    server: "online",
    database: "connected",
    network: "stable",
    security: "active",
    storage: "normal",
    systemLoad: "low",
    metrics: {
      platform: "Unknown",
      cpu: { cores: "Unknown" },
      memory: { usage: "Unknown" },
      uptime: "Unknown",
    },
  });
  const [lastUpdate, setLastUpdate] = useState(getCurrentISTTime());
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // Fetch real system status data from API
  const fetchSystemStatus = async () => {
    try {
      setLoading(true);
      setError(null);

      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.SYSTEM_HEALTH_STATUS)
      );

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      setSystemStatus({
        server: data.server,
        database: data.database,
        network: data.network,
        security: data.security,
        storage: data.storage,
        systemLoad: data.systemLoad,
        metrics: data.metrics,
      });
      setLastUpdate(getCurrentISTTime());
    } catch (error) {
      console.error("Error fetching system status:", error);
      setError(error.message);
      // Set fallback status on error
      setSystemStatus((prev) => ({
        ...prev,
        server: "unknown",
        database: "unknown",
        network: "unknown",
        security: "unknown",
        storage: "unknown",
        metrics: {
          platform: "Unknown",
          cpu: { cores: "Unknown" },
          memory: { usage: "Unknown" },
          uptime: "Unknown",
        },
      }));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSystemStatus();

    // Update every 30 seconds for real-time monitoring
    const interval = setInterval(fetchSystemStatus, 30000);

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

  const getStatusColor = (status) => {
    switch (status) {
      case "online":
      case "connected":
      case "stable":
      case "active":
      case "normal":
      case "low":
        return isLight ? "text-green-600" : "text-green-400";
      case "offline":
      case "disconnected":
      case "unstable":
      case "inactive":
      case "critical":
      case "high":
        return isLight ? "text-red-600" : "text-red-400";
      case "medium":
      case "warning":
        return isLight ? "text-yellow-600" : "text-yellow-400";
      case "unknown":
        return isLight ? "text-gray-600" : "text-gray-400";
      default:
        return isLight ? "text-blue-600" : "text-blue-400";
    }
  };

  const getStatusIcon = (status) => {
    switch (status) {
      case "online":
      case "connected":
      case "stable":
      case "active":
      case "normal":
      case "low":
        return <FaCheckCircle className="text-green-500 animate-pulse" />;
      case "offline":
      case "disconnected":
      case "unstable":
      case "inactive":
      case "critical":
      case "high":
        return (
          <FaExclamationTriangle className="text-red-500 animate-bounce" />
        );
      case "medium":
      case "warning":
        return <FaInfoCircle className="text-yellow-500" />;
      case "unknown":
        return <FaInfoCircle className="text-gray-500" />;
      default:
        return <FaInfoCircle className="text-blue-500" />;
    }
  };

  const getStatusPriority = (status) => {
    if (["offline", "disconnected", "critical", "high"].includes(status))
      return "high";
    if (["medium", "warning"].includes(status)) return "medium";
    if (["unknown"].includes(status)) return "unknown";
    return "low";
  };

  const getPriorityRing = (priority) => {
    switch (priority) {
      case "high":
        return "ring-2 ring-red-300 animate-pulse";
      case "medium":
        return "ring-2 ring-yellow-300";
      case "unknown":
        return "ring-2 ring-gray-300";
      default:
        return "";
    }
  };

  const statusItems = [
    {
      label: "Server Status",
      value: systemStatus.server,
      icon: <FaServer className="text-blue-500" />,
      status: systemStatus.server,
      priority: getStatusPriority(systemStatus.server),
    },
    {
      label: "Database",
      value: systemStatus.database,
      icon: <FaDatabase className="text-purple-500" />,
      status: systemStatus.database,
      priority: getStatusPriority(systemStatus.database),
    },
    {
      label: "Network",
      value: systemStatus.network,
      icon: <FaNetworkWired className="text-cyan-500" />,
      status: systemStatus.network,
      priority: getStatusPriority(systemStatus.network),
    },
    {
      label: "Security",
      value: systemStatus.security,
      icon: <FaShieldAlt className="text-emerald-500" />,
      status: systemStatus.security,
      priority: getStatusPriority(systemStatus.security),
    },
    {
      label: "Storage",
      value: systemStatus.storage,
      icon: <FaHdd className="text-orange-500" />,
      status: systemStatus.storage,
      priority: getStatusPriority(systemStatus.storage),
    },
    {
      label: "System Load",
      value: systemStatus.systemLoad,
      icon: <FaServer className="text-indigo-500" />,
      status: systemStatus.systemLoad,
      priority: getStatusPriority(systemStatus.systemLoad),
    },
  ];

  return (
    <div
      className={`mt-8 border-t ${
        isLight ? "border-amber-200" : "border-slate-700"
      }`}
    >
      <div
        className={`p-6 ${
          isLight ? "bg-white/50" : "bg-slate-800/50"
        } rounded-lg`}
      >
        {/* System Status Grid */}
        <div className="mb-6">
          <div className="mb-4">
            <h4
              className={`text-lg font-semibold ${
                isLight ? "text-amber-700" : "text-slate-300"
              }`}
            >
              System Health
            </h4>
          </div>

          {/* Error Display */}
          {error && (
            <div
              className={`mb-4 p-3 rounded-lg ${
                isLight
                  ? "bg-red-50 border border-red-200"
                  : "bg-red-900/20 border border-red-800"
              }`}
            >
              <p
                className={`text-sm ${
                  isLight ? "text-red-700" : "text-red-300"
                }`}
              >
                Error: {error}
              </p>
            </div>
          )}

          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
            {statusItems.map((item, index) => (
              <div
                key={index}
                className={`p-3 rounded-lg border-2 transition-all duration-200 ${
                  isLight
                    ? "bg-white/70 border-amber-200 hover:border-amber-300"
                    : "bg-slate-700/50 border-slate-600 hover:border-slate-500"
                } ${getPriorityRing(item.priority)}`}
              >
                <div className="flex items-center gap-2 mb-2">
                  {item.icon}
                  <span
                    className={`text-xs font-medium ${
                      isLight ? "text-amber-700" : "text-slate-300"
                    }`}
                  >
                    {item.label}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  {loading ? (
                    <div className="animate-spin h-4 w-4 border-2 border-blue-600 border-t-transparent rounded-full"></div>
                  ) : (
                    getStatusIcon(item.status)
                  )}
                  <span
                    className={`text-sm font-bold ${getStatusColor(
                      item.status
                    )}`}
                  >
                    {loading ? "..." : item.value}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default DashboardStatus;
