import { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Table, Select, Empty, Alert, Button, Skeleton } from 'antd';
import {
  EyeOutlined,
  VideoCameraOutlined,
  ClockCircleOutlined,
  TrophyOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { useOutletContext } from 'react-router-dom';
import { mediaApi } from '@/lib/media-api';
import type { AnalyticsOverviewResponse, TopVideosResponse } from '@/types/media';
import type { AppOutletContext } from '@/types/api';
import { getErrorMessage } from '@/utils/getErrorMessage';

export default function AnalyticsDashboardPage() {
  const { setPageHeader } = useOutletContext<AppOutletContext>();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [overview, setOverview] = useState<AnalyticsOverviewResponse | null>(null);
  const [topVideos, setTopVideos] = useState<TopVideosResponse | null>(null);
  const [topMetric, setTopMetric] = useState<'views' | 'watchTime'>('views');

  useEffect(() => {
    setPageHeader({
      title: 'Video Analytics Dashboard',
      subtitle: 'Global analytics across all videos',
    });
  }, [setPageHeader]);

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

  useEffect(() => {
    fetchTopVideos();
  }, [topMetric]);

  const fetchOverview = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await mediaApi.get('/videos/analytics/overview');
      setOverview(response.data);
    } catch (error: unknown) {
      console.error('Failed to fetch analytics overview:', error);
      setError(getErrorMessage(error, 'Failed to load analytics. Please try again.'));
    } finally {
      setLoading(false);
    }
  };

  const fetchTopVideos = async () => {
    try {
      const response = await mediaApi.get('/videos/analytics/top', {
        params: { metric: topMetric, limit: 10 },
      });
      setTopVideos(response.data);
    } catch (error: unknown) {
      console.error('Failed to fetch top videos:', error);
    }
  };

  const formatWatchTime = (seconds: number) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);

    if (hours > 0) {
      return `${hours}h ${minutes}m`;
    }
    return `${minutes}m`;
  };

  const topVideosColumns = [
    {
      title: 'Rank',
      key: 'rank',
      render: (_: any, __: any, index: number) => (
        <span style={{ fontSize: 18, fontWeight: 'bold', color: index < 3 ? '#faad14' : '#999' }}>
          #{index + 1}
        </span>
      ),
      width: 80,
    },
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      render: (title: string | null, record: any) => title || `Video ${record.id}`,
    },
    {
      title: topMetric === 'views' ? 'Views' : 'Watch Time',
      dataIndex: 'value',
      key: 'value',
      render: (value: number) =>
        topMetric === 'views' ? value.toLocaleString() : formatWatchTime(value),
      sorter: (a: any, b: any) => a.value - b.value,
      defaultSortOrder: 'descend' as const,
    },
  ];

  return (
    <div>
      {error ? (
        <div style={{ padding: 24 }}>
          <Alert
            type="error"
            message="Failed to Load Analytics"
            description={error}
            showIcon
            action={
              <Button
                size="small"
                type="primary"
                onClick={fetchOverview}
                icon={<ReloadOutlined />}
                aria-label="Retry loading analytics"
              >
                Retry
              </Button>
            }
          />
        </div>
      ) : loading && !overview ? (
        <div style={{ padding: 24 }}>
          <Row gutter={16} style={{ marginBottom: 24 }}>
            {[1, 2, 3, 4].map((i) => (
              <Col xs={24} sm={12} md={6} key={i}>
                <Skeleton.Button active block style={{ height: 100 }} />
              </Col>
            ))}
          </Row>
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={24} sm={12}>
              <Skeleton.Button active block style={{ height: 100 }} />
            </Col>
            <Col xs={24} sm={12}>
              <Skeleton.Button active block style={{ height: 100 }} />
            </Col>
          </Row>
          <Skeleton active paragraph={{ rows: 8 }} />
        </div>
      ) : overview ? (
        <>
          {/* Overview Stats */}
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="Total Videos"
                  value={overview.totalVideos}
                  prefix={<VideoCameraOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="Total Views"
                  value={overview.totalViews}
                  prefix={<EyeOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="Total Watch Time"
                  value={formatWatchTime(overview.totalWatchTimeSeconds)}
                  prefix={<ClockCircleOutlined />}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12} md={6}>
              <Card>
                <Statistic
                  title="Avg Completion Rate"
                  value={overview.averageCompletionRate}
                  precision={1}
                  suffix="%"
                  prefix={<TrophyOutlined />}
                />
              </Card>
            </Col>
          </Row>

          {/* Additional Stats */}
          <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
            <Col xs={24} sm={12}>
              <Card>
                <Statistic
                  title="Average Views per Video"
                  value={overview.totalVideos > 0 ? Math.round(overview.totalViews / overview.totalVideos) : 0}
                />
              </Card>
            </Col>
            <Col xs={24} sm={12}>
              <Card>
                <Statistic
                  title="Average Watch Time per Video"
                  value={
                    overview.totalVideos > 0
                      ? formatWatchTime(Math.round(overview.totalWatchTimeSeconds / overview.totalVideos))
                      : '0m'
                  }
                />
              </Card>
            </Col>
          </Row>

          {/* Top Videos */}
          <Card
            title={
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span>Top Performing Videos</span>
                <Select
                  value={topMetric}
                  onChange={setTopMetric}
                  style={{ width: 150 }}
                  options={[
                    { value: 'views', label: 'By Views' },
                    { value: 'watchTime', label: 'By Watch Time' },
                  ]}
                  aria-label="Select metric for top videos"
                />
              </div>
            }
          >
            {topVideos && topVideos.videos.length > 0 ? (
              <Table
                dataSource={topVideos.videos}
                columns={topVideosColumns}
                scroll={{ x: 'max-content' }}
                rowKey="id"
                pagination={false}
                size="small"
              />
            ) : (
              <Empty description="No video data available" />
            )}
          </Card>
        </>
      ) : (
        <Empty description="No analytics data available" />
      )}
    </div>
  );
}
