import { useState, useEffect } from "react";
import { Link } from "react-router";
import {
  Server,
  CheckCircle,
  XCircle,
  Clock,
  TrendingUp,
  AlertTriangle,
  Activity,
} from "lucide-react";

interface ServerStatus {
  id: string;
  name: string;
  url: string;
  status: "online" | "offline" | "warning";
  responseTime: number;
  uptime: number;
  lastCheck: string;
  checkType: string;
}

export function Dashboard() {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
    
  const [servers,setServers] = useState<ServerStatus[]>([
    {
      id: "1",
      name: "Production APIs",
      url: "https://api.example.com",
      status: "online",
      responseTime: 142,
      uptime: 99.9,
      lastCheck: "2 min ago",
      checkType: "HTTPS",
    },
    {
      id: "2",
      name: "Database Server",
      url: "db.example.com:5432",
      status: "online",
      responseTime: 45,
      uptime: 100,
      lastCheck: "1 min ago",
      checkType: "TCP",
    },
    {
      id: "3",
      name: "CDN Edge Node",
      url: "https://cdn.example.com",
      status: "warning",
      responseTime: 890,
      uptime: 98.5,
      lastCheck: "30 sec ago",
      checkType: "HTTPS",
    },
    {
      id: "4",
      name: "Mail Server",
      url: "mail.example.com",
      status: "offline",
      responseTime: 0,
      uptime: 95.2,
      lastCheck: "5 min ago",
      checkType: "SMTP",
    },
    {
      id: "5",
      name: "Analytics Service",
      url: "https://analytics.example.com",
      status: "online",
      responseTime: 210,
      uptime: 99.7,
      lastCheck: "3 min ago",
      checkType: "HTTPS",
    },
    {
      id: "6",
      name: "Backup Server",
      url: "backup.example.com:22",
      status: "online",
      responseTime: 78,
      uptime: 99.95,
      lastCheck: "1 min ago",
      checkType: "SSH",
    },
  ]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await fetch('https://bitrix.tavres.ru/rest/1/2jkuss1wwr0vnkkt/iblock.servers');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const result = await response.json();
        setServers([...servers, ...result['result']]);
        setError(null);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
    const intervalId = setInterval(fetchData, 5000);
    return () => clearInterval(intervalId);
  },[])
  
  const onlineCount = servers.filter((s) => s.status === "online").length;
  const offlineCount = servers.filter((s) => s.status === "offline").length;
  const warningCount = servers.filter((s) => s.status === "warning").length;
  const avgResponseTime = Math.round(
    servers.reduce((acc, s) => acc + s.responseTime, 0) / servers.length
  );

  const getStatusColor = (status: string) => {
    switch (status) {
      case "online":
        return "bg-emerald-100 text-emerald-700 border-emerald-200";
      case "offline":
        return "bg-rose-100 text-rose-700 border-rose-200";
      case "warning":
        return "bg-amber-100 text-amber-700 border-amber-200";
      default:
        return "bg-gray-100 text-gray-700 border-gray-200";
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "online":
        return <CheckCircle className="w-5 h-5" />;
      case "offline":
        return <XCircle className="w-5 h-5" />;
      case "warning":
        return <AlertTriangle className="w-5 h-5" />;
      default:
        return <Clock className="w-5 h-5" />;
    }
  };

  return (
    <div className="max-w-7xl mx-auto px-6 py-8">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">System Overview</h1>
        <p className="text-gray-600">Real-time monitoring of all servers and services</p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div className="bg-white rounded-2xl p-6 shadow-md border border-gray-100">
          <div className="flex items-center justify-between mb-4">
            <div className="bg-emerald-100 p-3 rounded-xl">
              <CheckCircle className="w-6 h-6 text-emerald-600" />
            </div>
            <span className="text-3xl font-bold text-emerald-600">{onlineCount}</span>
          </div>
          <h3 className="text-gray-600 font-medium">Online</h3>
          <p className="text-sm text-gray-500">Servers running</p>
        </div>

        <div className="bg-white rounded-2xl p-6 shadow-md border border-gray-100">
          <div className="flex items-center justify-between mb-4">
            <div className="bg-rose-100 p-3 rounded-xl">
              <XCircle className="w-6 h-6 text-rose-600" />
            </div>
            <span className="text-3xl font-bold text-rose-600">{offlineCount}</span>
          </div>
          <h3 className="text-gray-600 font-medium">Offline</h3>
          <p className="text-sm text-gray-500">Servers down</p>
        </div>

        <div className="bg-white rounded-2xl p-6 shadow-md border border-gray-100">
          <div className="flex items-center justify-between mb-4">
            <div className="bg-amber-100 p-3 rounded-xl">
              <AlertTriangle className="w-6 h-6 text-amber-600" />
            </div>
            <span className="text-3xl font-bold text-amber-600">{warningCount}</span>
          </div>
          <h3 className="text-gray-600 font-medium">Warning</h3>
          <p className="text-sm text-gray-500">Need attention</p>
        </div>

        <div className="bg-white rounded-2xl p-6 shadow-md border border-gray-100">
          <div className="flex items-center justify-between mb-4">
            <div className="bg-blue-100 p-3 rounded-xl">
              <TrendingUp className="w-6 h-6 text-blue-600" />
            </div>
            <span className="text-3xl font-bold text-blue-600">{avgResponseTime}ms</span>
          </div>
          <h3 className="text-gray-600 font-medium">Avg Response</h3>
          <p className="text-sm text-gray-500">Time</p>
        </div>
      </div>

      {/* Server List */}
      <div className="bg-white rounded-2xl shadow-md border border-gray-100 overflow-hidden">
        <div className="px-6 py-4 bg-gradient-to-r from-blue-50 to-indigo-50 border-b border-gray-200">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Server className="w-5 h-5 text-blue-600" />
              <h2 className="text-xl font-bold text-gray-900">Server Status</h2>
            </div>
            <Link
              to="/servers"
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium"
            >
              View All
            </Link>
          </div>
        </div>

        <div className="divide-y divide-gray-100">
          {servers.map((server) => (
            <Link
              key={server.id}
              to={`/servers/${server.id}`}
              className="block px-6 py-4 hover:bg-gray-50 transition-colors"
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-4 flex-1">
                  <div className={`p-2 rounded-lg ${getStatusColor(server.status)}`}>
                    {getStatusIcon(server.status)}
                  </div>
                  <div className="flex-1">
                    <h3 className="font-semibold text-gray-900">{server.name}</h3>
                    <p className="text-sm text-gray-500">{server.url}</p>
                  </div>
                </div>

                <div className="flex items-center gap-8">
                  <div className="text-right">
                    <p className="text-sm font-medium text-gray-900">
                      {server.responseTime > 0 ? `${server.responseTime}ms` : "N/A"}
                    </p>
                    <p className="text-xs text-gray-500">Response Time</p>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-medium text-gray-900">{server.uptime}%</p>
                    <p className="text-xs text-gray-500">Uptime</p>
                  </div>
                  <div className="text-right">
                    <span className="px-3 py-1 bg-gray-100 text-gray-700 rounded-lg text-xs font-medium">
                      {server.checkType}
                    </span>
                  </div>
                  <div className="text-right min-w-[80px]">
                    <div className="flex items-center gap-1 text-gray-500">
                      <Activity className="w-3 h-3" />
                      <p className="text-xs">{server.lastCheck}</p>
                    </div>
                  </div>
                </div>
              </div>
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
}
