import { useEffect, useMemo, useState } from 'react';
import {
  Clock,
  Database,
  HardDrive,
  RadioTower,
  Server,
  ShieldCheck,
} from 'lucide-react';

import { TopBar } from '@/components/layout/TopBar';
import { MetricCard } from '@/components/dashboard/MetricCard';
import { IpPoolChart } from '@/components/dashboard/IpPoolChart';
import { NetworkTrafficChart } from '@/components/dashboard/NetworkTrafficChart';

import { ProvisioningWizard } from '@/components/provisioning/ProvisioningWizard';
import { BackendSettings } from '@/components/settings/BackendSettings';
import { ActivityLogs } from '@/components/activity/ActivityLogs';
import { Card } from '@/components/ui/Card';
import { Udp2rawConfig } from '@/components/udp2raw/Udp2rawConfig';
import { ControllersRoute } from '@/components/controllers/ControllersRoute';

import { vpnApi } from '@/services/vpnApi';
import { vpsApi } from '@/services/vpsApi';

import type {
  UsedIpsResponse,
  VpsHealth,
} from '@/types/api';

export function DashboardRoute() {
  const [health, setHealth] =
    useState<VpsHealth | null>(null);

  const [usedIps, setUsedIps] =
    useState<UsedIpsResponse | null>(null);

  const [error, setError] = useState('');

  useEffect(() => {
    async function loadDashboard() {
      try {
        const [
          healthResponse,
          usedIpsResponse,
        ] = await Promise.all([
          vpsApi.health(),
          vpnApi.usedIps(),
        ]);

        setHealth(healthResponse);
        setUsedIps(usedIpsResponse);
        setError('');
      } catch (err) {
        setHealth(null);
        setUsedIps(null);
        setError(String(err));
      }
    }

    loadDashboard();

    const intervalId = window.setInterval(
      loadDashboard,
      15000,
    );

    return () => {
      window.clearInterval(intervalId);
    };
  }, []);

  const ipPoolTotal =
    health?.ipPoolTotal ?? 65534;

  const usedCount =
    health?.ipPoolUsed ??
    usedIps?.count ??
    0;

  const ipPoolPercent = useMemo(() => {
    return (
      (usedCount / ipPoolTotal) *
      100
    ).toFixed(2);
  }, [usedCount, ipPoolTotal]);

  const backendHealthy =
    health?.backend === true;

  const vpnHealthy =
    health?.wireGuardRunning === true;

  const udp2rawHealthy =
    health?.udp2rawActive === true;

  const dashboardReady =
    !error &&
    Boolean(health) &&
    backendHealthy &&
    vpnHealthy &&
    udp2rawHealthy;

  return (
    <div className="flex min-h-full flex-col">
      <TopBar healthy={dashboardReady} />

      {error && (
        <div className="mb-4 rounded-2xl border border-red-500/20 bg-red-500/10 p-4 text-sm text-red-300">
          Erro no backend do painel: {error}
        </div>
      )}

      <div className="grid gap-4 lg:grid-cols-2 2xl:grid-cols-12">
        <div className="2xl:col-span-3">
          <MetricCard
            title="VPN"
            value={vpnHealthy ? 'Ligada' : 'Offline'}
            subtitle={
              health?.wireGuardInterface
                ? `Interface ${health.wireGuardInterface}`
                : 'WireGuard wg0'
            }
            icon={<ShieldCheck size={22} />}
            tone={vpnHealthy ? 'green' : 'red'}
          />
        </div>

        <div className="2xl:col-span-3">
          <MetricCard
            title="UDP2RAW"
            value={udp2rawHealthy ? 'Ativo' : 'Offline'}
            subtitle={health?.udp2rawService ?? 'udp2raw-wg'}
            icon={<RadioTower size={22} />}
            tone={udp2rawHealthy ? 'purple' : 'red'}
          />
        </div>

        <div className="2xl:col-span-2">
          <MetricCard
            title="Pool IP"
            value={`${ipPoolPercent}%`}
            subtitle={`${usedCount} / ${ipPoolTotal} usados`}
            icon={<Database size={22} />}
            tone="blue"
          />
        </div>

        <div className="2xl:col-span-2">
          <MetricCard
            title="Disco"
            value={`${health?.diskUsagePercent ?? 0}%`}
            subtitle={`Memória ${health?.memoryUsagePercent ?? 0}%`}
            icon={<HardDrive size={22} />}
            tone={
              (health?.diskUsagePercent ?? 0) > 85
                ? 'red'
                : 'blue'
            }
          />
        </div>

        <div className="lg:col-span-2 2xl:col-span-2">
          <MetricCard
            title="Backend"
            value={backendHealthy ? 'Saudável' : 'Offline'}
            subtitle="Conectividade API"
            icon={<Server size={22} />}
            tone={backendHealthy ? 'green' : 'red'}
          />
        </div>
      </div>

      <div className="mt-4 grid gap-4 2xl:grid-cols-12">
        <div className="min-h-[360px] 2xl:col-span-7">
          <NetworkTrafficChart
            title="Tráfego WireGuard"
            subtitle="Débito RX/TX wg0 em direto"
            mode="wireguard"
          />
        </div>

        <div className="min-h-[360px] 2xl:col-span-5">
          <NetworkTrafficChart
            title="Tráfego UDP2RAW"
            subtitle="Faketcp na porta 444"
            mode="udp2raw"
          />
        </div>
      </div>

      <div className="mt-4 grid gap-4 pb-4 xl:grid-cols-12">
        <Card className="min-h-[260px] xl:col-span-5">
          <div className="flex h-full flex-col justify-between">
            <div>
              <div className="mb-4 flex items-center gap-3">
                <div className="rounded-2xl bg-blue-500/10 p-3 text-blue-300">
                  <Clock size={20} />
                </div>

                <div className="min-w-0">
                  <h3 className="font-semibold text-white">
                    Estado da VPS
                  </h3>

                  <p className="text-xs text-slate-500">
                    Uptime e carga do sistema
                  </p>
                </div>
              </div>

              <p className="text-xl font-black leading-tight text-white 2xl:text-2xl">
                {health?.systemUptime ?? 'Desconhecido'}
              </p>

              <p className="mt-3 break-all font-mono text-xs text-slate-400">
                Load: {health?.loadAverage ?? '—'}
              </p>

              <p className="mt-2 break-all font-mono text-xs text-slate-500">
                IP: {health?.publicIp ?? '—'}
              </p>
            </div>

            <div className="mt-5 rounded-2xl border border-white/10 bg-white/[0.03] p-3">
              <div className="mb-2 flex justify-between text-xs text-slate-500">
                <span>Memória</span>
                <span>{health?.memoryUsagePercent ?? 0}%</span>
              </div>

              <div className="h-2 overflow-hidden rounded-full bg-slate-800">
                <div
                  className="h-full rounded-full bg-blue-400"
                  style={{
                    width: `${Math.min(
                      health?.memoryUsagePercent ?? 0,
                      100,
                    )}%`,
                  }}
                />
              </div>
            </div>
          </div>
        </Card>

        <div className="min-h-[340px] xl:col-span-7">
          <IpPoolChart
            used={usedCount}
            total={ipPoolTotal}
          />
        </div>
      </div>
    </div>
  );
}

export function PlaceholderRoute({
  name,
}: {
  name: string;
}) {
  return (
    <Card>
      <h2 className="text-2xl font-bold">
        {name}
      </h2>

      <p className="mt-2 text-slate-400">
        Estrutura do ecrã pronta para
        implementação em produção.
      </p>
    </Card>
  );
}

export function RouteView({
  active,
}: {
  active: string;
}) {
  if (active === 'Painel') {
    return <DashboardRoute />;
  }

  if (active === 'Controladores') {
    return <ControllersRoute />;
  }

  if (active === 'Provisionamento') {
    return <ProvisioningWizard />;
  }

  if (active === 'Configuração UDP2RAW') {
    return <Udp2rawConfig />;
  }

  if (active === 'Registos de Atividade') {
    return <ActivityLogs />;
  }

  if (active === 'Posto de Trabalho') {
    return <BackendSettings />;
  }

  return <PlaceholderRoute name={active} />;
}