import { useState, useEffect, useCallback } from 'react';
import { Card, Typography, Spin, Flex, Button, Statistic, Tooltip } from 'antd';
import {
  BookOutlined,
  ReloadOutlined,
  FileTextOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import type { DashboardDocsAnalytics } from '@/types/api';

const { Text } = Typography;

export default function DocsAnalyticsCard() {
  const navigate = useNavigate();
  const [data, setData] = useState<DashboardDocsAnalytics | null>(null);
  const [loading, setLoading] = useState(true);
  const [hasError, setHasError] = useState(false);

  const fetchAnalytics = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<DashboardDocsAnalytics>('/docs-analytics/summary', {
        params: { days: 30 },
      });
      setData(res.data);
      setHasError(false);
    } catch {
      setHasError(true);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchAnalytics();
    const interval = setInterval(fetchAnalytics, 5 * 60_000);
    return () => clearInterval(interval);
  }, [fetchAnalytics]);

  // Hide if the endpoint isn't available
  if (hasError && !data) return null;

  const avgPerDay = data ? Math.round(data.totalViews / 30) : 0;
  const topPages = data?.topPages?.slice(0, 5) || [];

  return (
    <Card
      title={<span style={{ fontSize: 14 }}><BookOutlined style={{ marginRight: 6, fontSize: 15 }} />Docs Analytics</span>}
      size="small"
      extra={
        <Flex align="center" gap={6}>
          <Button type="link" size="small" onClick={() => navigate('/app/docs/analytics')} style={{ fontSize: 12, padding: 0 }}>
            Full Report
          </Button>
          <Button type="text" size="small" icon={<ReloadOutlined spin={loading} style={{ fontSize: 13 }} />} onClick={fetchAnalytics} />
        </Flex>
      }
      styles={{ body: { padding: '6px 14px 8px' } }}
    >
      {loading && !data ? (
        <div style={{ textAlign: 'center', padding: 12 }}><Spin size="small" /></div>
      ) : data ? (
        <>
          <Flex gap={16} wrap="wrap" style={{ marginBottom: 8 }}>
            <Statistic
              title={<Text style={{ fontSize: 11 }}>Page Views</Text>}
              value={data.totalViews}
              valueStyle={{ fontSize: 18 }}
            />
            <Statistic
              title={<Text style={{ fontSize: 11 }}>Sessions</Text>}
              value={data.uniqueSessions}
              valueStyle={{ fontSize: 18 }}
            />
            <Statistic
              title={<Text style={{ fontSize: 11 }}>Avg/Day</Text>}
              value={avgPerDay}
              valueStyle={{ fontSize: 18 }}
            />
          </Flex>
          {topPages.length > 0 && (
            <div style={{ borderTop: '1px solid rgba(255,255,255,0.06)', paddingTop: 6 }}>
              <Text type="secondary" style={{ fontSize: 11, display: 'block', marginBottom: 4 }}>Top Pages (30d)</Text>
              {topPages.map((page, i) => (
                <Flex key={i} justify="space-between" style={{ padding: '2px 0' }}>
                  <Tooltip title={page.path}>
                    <Text style={{ fontSize: 12, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '75%' }}>
                      <FileTextOutlined style={{ marginRight: 4, fontSize: 10, color: '#1890ff' }} />
                      {page.path}
                    </Text>
                  </Tooltip>
                  <Text type="secondary" style={{ fontSize: 12, flexShrink: 0 }}>{page.views}</Text>
                </Flex>
              ))}
            </div>
          )}
        </>
      ) : (
        <Text type="secondary" style={{ fontSize: 13, display: 'block', padding: '8px 0' }}>No analytics data</Text>
      )}
    </Card>
  );
}
