import { Modal, Tabs, Statistic, Row, Col, Empty, Card, Table, Alert, Button, Skeleton, Grid } from 'antd';
import {
  EyeOutlined,
  UserOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  BarChartOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { useEffect, useState } from 'react';
import { mediaApi } from '@/lib/media-api';
import type { VideoAnalytics } from '@/types/media';
import AnalyticsChart from './AnalyticsChart';
import ViewersTable from './ViewersTable';
import { getErrorMessage } from '@/utils/getErrorMessage';

interface VideoAnalyticsModalProps {
  videoId: number | null;
  videoTitle: string;
  open: boolean;
  onClose: () => void;
}

export default function VideoAnalyticsModal({
  videoId,
  videoTitle,
  open,
  onClose,
}: VideoAnalyticsModalProps) {
  const [loading, setLoading] = useState(false);
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const [error, setError] = useState<string | null>(null);
  const [analytics, setAnalytics] = useState<VideoAnalytics | null>(null);

  useEffect(() => {
    if (open && videoId) {
      fetchAnalytics();
    }
  }, [open, videoId]);

  const fetchAnalytics = async () => {
    if (!videoId) return;

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

  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 tabItems = [
    {
      key: 'overview',
      label: 'Overview',
      children: analytics ? (
        <div>
          {/* Stats Cards */}
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Card>
                <Statistic
                  title="Total Views"
                  value={analytics.overview.totalViews}
                  prefix={<EyeOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="Unique Viewers"
                  value={analytics.overview.uniqueViewers}
                  prefix={<UserOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="Avg Watch Time"
                  value={formatWatchTime(Math.round(analytics.overview.averageWatchTime))}
                  prefix={<ClockCircleOutlined />}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card>
                <Statistic
                  title="Completion Rate"
                  value={analytics.overview.completionRate}
                  precision={1}
                  suffix="%"
                  prefix={<CheckCircleOutlined />}
                />
              </Card>
            </Col>
          </Row>

          {/* Total Watch Time */}
          <Card style={{ marginBottom: 24 }}>
            <Statistic
              title="Total Watch Time"
              value={formatWatchTime(analytics.overview.totalWatchTime)}
              prefix={<ClockCircleOutlined />}
            />
            <p style={{ marginTop: 8, color: '#666', fontSize: 12 }}>
              {analytics.overview.totalWatchTime} seconds total
            </p>
          </Card>

          {/* Top Referrers */}
          <Card title="Top Referrers">
            {analytics.topReferrers.length > 0 ? (
              <Table
                dataSource={analytics.topReferrers}
                columns={[
                  {
                    title: 'Source',
                    dataIndex: 'referer',
                    key: 'referer',
                  },
                  {
                    title: 'Views',
                    dataIndex: 'count',
                    key: 'count',
                    sorter: (a, b) => a.count - b.count,
                    defaultSortOrder: 'descend' as const,
                  },
                ]}
                rowKey="referer"
                pagination={false}
                size="small"
              />
            ) : (
              <Empty description="No referrer data" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </Card>
        </div>
      ) : (
        <Empty description="No data available" />
      ),
    },
    {
      key: 'charts',
      label: 'Charts',
      children: analytics ? (
        <div>
          {/* Views Over Time */}
          <Card title="Views Over Time (Last 30 Days)" style={{ marginBottom: 24 }}>
            {analytics.viewsOverTime.length > 0 ? (
              <AnalyticsChart
                type="area"
                data={analytics.viewsOverTime}
                dataKey="count"
                xKey="date"
                color="#1890ff"
                height={300}
              />
            ) : (
              <Empty description="No view history" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </Card>

          {/* Top Referrers Pie Chart */}
          <Card title="Traffic Sources Distribution">
            {analytics.topReferrers.length > 0 ? (
              <AnalyticsChart
                type="pie"
                data={analytics.topReferrers.map((item) => ({
                  name: item.referer,
                  value: item.count,
                }))}
                dataKey="value"
                height={400}
              />
            ) : (
              <Empty description="No referrer data" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </Card>
        </div>
      ) : (
        <Empty description="No data available" />
      ),
    },
    {
      key: 'viewers',
      label: `Viewers (${analytics?.registeredViewers.length || 0})`,
      children: analytics ? (
        <div>
          {analytics.registeredViewers.length > 0 ? (
            <ViewersTable viewers={analytics.registeredViewers} />
          ) : (
            <Empty description="No registered viewers yet" />
          )}
        </div>
      ) : (
        <Empty description="No data available" />
      ),
    },
  ];

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <BarChartOutlined />
          <span>Detailed Analytics: {videoTitle}</span>
        </div>
      }
      open={open}
      onCancel={onClose}
      footer={null}
      width={isMobile ? '95vw' : 1000}
      style={{ top: 20 }}
      styles={{
        body: { maxHeight: 'calc(100vh - 200px)', overflowY: 'auto' }
      }}
      aria-label="Video analytics modal"
    >
      {error ? (
        <div style={{ padding: 24 }}>
          <Alert
            type="error"
            message="Failed to Load Analytics"
            description={error}
            showIcon
            action={
              <Button
                size="small"
                type="primary"
                onClick={fetchAnalytics}
                icon={<ReloadOutlined />}
                aria-label="Retry loading analytics"
              >
                Retry
              </Button>
            }
          />
        </div>
      ) : loading ? (
        <div style={{ padding: 24 }}>
          <Row gutter={16} style={{ marginBottom: 24 }}>
            {[1, 2, 3, 4].map((i) => (
              <Col span={6} key={i}>
                <Skeleton.Button active block style={{ height: 100 }} />
              </Col>
            ))}
          </Row>
          <Skeleton active paragraph={{ rows: 6 }} />
        </div>
      ) : (
        <Tabs items={tabItems} />
      )}
    </Modal>
  );
}
