import { useState, useEffect, useCallback, useMemo } from 'react';
import { Row, Col, Card, Statistic, Table, Select, Button, App, Spin, Empty, Tag, Progress } from 'antd';
import {
  EyeOutlined,
  UserOutlined,
  CalendarOutlined,
  ReloadOutlined,
  BarChartOutlined,
} 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';

/* ------------------------------------------------------------------ */
/*  Types                                                              */
/* ------------------------------------------------------------------ */

interface ModuleBreakdown {
  module: string;
  views: number;
}

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

interface OverviewData {
  totalViews: number;
  uniqueSessions: number;
  avgViewsPerDay: number;
  moduleBreakdown: ModuleBreakdown[];
  viewsByDay: DayViews[];
}

interface ContentItem {
  title: string;
  module: string;
  views: number;
}

/* ------------------------------------------------------------------ */
/*  Constants                                                          */
/* ------------------------------------------------------------------ */

const MODULE_COLORS: Record<string, string> = {
  docs: '#1890ff',
  video: '#722ed1',
  photo: '#52c41a',
};

const MODULE_LABELS: Record<string, string> = {
  docs: 'Docs',
  video: 'Video',
  photo: 'Photo',
};

/* ------------------------------------------------------------------ */
/*  Helpers                                                            */
/* ------------------------------------------------------------------ */

/** Pivot day-level rows into { date, docs, video, photo } for recharts */
function pivotByDay(rows: DayViews[]): Record<string, number | string>[] {
  const map = new Map<string, Record<string, number | string>>();
  for (const r of rows) {
    if (!map.has(r.date)) map.set(r.date, { date: r.date });
    const entry = map.get(r.date)!;
    entry[r.module] = (typeof entry[r.module] === 'number' ? (entry[r.module] as number) : 0) + r.views;
  }
  return Array.from(map.values()).sort((a, b) =>
    String(a.date).localeCompare(String(b.date)),
  );
}

/* ------------------------------------------------------------------ */
/*  Table columns                                                      */
/* ------------------------------------------------------------------ */

const contentColumns = [
  {
    title: 'Title',
    dataIndex: 'title',
    key: 'title',
    ellipsis: true,
    render: (title: string) => (
      <span style={{ fontWeight: 500 }}>{title}</span>
    ),
  },
  {
    title: 'Module',
    dataIndex: 'module',
    key: 'module',
    width: 100,
    render: (mod: string) => (
      <Tag color={MODULE_COLORS[mod] ?? 'default'}>
        {MODULE_LABELS[mod] ?? mod}
      </Tag>
    ),
  },
  {
    title: 'Views',
    dataIndex: 'views',
    key: 'views',
    width: 90,
    sorter: (a: ContentItem, b: ContentItem) => a.views - b.views,
    defaultSortOrder: 'descend' as const,
  },
];

/* ------------------------------------------------------------------ */
/*  Component                                                          */
/* ------------------------------------------------------------------ */

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

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

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const [overviewRes, contentRes] = await Promise.all([
        api.get('/analytics/overview', { params: { days } }),
        api.get('/analytics/content', { params: { days, module: 'all' } }),
      ]);
      setData(overviewRes.data);
      setContent(Array.isArray(contentRes.data) ? contentRes.data : contentRes.data.items ?? []);
    } catch {
      message.error('Failed to load analytics data');
    } finally {
      setLoading(false);
    }
  }, [days, message]);

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

  const chartData = useMemo(() => (data ? pivotByDay(data.viewsByDay) : []), [data]);

  const totalModuleViews = useMemo(
    () => (data ? data.moduleBreakdown.reduce((sum, m) => sum + m.views, 0) : 0),
    [data],
  );

  return (
    <div>
      {/* Header row */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
        <BarChartOutlined style={{ fontSize: 18 }} />
        <div style={{ flex: 1 }} />
        <Select
          value={days}
          onChange={setDays}
          style={{ width: 140 }}
          options={[
            { label: 'Last 7 days', value: 7 },
            { label: 'Last 30 days', value: 30 },
            { label: 'Last 90 days', value: 90 },
            { label: 'Last 365 days', value: 365 },
          ]}
        />
        <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" />
      ) : (
        <>
          {/* Stat cards */}
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={24} sm={12} md={8}>
              <Card>
                <Statistic
                  title="Total Views"
                  value={data.totalViews}
                  prefix={<EyeOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <Card>
                <Statistic
                  title="Unique Sessions"
                  value={data.uniqueSessions}
                  prefix={<UserOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <Card>
                <Statistic
                  title="Avg Views / Day"
                  value={data.avgViewsPerDay}
                  precision={1}
                  prefix={<CalendarOutlined />}
                />
              </Card>
            </Col>
          </Row>

          {/* Views over time chart */}
          <Card title="Views Over Time" style={{ marginBottom: 24 }}>
            {chartData.length === 0 ? (
              <Empty description="No data for this period" />
            ) : (
              <div style={{ width: '100%', height: 300 }}>
                <ResponsiveContainer>
                  <AreaChart data={chartData} 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="docs"
                      name="Docs"
                      stroke={MODULE_COLORS.docs}
                      fill={MODULE_COLORS.docs}
                      fillOpacity={0.3}
                      stackId="1"
                    />
                    <Area
                      type="monotone"
                      dataKey="video"
                      name="Video"
                      stroke={MODULE_COLORS.video}
                      fill={MODULE_COLORS.video}
                      fillOpacity={0.3}
                      stackId="1"
                    />
                    <Area
                      type="monotone"
                      dataKey="photo"
                      name="Photo"
                      stroke={MODULE_COLORS.photo}
                      fill={MODULE_COLORS.photo}
                      fillOpacity={0.3}
                      stackId="1"
                    />
                  </AreaChart>
                </ResponsiveContainer>
              </div>
            )}
          </Card>

          {/* Module breakdown */}
          <Card title="Module Breakdown" style={{ marginBottom: 24 }}>
            <Row gutter={[16, 16]}>
              {data.moduleBreakdown.map((m) => {
                const pct = totalModuleViews > 0
                  ? Math.round((m.views / totalModuleViews) * 100)
                  : 0;
                return (
                  <Col xs={24} sm={8} key={m.module}>
                    <div style={{ textAlign: 'center' }}>
                      <Tag color={MODULE_COLORS[m.module] ?? 'default'} style={{ marginBottom: 8, fontSize: 13 }}>
                        {MODULE_LABELS[m.module] ?? m.module}
                      </Tag>
                      <Progress
                        type="circle"
                        percent={pct}
                        size={80}
                        strokeColor={MODULE_COLORS[m.module]}
                        format={() => m.views.toLocaleString()}
                      />
                      <div style={{ marginTop: 4, fontSize: 12, opacity: 0.65 }}>
                        {pct}% of total
                      </div>
                    </div>
                  </Col>
                );
              })}
              {data.moduleBreakdown.length === 0 && (
                <Col span={24}>
                  <Empty description="No module data" />
                </Col>
              )}
            </Row>
          </Card>

          {/* Top content table */}
          <Card title="Top Content">
            <Table
              dataSource={content}
              columns={contentColumns}
              rowKey={(r, i) => `${r.module}-${r.title}-${i}`}
              pagination={{ pageSize: 10, showSizeChanger: false }}
              size="small"
              scroll={{ x: 400 }}
            />
          </Card>
        </>
      )}
    </div>
  );
}
