import { useState, useEffect, memo } from 'react';
import { 
  Container, 
  Title, 
  Text, 
  SimpleGrid,
  Paper,
  Group,
  ThemeIcon,
  Loader,
  Center,
  Stack,
  Image,
} from '@mantine/core';
import { 
  IconUsers, 
  IconWebhook, 
  IconBrandWhatsapp, 
  IconFileText,
  IconDatabase,
  IconCpu,
  IconDeviceDesktopAnalytics,
  IconNetwork,
} from '@tabler/icons-react';
import { apiClient } from '../lib/api';

interface DashboardStats {
  users: number;
  hooks: number;
  accounts: number;
  eventLogs: number;
  messageCacheEnabled: boolean;
  messageCacheCount: number;
}

interface RuntimeStats {
  goMemoryMB: number;
  goCPUPercent: number;
  networkBytesPerSec: number;
}

const StatCard = memo(function StatCard({ 
  title, 
  value, 
  icon: Icon, 
  color,
  valueColor,
}: { 
  title: string; 
  value: number | string;
  icon: any; 
  color: string;
  valueColor?: string;
}) {
  return (
    <Paper withBorder p="md" radius="md">
      <Group justify="space-between">
        <div>
          <Text c="dimmed" tt="uppercase" fw={700} fz="xs">
            {title}
          </Text>
          <Text fw={700} fz="xl" mt="md" c={valueColor}>
            {typeof value === 'number' ? value.toLocaleString() : value}
          </Text>
        </div>
        <ThemeIcon 
          color={color} 
          variant="light" 
          size={60} 
          radius="md"
        >
          <Icon size={32} stroke={1.5} />
        </ThemeIcon>
      </Group>
    </Paper>
  );
});

export default function DashboardPage() {
  const logoSrc = `${import.meta.env.BASE_URL}logo.png`;
  const [stats, setStats] = useState<DashboardStats>({
    users: 0,
    hooks: 0,
    accounts: 0,
    eventLogs: 0,
    messageCacheEnabled: false,
    messageCacheCount: 0,
  });
  const [runtimeStats, setRuntimeStats] = useState<RuntimeStats>({
    goMemoryMB: 0,
    goCPUPercent: 0,
    networkBytesPerSec: 0,
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadDashboardStats();
    const intervalID = window.setInterval(loadDashboardStats, 60000);
    return () => window.clearInterval(intervalID);
  }, []);

  useEffect(() => {
    loadRuntimeStats();
    const intervalID = window.setInterval(loadRuntimeStats, 5000);
    return () => window.clearInterval(intervalID);
  }, []);

  const loadDashboardStats = async () => {
    try {
      setLoading(true);
      const [usersResult, hooksResult, accountsResult, eventLogsResult, messageCacheResult] = await Promise.allSettled([
        apiClient.getUsers(),
        apiClient.getHooks(),
        apiClient.getAccounts(),
        apiClient.getEventLogs({ limit: 1, offset: 0, sort: '-created_at' }),
        apiClient.getMessageCacheStats(),
      ]);

      const users = usersResult.status === 'fulfilled' ? usersResult.value : [];
      const hooks = hooksResult.status === 'fulfilled' ? hooksResult.value : [];
      const accounts = accountsResult.status === 'fulfilled' ? accountsResult.value : [];
      const eventLogs = eventLogsResult.status === 'fulfilled' ? eventLogsResult.value : null;
      const messageCache = messageCacheResult.status === 'fulfilled' ? messageCacheResult.value : null;

      const eventLogCount = eventLogs?.meta?.total ?? eventLogs?.data?.length ?? 0;
      const messageCacheEnabled = !!messageCache?.enabled;
      const messageCacheCount = messageCache?.total_count ?? messageCache?.count ?? 0;

      setStats({
        users: users?.length || 0,
        hooks: hooks?.length || 0,
        accounts: accounts?.length || 0,
        eventLogs: eventLogCount,
        messageCacheEnabled,
        messageCacheCount,
      });

      if (usersResult.status === 'rejected' || hooksResult.status === 'rejected' || accountsResult.status === 'rejected' || eventLogsResult.status === 'rejected' || messageCacheResult.status === 'rejected') {
        console.error('One or more dashboard stats failed to load', {
          users: usersResult.status === 'rejected' ? usersResult.reason : null,
          hooks: hooksResult.status === 'rejected' ? hooksResult.reason : null,
          accounts: accountsResult.status === 'rejected' ? accountsResult.reason : null,
          eventLogs: eventLogsResult.status === 'rejected' ? eventLogsResult.reason : null,
          messageCache: messageCacheResult.status === 'rejected' ? messageCacheResult.reason : null,
        });
      }
    } catch (err) {
      console.error('Failed to load stats:', err);
    } finally {
      setLoading(false);
    }
  };

  const loadRuntimeStats = async () => {
    try {
      const systemStats = await apiClient.getSystemStats();
      setRuntimeStats({
        goMemoryMB: Number(systemStats?.go_memory_mb ?? 0),
        goCPUPercent: Number(systemStats?.go_cpu_percent ?? 0),
        networkBytesPerSec: Number(systemStats?.network_bytes_per_sec ?? 0),
      });
    } catch (err) {
      console.error('Failed to load runtime stats:', err);
    }
  };

  if (loading) {
    return (
      <Container size="xl" py="xl">
        <Center h={400}>
          <Loader size="lg" />
        </Center>
      </Container>
    );
  }

  return (
    <Container size="xl" py="xl">
      <Stack gap="xl">
        <div>
          <Image src={logoSrc} alt="WhatsHooked logo" w={120} h={120} fit="contain" mb="sm" />
          <Title order={2}>Dashboard</Title>
          <Text c="dimmed" size="sm">Welcome to WhatsHooked Admin Panel</Text>
        </div>

        <SimpleGrid cols={{ base: 1, sm: 2, md: 3, lg: 4 }}>
          <StatCard
            title="Total Users"
            value={stats.users}
            icon={IconUsers}
            color="blue"
          />
          <StatCard
            title="Active Hooks"
            value={stats.hooks}
            icon={IconWebhook}
            color="teal"
          />
          <StatCard
            title="WhatsApp Accounts"
            value={stats.accounts}
            icon={IconBrandWhatsapp}
            color="green"
          />
          <StatCard
            title="Event Logs"
            value={stats.eventLogs}
            icon={IconFileText}
            color="violet"
          />
          <StatCard
            title="Message Cache"
            value={stats.messageCacheEnabled ? stats.messageCacheCount : 'Disabled'}
            icon={IconDatabase}
            color={stats.messageCacheEnabled ? 'green' : 'gray'}
            valueColor={stats.messageCacheEnabled ? undefined : 'dimmed'}
          />
          <StatCard
            title="Go Memory"
            value={`${runtimeStats.goMemoryMB.toFixed(2)} MB`}
            icon={IconDeviceDesktopAnalytics}
            color="cyan"
          />
          <StatCard
            title="Go CPU"
            value={`${runtimeStats.goCPUPercent.toFixed(2)}%`}
            icon={IconCpu}
            color="orange"
          />
          <StatCard
            title="Network Throughput"
            value={`${(runtimeStats.networkBytesPerSec / 1024).toFixed(2)} KB/s`}
            icon={IconNetwork}
            color="indigo"
          />
        </SimpleGrid>
      </Stack>
    </Container>
  );
}
