import { useState, useEffect, useCallback } from 'react';
import { Row, Col, Card, Table, Select, Spin, Empty, Tag, Segmented, App } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { FileTextOutlined } from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/types/api';

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

interface ContentAnalyticsData {
  content: ContentItem[];
}

const MODULE_TAG_COLORS: Record<string, string> = {
  docs: 'blue',
  video: 'purple',
  photo: 'green',
};

const MODULE_OPTIONS = ['All', 'Docs', 'Video', 'Photo'];

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

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

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

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

  const columns: ColumnsType<ContentItem> = [
    {
      title: '#',
      key: 'rank',
      width: 50,
      render: (_: unknown, __: ContentItem, index: number) => index + 1,
    },
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
    },
    {
      title: 'Module',
      dataIndex: 'module',
      key: 'module',
      width: 100,
      render: (mod: string) => (
        <Tag color={MODULE_TAG_COLORS[mod] ?? 'default'}>
          {mod.charAt(0).toUpperCase() + mod.slice(1)}
        </Tag>
      ),
    },
    {
      title: 'Views',
      dataIndex: 'views',
      key: 'views',
      width: 100,
      sorter: (a: ContentItem, b: ContentItem) => a.views - b.views,
      defaultSortOrder: 'descend',
    },
  ];

  return (
    <div>
      <Row gutter={[16, 16]} align="middle" style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12}>
          <Segmented
            value={moduleFilter}
            onChange={(val) => setModuleFilter(val as string)}
            options={MODULE_OPTIONS}
          />
        </Col>
        <Col xs={24} sm={12} style={{ textAlign: 'right' }}>
          <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 },
            ]}
          />
        </Col>
      </Row>

      {loading && !data ? (
        <div style={{ textAlign: 'center', padding: 80 }}>
          <Spin size="large" />
        </div>
      ) : !data || data.content.length === 0 ? (
        <Empty description="No content analytics data available" />
      ) : (
        <Card title={<><FileTextOutlined style={{ marginRight: 8 }} />Content Performance</>}>
          <Table
            dataSource={data.content}
            columns={columns}
            rowKey="id"
            size="small"
            scroll={{ x: 400 }}
            pagination={{ pageSize: 20, showSizeChanger: false }}
          />
        </Card>
      )}
    </div>
  );
}
