import { useState, useEffect, useCallback } from 'react';
import { Row, Col, Card, Statistic, Table, Select, Button, Spin, Empty, Tag, App, Grid } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  TeamOutlined,
  ArrowLeftOutlined,
  PlayCircleOutlined,
  ClockCircleOutlined,
  PictureOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import { useOutletContext, useParams, useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import type { AppOutletContext } from '@/types/api';

/* ---------- Shared 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 | null): string {
  if (!dateStr) return 'Never';
  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 UserRow {
  userId: string;
  name: string | null;
  email: string;
  videoViews: number;
  photoViews: number;
  totalWatchTime: number;
  lastActive: string | null;
}

interface UserDetailSummary {
  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 UserDetailData {
  summary: UserDetailSummary;
  recentVideoViews: RecentVideoView[];
  recentPhotoViews: RecentPhotoView[];
}

interface UserListData {
  users: UserRow[];
  pagination: { page: number; limit: number; total: number; totalPages: number };
}

/* ---------- List mode ---------- */

function UserList() {
  const { message } = App.useApp();
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

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

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

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

  const columns: ColumnsType<UserRow> = [
    {
      title: 'Name',
      key: 'name',
      ellipsis: true,
      render: (_: unknown, record: UserRow) => record.name || record.email,
    },
    {
      title: 'Video Views',
      dataIndex: 'videoViews',
      key: 'videoViews',
      width: 110,
      sorter: (a: UserRow, b: UserRow) => a.videoViews - b.videoViews,
    },
    {
      title: 'Photo Views',
      dataIndex: 'photoViews',
      key: 'photoViews',
      width: 110,
      sorter: (a: UserRow, b: UserRow) => a.photoViews - b.photoViews,
    },
    {
      title: 'Watch Time',
      dataIndex: 'totalWatchTime',
      key: 'totalWatchTime',
      width: 110,
      render: (val: number) => formatWatchTime(val),
      sorter: (a: UserRow, b: UserRow) => a.totalWatchTime - b.totalWatchTime,
    },
    {
      title: 'Last Active',
      dataIndex: 'lastActive',
      key: 'lastActive',
      width: 110,
      render: (val: string | null) => formatRelativeTime(val),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
        <div style={{ flex: 1 }} />
        <Select
          value={days}
          onChange={(val) => { setDays(val); setPage(1); }}
          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>

      {loading && !data ? (
        <div style={{ textAlign: 'center', padding: 80 }}>
          <Spin size="large" />
        </div>
      ) : !data || data.users.length === 0 ? (
        <Empty description="No user analytics data available" />
      ) : (
        <Card title={<><TeamOutlined style={{ marginRight: 8 }} />User Engagement</>}>
          <Table
            dataSource={data.users}
            columns={columns}
            rowKey="userId"
            size="small"
            scroll={isMobile ? { x: 600 } : undefined}
            loading={loading}
            onRow={(record) => ({
              style: { cursor: 'pointer' },
              onClick: () => navigate(`/app/analytics/users/${record.userId}`),
            })}
            pagination={{
              current: page,
              total: data.pagination.total,
              pageSize: 20,
              showSizeChanger: false,
              onChange: setPage,
            }}
          />
        </Card>
      )}
    </div>
  );
}

/* ---------- Detail mode ---------- */

function UserDetail({ userId }: { userId: string }) {
  const { message } = App.useApp();
  const navigate = useNavigate();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

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

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get(`/analytics/users/${userId}`, {
        params: { days },
      });
      setData(res.data);
    } catch {
      message.error('Failed to load user detail');
    } finally {
      setLoading(false);
    }
  }, [userId, 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: 110,
      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: 'Viewed',
      dataIndex: 'viewedAt',
      key: 'viewedAt',
      width: 110,
      render: (val: string) => formatRelativeTime(val),
    },
  ];

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

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate('/app/analytics/users')}
        >
          Back to Users
        </Button>
        <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>

      {loading && !data ? (
        <div style={{ textAlign: 'center', padding: 80 }}>
          <Spin size="large" />
        </div>
      ) : !data ? (
        <Empty description="No data available for this user" />
      ) : (
        <>
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={24} sm={12} md={8}>
              <Card>
                <Statistic
                  title="Video Views"
                  value={data.summary.videoViews}
                  prefix={<PlayCircleOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <Card>
                <Statistic
                  title="Watch Time"
                  value={formatWatchTime(data.summary.totalWatchTime)}
                  prefix={<ClockCircleOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <Card>
                <Statistic
                  title="Photo Views"
                  value={data.summary.photoViews}
                  prefix={<PictureOutlined />}
                />
              </Card>
            </Col>
          </Row>

          <Row gutter={[16, 16]}>
            <Col xs={24} lg={14}>
              <Card title="Recent Video Views" style={{ marginBottom: 16 }}>
                {data.recentVideoViews.length === 0 ? (
                  <Empty description="No video views" />
                ) : (
                  <Table
                    dataSource={data.recentVideoViews}
                    columns={videoColumns}
                    rowKey="videoId"
                    size="small"
                    scroll={isMobile ? { x: 500 } : undefined}
                    pagination={{ pageSize: 10, showSizeChanger: false }}
                  />
                )}
              </Card>
            </Col>
            <Col xs={24} lg={10}>
              <Card title="Recent Photo Views" style={{ marginBottom: 16 }}>
                {data.recentPhotoViews.length === 0 ? (
                  <Empty description="No photo views" />
                ) : (
                  <Table
                    dataSource={data.recentPhotoViews}
                    columns={photoColumns}
                    rowKey="photoId"
                    size="small"
                    scroll={isMobile ? { x: 300 } : undefined}
                    pagination={{ pageSize: 10, showSizeChanger: false }}
                  />
                )}
              </Card>
            </Col>
          </Row>
        </>
      )}
    </div>
  );
}

/* ---------- Main export ---------- */

export default function UserAnalyticsPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const { userId } = useParams<{ userId: string }>();

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

  if (userId) {
    return <UserDetail userId={userId} />;
  }

  return <UserList />;
}
