import React, { useState, useEffect } from 'react';
import {
  Grid,
  Card,
  Text,
  Group,
  Stack,
  Badge,
  RingProgress,
  SimpleGrid,
  Title,
  ThemeIcon,
  Loader,
} from '@mantine/core';
import {
  IconApps,
  IconKey,
  IconUsers,
  IconActivity,
  IconTrendingUp,
  IconAlertTriangle,
} from '@tabler/icons-react';
import { apiService } from '../services/apiService';

interface DashboardStats {
  totalApplications: number;
  totalTokens: number;
  recentActivity: number;
  systemHealth: 'healthy' | 'warning' | 'error';
}

const Dashboard: React.FC = () => {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);

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

  const loadDashboardData = async () => {
    try {
      setLoading(true);
      
      // Load applications and tokens data
      const [appsResponse] = await Promise.all([
        apiService.getApplications(100, 0),
      ]);

      // Calculate stats
      const dashboardStats: DashboardStats = {
        totalApplications: appsResponse.count,
        totalTokens: 0, // We'd need to aggregate from all apps
        recentActivity: 0,
        systemHealth: 'healthy',
      };

      setStats(dashboardStats);
    } catch (error) {
      console.error('Failed to load dashboard data:', error);
      setStats({
        totalApplications: 0,
        totalTokens: 0,
        recentActivity: 0,
        systemHealth: 'error',
      });
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <Stack align="center" justify="center" h={400}>
        <Loader size="lg" />
        <Text>Loading dashboard...</Text>
      </Stack>
    );
  }

  const statCards = [
    {
      title: 'Applications',
      value: stats?.totalApplications || 0,
      icon: IconApps,
      color: 'blue',
      description: 'Active applications',
    },
    {
      title: 'API Tokens',
      value: stats?.totalTokens || 0,
      icon: IconKey,
      color: 'green',
      description: 'Generated tokens',
    },
    {
      title: 'Recent Activity',
      value: stats?.recentActivity || 0,
      icon: IconActivity,
      color: 'orange',
      description: 'Events today',
    },
    {
      title: 'System Health',
      value: stats?.systemHealth === 'healthy' ? '100%' : '85%',
      icon: stats?.systemHealth === 'healthy' ? IconTrendingUp : IconAlertTriangle,
      color: stats?.systemHealth === 'healthy' ? 'green' : 'yellow',
      description: 'System status',
    },
  ];

  return (
    <Stack gap="lg">
      <div>
        <Title order={2} mb="xs">
          Dashboard Overview
        </Title>
        <Text c="dimmed">
          Monitor your key management system status and metrics
        </Text>
      </div>

      <SimpleGrid cols={{ base: 1, sm: 2, lg: 4 }} spacing="lg">
        {statCards.map((stat) => (
          <Card key={stat.title} shadow="sm" radius="md" withBorder p="lg">
            <Group justify="space-between" mb="xs">
              <Text size="sm" c="dimmed" fw={500}>
                {stat.title}
              </Text>
              <ThemeIcon color={stat.color} variant="light" size="lg">
                <stat.icon size={20} />
              </ThemeIcon>
            </Group>

            <Text size="xl" fw={700} mb="xs">
              {stat.value}
            </Text>

            <Text size="xs" c="dimmed">
              {stat.description}
            </Text>
          </Card>
        ))}
      </SimpleGrid>

      <Grid>
        <Grid.Col span={{ base: 12, md: 8 }}>
          <Card shadow="sm" radius="md" withBorder p="lg" h={300}>
            <Title order={3} mb="md">
              Activity Timeline
            </Title>
            <Stack justify="center" align="center" h={200}>
              <Text c="dimmed" ta="center">
                Activity timeline will be displayed here
                <br />
                <Text size="xs" c="dimmed">
                  Integration with audit events coming soon
                </Text>
              </Text>
            </Stack>
          </Card>
        </Grid.Col>

        <Grid.Col span={{ base: 12, md: 4 }}>
          <Card shadow="sm" radius="md" withBorder p="lg" h={300}>
            <Title order={3} mb="md">
              System Status
            </Title>
            <Stack gap="md" align="center">
              <RingProgress
                size={120}
                thickness={12}
                sections={[
                  {
                    value: stats?.systemHealth === 'healthy' ? 100 : 85,
                    color: stats?.systemHealth === 'healthy' ? 'green' : 'yellow',
                  },
                ]}
                label={
                  <Text ta="center" fw={700} size="lg">
                    {stats?.systemHealth === 'healthy' ? '100%' : '85%'}
                  </Text>
                }
              />
              <Badge
                color={stats?.systemHealth === 'healthy' ? 'green' : 'yellow'}
                variant="light"
                size="lg"
              >
                {stats?.systemHealth === 'healthy' ? 'Healthy' : 'Warning'}
              </Badge>
              <Text size="sm" c="dimmed" ta="center">
                All systems operational
              </Text>
            </Stack>
          </Card>
        </Grid.Col>
      </Grid>
    </Stack>
  );
};

export default Dashboard;