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

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

export default function QuickAnalyticsModal({
  videoId,
  videoTitle,
  open,
  onClose,
}: QuickAnalyticsModalProps) {
  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 () => {
    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);
    const secs = seconds % 60;

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

  return (
    <Modal
      title={`Analytics: ${videoTitle}`}
      open={open}
      onCancel={onClose}
      footer={null}
      width={isMobile ? '95vw' : 800}
      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 />}
              >
                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: 80 }} />
              </Col>
            ))}
          </Row>
          <Skeleton active paragraph={{ rows: 4 }} />
        </div>
      ) : analytics ? (
        <div>
          {/* Overview stats */}
          <Row gutter={16} style={{ marginBottom: 24 }}>
            <Col span={6}>
              <Statistic
                title="Total Views"
                value={analytics.overview.totalViews}
                prefix={<EyeOutlined />}
              />
            </Col>
            <Col span={6}>
              <Statistic
                title="Unique Viewers"
                value={analytics.overview.uniqueViewers}
                prefix={<UserOutlined />}
              />
            </Col>
            <Col span={6}>
              <Statistic
                title="Avg Watch Time"
                value={formatWatchTime(Math.round(analytics.overview.averageWatchTime))}
                prefix={<ClockCircleOutlined />}
              />
            </Col>
            <Col span={6}>
              <Statistic
                title="Completion Rate"
                value={analytics.overview.completionRate}
                precision={1}
                suffix="%"
                prefix={<CheckCircleOutlined />}
              />
            </Col>
          </Row>

          {/* Top Referrers */}
          <div style={{ marginBottom: 24 }}>
            <h4>Top Referrers</h4>
            {analytics.topReferrers.length > 0 ? (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {analytics.topReferrers.slice(0, 5).map((item, index) => (
                  <Tag key={index} color="blue">
                    {item.referer} ({item.count})
                  </Tag>
                ))}
              </div>
            ) : (
              <Empty description="No referrer data" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </div>

          {/* Registered Viewers */}
          <div>
            <h4>Recent Registered Viewers ({analytics.registeredViewers.length})</h4>
            {analytics.registeredViewers.length > 0 ? (
              <div style={{ maxHeight: 200, overflowY: 'auto' }}>
                <table style={{ width: '100%', fontSize: 12 }}>
                  <thead>
                    <tr style={{ background: '#f5f5f5' }}>
                      <th style={{ padding: 8, textAlign: 'left' }}>User</th>
                      <th style={{ padding: 8, textAlign: 'left' }}>Email</th>
                      <th style={{ padding: 8, textAlign: 'right' }}>Watch Time</th>
                      <th style={{ padding: 8, textAlign: 'center' }}>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {analytics.registeredViewers.slice(0, 10).map((viewer) => (
                      <tr key={viewer.userId} style={{ borderBottom: '1px solid #f0f0f0' }}>
                        <td style={{ padding: 8 }}>{viewer.userName || 'N/A'}</td>
                        <td style={{ padding: 8, fontSize: 11 }}>{viewer.userEmail}</td>
                        <td style={{ padding: 8, textAlign: 'right' }}>
                          {formatWatchTime(viewer.watchTime)}
                        </td>
                        <td style={{ padding: 8, textAlign: 'center' }}>
                          {viewer.completed ? (
                            <Tag color="success">Completed</Tag>
                          ) : (
                            <Tag color="default">Partial</Tag>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <Empty description="No registered viewers yet" image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
          </div>

          {/* Total watch time summary */}
          <div style={{ marginTop: 16, padding: 12, background: '#f5f5f5', borderRadius: 4 }}>
            <strong>Total Watch Time:</strong> {formatWatchTime(analytics.overview.totalWatchTime)}
          </div>
        </div>
      ) : (
        <Empty description="No analytics data available" />
      )}
    </Modal>
  );
}
