import { useState, useEffect, useCallback } from 'react';
import { Row, Col, Card, Statistic, Table, Select, Spin, Empty, Tag, Typography, App, Grid } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  PlayCircleOutlined,
  ClockCircleOutlined,
  PictureOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';

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

function formatWatchTime(seconds: number): string {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = Math.floor(seconds % 60);
  if (h > 0) return `${h}h ${m}m`;
  return `${m}m ${s}s`;
}

function formatRelativeTime(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return 'Just now';
  if (mins < 60) return `${mins}m ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours}h ago`;
  const days = Math.floor(hours / 24);
  if (days < 30) return `${days}d ago`;
  const months = Math.floor(days / 30);
  return `${months}mo ago`;
}

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

interface MyAnalyticsSummary {
  videoViews: number;
  totalWatchTime: number;
  photoViews: number;
}

interface RecentVideoView {
  videoId: number;
  videoTitle: string;
  watchTime: number;
  completed: boolean;
  viewedAt: string;
}

interface RecentPhotoView {
  photoId: number;
  photoTitle: string;
  viewedAt: string;
}

interface MyAnalyticsData {
  summary: MyAnalyticsSummary;
  recentVideoViews: RecentVideoView[];
  recentPhotoViews: RecentPhotoView[];
}

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

export default function MyAnalyticsPage() {
  const { message } = App.useApp();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const [days, setDays] = useState(30);
  const [data, setData] = useState<MyAnalyticsData | null>(null);
  const [loading, setLoading] = useState(true);

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

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

  const videoColumns: ColumnsType<RecentVideoView> = [
    {
      title: 'Video',
      dataIndex: 'videoTitle',
      key: 'videoTitle',
      ellipsis: true,
    },
    {
      title: 'Watch Time',
      dataIndex: 'watchTime',
      key: 'watchTime',
      width: 100,
      render: (val: number) => formatWatchTime(val),
    },
    {
      title: 'Completed',
      dataIndex: 'completed',
      key: 'completed',
      width: 90,
      render: (val: boolean) =>
        val ? <Tag icon={<CheckCircleOutlined />} color="success">Yes</Tag> : <Tag>No</Tag>,
    },
    {
      title: 'When',
      dataIndex: 'viewedAt',
      key: 'viewedAt',
      width: 100,
      render: (val: string) => formatRelativeTime(val),
    },
  ];

  const photoColumns: ColumnsType<RecentPhotoView> = [
    {
      title: 'Photo',
      dataIndex: 'photoTitle',
      key: 'photoTitle',
      ellipsis: true,
    },
    {
      title: 'When',
      dataIndex: 'viewedAt',
      key: 'viewedAt',
      width: 100,
      render: (val: string) => formatRelativeTime(val),
    },
  ];

  if (loading && !data) {
    return <div style={{ textAlign: 'center', padding: 48 }}><Spin size="large" /></div>;
  }

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
        <Typography.Title level={3} style={{ margin: 0 }}>My Stats</Typography.Title>
        <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 },
          ]}
        />
      </div>

      {!data ? (
        <Empty description="No stats available yet" />
      ) : (
        <>
          <Row gutter={[12, 12]} style={{ marginBottom: 24 }}>
            <Col xs={24} sm={8}>
              <Card size="small">
                <Statistic
                  title="Videos Watched"
                  value={data.summary.videoViews}
                  prefix={<PlayCircleOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card size="small">
                <Statistic
                  title="Watch Time"
                  value={formatWatchTime(data.summary.totalWatchTime)}
                  prefix={<ClockCircleOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={8}>
              <Card size="small">
                <Statistic
                  title="Photos Viewed"
                  value={data.summary.photoViews}
                  prefix={<PictureOutlined />}
                />
              </Card>
            </Col>
          </Row>

          <Card title="Recent Videos" size="small" style={{ marginBottom: 16 }}>
            {data.recentVideoViews.length === 0 ? (
              <Empty description="No video views yet" />
            ) : (
              <Table
                dataSource={data.recentVideoViews}
                columns={videoColumns}
                rowKey="videoId"
                size="small"
                scroll={isMobile ? { x: 500 } : undefined}
                loading={loading}
                pagination={{ pageSize: 10, showSizeChanger: false }}
              />
            )}
          </Card>

          <Card title="Recent Photos" size="small">
            {data.recentPhotoViews.length === 0 ? (
              <Empty description="No photo views yet" />
            ) : (
              <Table
                dataSource={data.recentPhotoViews}
                columns={photoColumns}
                rowKey="photoId"
                size="small"
                scroll={isMobile ? { x: 300 } : undefined}
                loading={loading}
                pagination={{ pageSize: 10, showSizeChanger: false }}
              />
            )}
          </Card>
        </>
      )}
    </div>
  );
}
