import React, { useEffect, useState } from 'react';
import {
  Box,
  SimpleGrid,
  Stat,
  StatLabel,
  StatNumber,
  StatHelpText,
  StatArrow,
  Heading,
  Text,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  Badge,
  VStack,
  HStack,
  Spinner,
  Icon,
  Card,
  CardBody,
  Link,
} from '@chakra-ui/react';
import { FiEye, FiTrendingUp, FiFileText, FiUsers } from 'react-icons/fi';
import api from '../../services/api';
import { Link as RouterLink } from 'react-router-dom';

type AnalyticsStats = {
  total_page_views: number;
  unique_visitors: number;
  total_articles: number;
  published_articles: number;
  page_views_today: number;
  page_views_week: number;
  unique_visitors_week: number;
  avg_time_on_site: number;
};

type TopPage = {
  page_path: string;
  page_name: string;
  view_count: number;
  unique_visitors: number;
};

type TopArticle = {
  id: number;
  title: string;
  slug: string;
  view_count: number;
  published_at: string;
};

const AnalyticsDashboard: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState<AnalyticsStats | null>(null);
  const [topPages, setTopPages] = useState<TopPage[]>([]);
  const [topArticles, setTopArticles] = useState<TopArticle[]>([]);

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

  const loadAnalytics = async () => {
    setLoading(true);
    try {
      // Load overview stats
      const statsRes = await api.get('/admin/analytics/overview');
      setStats(statsRes.data);

      // Load top pages
      const pagesRes = await api.get('/admin/analytics/top-pages?limit=10');
      setTopPages(pagesRes.data || []);

      // Load top articles
      const articlesRes = await api.get('/admin/analytics/top-articles?limit=10');
      setTopArticles(articlesRes.data || []);
    } catch (error) {
      console.error('Failed to load analytics:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <Box textAlign="center" py={10}>
        <Spinner size="xl" />
        <Text mt={4} color="gray.600">Načítám statistiky...</Text>
      </Box>
    );
  }

  return (
    <VStack align="stretch" spacing={6}>
      <Heading size="lg">Analytika a statistiky</Heading>

      {/* Overview Stats */}
      <SimpleGrid columns={{ base: 1, md: 2, lg: 4 }} spacing={4}>
        <Card>
          <CardBody>
            <Stat>
              <HStack>
                <Icon as={FiEye} boxSize={6} color="blue.500" />
                <StatLabel>Celkem zobrazení</StatLabel>
              </HStack>
              <StatNumber>{stats?.total_page_views || 0}</StatNumber>
              <StatHelpText>
                <StatArrow type="increase" />
                {stats?.page_views_today || 0} dnes
              </StatHelpText>
            </Stat>
          </CardBody>
        </Card>

        <Card>
          <CardBody>
            <Stat>
              <HStack>
                <Icon as={FiUsers} boxSize={6} color="green.500" />
                <StatLabel>Unikátní návštěvníci</StatLabel>
              </HStack>
              <StatNumber>{stats?.unique_visitors || 0}</StatNumber>
              <StatHelpText>
                {stats?.unique_visitors_week || 0} tento týden
              </StatHelpText>
            </Stat>
          </CardBody>
        </Card>

        <Card>
          <CardBody>
            <Stat>
              <HStack>
                <Icon as={FiFileText} boxSize={6} color="purple.500" />
                <StatLabel>Publikované články</StatLabel>
              </HStack>
              <StatNumber>{stats?.published_articles || 0}</StatNumber>
              <StatHelpText>
                z {stats?.total_articles || 0} celkem
              </StatHelpText>
            </Stat>
          </CardBody>
        </Card>

        <Card>
          <CardBody>
            <Stat>
              <HStack>
                <Icon as={FiTrendingUp} boxSize={6} color="orange.500" />
                <StatLabel>Zobrazení (týden)</StatLabel>
              </HStack>
              <StatNumber>{stats?.page_views_week || 0}</StatNumber>
              <StatHelpText>
                Ø {Math.round((stats?.page_views_week || 0) / 7)} / den
              </StatHelpText>
            </Stat>
          </CardBody>
        </Card>
      </SimpleGrid>

      {/* Top Articles */}
      <Box>
        <Heading size="md" mb={4}>Nejčtenější články</Heading>
        <Card>
          <CardBody>
            {topArticles.length === 0 ? (
              <Text color="gray.600">Zatím žádná data</Text>
            ) : (
              <Table size="sm">
                <Thead>
                  <Tr>
                    <Th>Článek</Th>
                    <Th isNumeric>Zobrazení</Th>
                    <Th>Datum publikace</Th>
                    <Th>Akce</Th>
                  </Tr>
                </Thead>
                <Tbody>
                  {topArticles.map((article, index) => (
                    <Tr key={article.id}>
                      <Td>
                        <HStack>
                          <Badge colorScheme="blue">{index + 1}</Badge>
                          <Text fontWeight="medium">{article.title}</Text>
                        </HStack>
                      </Td>
                      <Td isNumeric>
                        <Badge colorScheme="green">{article.view_count}</Badge>
                      </Td>
                      <Td>
                        <Text fontSize="sm" color="gray.600">
                          {new Date(article.published_at).toLocaleDateString('cs-CZ')}
                        </Text>
                      </Td>
                      <Td>
                        <HStack spacing={2}>
                          <Link
                            as={RouterLink}
                            to={`/blog/${article.slug}`}
                            fontSize="sm"
                            color="blue.600"
                          >
                            Zobrazit
                          </Link>
                          <Link
                            as={RouterLink}
                            to={`/admin/clanky?edit=${article.id}`}
                            fontSize="sm"
                            color="purple.600"
                          >
                            Upravit
                          </Link>
                        </HStack>
                      </Td>
                    </Tr>
                  ))}
                </Tbody>
              </Table>
            )}
          </CardBody>
        </Card>
      </Box>

      {/* Top Pages */}
      <Box>
        <Heading size="md" mb={4}>Nejnavštěvovanější stránky</Heading>
        <Card>
          <CardBody>
            {topPages.length === 0 ? (
              <Text color="gray.600">Zatím žádná data</Text>
            ) : (
              <Table size="sm">
                <Thead>
                  <Tr>
                    <Th>Stránka</Th>
                    <Th>Cesta</Th>
                    <Th isNumeric>Zobrazení</Th>
                    <Th isNumeric>Unikátní</Th>
                  </Tr>
                </Thead>
                <Tbody>
                  {topPages.map((page, index) => (
                    <Tr key={page.page_path}>
                      <Td>
                        <HStack>
                          <Badge colorScheme="purple">{index + 1}</Badge>
                          <Text>{page.page_name || page.page_path}</Text>
                        </HStack>
                      </Td>
                      <Td>
                        <Text fontSize="sm" color="gray.600" fontFamily="mono">
                          {page.page_path}
                        </Text>
                      </Td>
                      <Td isNumeric>
                        <Badge colorScheme="blue">{page.view_count}</Badge>
                      </Td>
                      <Td isNumeric>
                        <Badge colorScheme="green">{page.unique_visitors}</Badge>
                      </Td>
                    </Tr>
                  ))}
                </Tbody>
              </Table>
            )}
          </CardBody>
        </Card>
      </Box>
    </VStack>
  );
};

export default AnalyticsDashboard;
