import { useState, useEffect, useCallback } from 'react';
import { Row, Col, Card, Statistic, Table, Select, Button, App, Spin, Empty } from 'antd';
import {
  EyeOutlined,
  UserOutlined,
  CalendarOutlined,
  ReloadOutlined,
  LinkOutlined,
} from '@ant-design/icons';
import {
  AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend,
} from 'recharts';
import { useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/types/api';

interface TopPage {
  path: string;
  views: number;
  uniqueSessions: number;
}

interface DayViews {
  date: string;
  views: number;
  uniqueSessions: number;
}

interface TopReferrer {
  referrer: string;
  count: number;
}

interface AnalyticsSummary {
  totalViews: number;
  uniqueSessions: number;
  topPages: TopPage[];
  viewsByDay: DayViews[];
  topReferrers: TopReferrer[];
}

const topPagesColumns = [
  {
    title: 'Page',
    dataIndex: 'path',
    key: 'path',
    ellipsis: true,
    render: (path: string) => (
      <span title={path} style={{ fontFamily: 'monospace', fontSize: 12 }}>
        {path}
      </span>
    ),
  },
  {
    title: 'Views',
    dataIndex: 'views',
    key: 'views',
    width: 90,
    sorter: (a: TopPage, b: TopPage) => a.views - b.views,
    defaultSortOrder: 'descend' as const,
  },
  {
    title: 'Unique',
    dataIndex: 'uniqueSessions',
    key: 'uniqueSessions',
    width: 90,
    sorter: (a: TopPage, b: TopPage) => a.uniqueSessions - b.uniqueSessions,
  },
];

const referrerColumns = [
  {
    title: 'Referrer',
    dataIndex: 'referrer',
    key: 'referrer',
    ellipsis: true,
    render: (url: string) => {
      try {
        const hostname = new URL(url).hostname;
        return (
          <a href={url} target="_blank" rel="noopener noreferrer" title={url}>
            {hostname}
          </a>
        );
      } catch {
        return <span title={url}>{url}</span>;
      }
    },
  },
  {
    title: 'Count',
    dataIndex: 'count',
    key: 'count',
    width: 80,
  },
];

export default function DocsAnalyticsPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [days, setDays] = useState(30);
  const [data, setData] = useState<AnalyticsSummary | null>(null);
  const [loading, setLoading] = useState(true);
  const { message } = App.useApp();

  useEffect(() => {
    setPageHeader({ title: 'Documentation Analytics' });
    return () => setPageHeader(null);
  }, [setPageHeader]);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get('/docs-analytics/summary', { params: { days } });
      setData(res.data);
    } catch {
      message.error('Failed to load analytics data');
    } finally {
      setLoading(false);
    }
  }, [days, message]);

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

  const avgViewsPerDay = data && days > 0
    ? Math.round((data.totalViews / days) * 10) / 10
    : 0;

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
        <div style={{ flex: 1 }} />
        <Select
          value={days}
          onChange={setDays}
          style={{ width: 130 }}
          options={[
            { label: 'Last 7 days', value: 7 },
            { label: 'Last 30 days', value: 30 },
            { label: 'Last 90 days', value: 90 },
          ]}
        />
        <Button icon={<ReloadOutlined />} onClick={fetchData} loading={loading}>
          Refresh
        </Button>
      </div>

      {loading && !data ? (
        <div style={{ textAlign: 'center', padding: 80 }}>
          <Spin size="large" />
        </div>
      ) : !data ? (
        <Empty description="No analytics data available" />
      ) : (
        <>
          {/* Summary Cards */}
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={24} sm={8}>
              <Card>
                <Statistic
                  title="Total Page Views"
                  value={data.totalViews}
                  prefix={<EyeOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card>
                <Statistic
                  title="Unique Sessions"
                  value={data.uniqueSessions}
                  prefix={<UserOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card>
                <Statistic
                  title="Avg Views / Day"
                  value={avgViewsPerDay}
                  prefix={<CalendarOutlined />}
                />
              </Card>
            </Col>
          </Row>

          {/* Views Over Time Chart */}
          <Card title="Views Over Time" style={{ marginBottom: 24 }}>
            {data.viewsByDay.length === 0 ? (
              <Empty description="No data for this period" />
            ) : (
              <div style={{ width: '100%', height: 300 }}>
                <ResponsiveContainer>
                  <AreaChart data={data.viewsByDay} margin={{ top: 4, right: 8, left: -16, bottom: 0 }}>
                    <CartesianGrid strokeDasharray="3 3" strokeOpacity={0.3} />
                    <XAxis
                      dataKey="date"
                      tick={{ fontSize: 11 }}
                      interval="preserveStartEnd"
                    />
                    <YAxis tick={{ fontSize: 11 }} allowDecimals={false} />
                    <Tooltip contentStyle={{ fontSize: 12, borderRadius: 6 }} />
                    <Legend wrapperStyle={{ fontSize: 12 }} />
                    <Area
                      type="monotone"
                      dataKey="views"
                      name="Page Views"
                      stroke="#1890ff"
                      fill="#1890ff"
                      fillOpacity={0.3}
                    />
                    <Area
                      type="monotone"
                      dataKey="uniqueSessions"
                      name="Unique Sessions"
                      stroke="#52c41a"
                      fill="#52c41a"
                      fillOpacity={0.3}
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            )}
          </Card>

          {/* Top Pages + Top Referrers */}
          <Row gutter={[16, 16]}>
            <Col xs={24} lg={14}>
              <Card title="Top Pages">
                <Table
                  dataSource={data.topPages}
                  columns={topPagesColumns}
                  rowKey="path"
                  pagination={false}
                  size="small"
                  scroll={{ x: 300 }}
                />
              </Card>
            </Col>
            <Col xs={24} lg={10}>
              <Card title={<><LinkOutlined /> Top Referrers</>}>
                {data.topReferrers.length === 0 ? (
                  <Empty description="No referrer data" />
                ) : (
                  <Table
                    dataSource={data.topReferrers}
                    columns={referrerColumns}
                    rowKey="referrer"
                    pagination={false}
                    size="small"
                  />
                )}
              </Card>
            </Col>
          </Row>
        </>
      )}
    </div>
  );
}
