import { useState, useEffect, useCallback } from 'react';
import { Typography, Card, Row, Col, Spin, Button, Grid, theme, App } from 'antd';
import {
  ClockCircleOutlined,
  PlayCircleOutlined,
  MessageOutlined,
  HeartOutlined,
  TrophyOutlined,
  FireOutlined,
  ReloadOutlined,
  HistoryOutlined,
  MoonOutlined,
  SunOutlined,
  ThunderboltOutlined,
} from '@ant-design/icons';
import { mediaApi } from '@/lib/media-api';

const { Title, Text } = Typography;
const { useBreakpoint } = Grid;

interface UserStatsData {
  totalWatchTimeSeconds: number | null;
  totalVideosWatched: number | null;
  totalCommentsMade: number | null;
  totalUpvotesGiven: number | null;
  totalFinishes: number | null;
  currentDayStreak: number | null;
  longestDayStreak: number | null;
  longestSingleSession: number | null;
  nightOwlCount: number | null;
  earlyBirdCount: number | null;
}

interface DailyActivity {
  activityDate: string;
  watchTimeSeconds: number | null;
  videosWatched: number | null;
}

interface WatchHistoryItem {
  id: number;
  watchTimeSeconds: number;
  completed: boolean;
  createdAt: string;
  video: {
    id: number;
    title: string | null;
    filename: string;
    thumbnailPath: string | null;
    durationSeconds: number | null;
  };
}

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

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
}

export default function MyStatsPage() {
  const { token } = theme.useToken();
  const { message } = App.useApp();
  const screens = useBreakpoint();
  const isMobile = !screens.md;

  const [loading, setLoading] = useState(true);
  const [recalculating, setRecalculating] = useState(false);
  const [stats, setStats] = useState<UserStatsData | null>(null);
  const [dailyActivity, setDailyActivity] = useState<DailyActivity[]>([]);
  const [achievementCount, setAchievementCount] = useState(0);
  const [history, setHistory] = useState<WatchHistoryItem[]>([]);
  const [historyTotal, setHistoryTotal] = useState(0);
  const [historyLoading, setHistoryLoading] = useState(false);

  const fetchStats = useCallback(async () => {
    try {
      const { data } = await mediaApi.get('/media/me/stats');
      setStats(data.stats);
      setDailyActivity(data.dailyActivity || []);
      setAchievementCount(data.achievementCount || 0);
    } catch {
      // Stats may not exist yet
    }
  }, []);

  const fetchHistory = useCallback(async (offset = 0) => {
    try {
      setHistoryLoading(true);
      const { data } = await mediaApi.get('/media/me/watch-history', {
        params: { limit: '10', offset: String(offset) },
      });
      if (offset === 0) {
        setHistory(data.views);
      } else {
        setHistory((prev) => [...prev, ...data.views]);
      }
      setHistoryTotal(data.total);
    } catch {
      // Silent
    } finally {
      setHistoryLoading(false);
    }
  }, []);

  useEffect(() => {
    Promise.all([fetchStats(), fetchHistory()]).finally(() => setLoading(false));
  }, [fetchStats, fetchHistory]);

  const handleRecalculate = async () => {
    setRecalculating(true);
    try {
      const { data } = await mediaApi.post('/media/me/stats/recalculate');
      setStats(data.stats);
      message.success('Stats recalculated');
    } catch {
      message.error('Failed to recalculate stats');
    } finally {
      setRecalculating(false);
    }
  };

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', paddingTop: 100 }}>
        <Spin size="large" />
      </div>
    );
  }

  const s = stats || ({} as Partial<UserStatsData>);
  const maxDailyWatch = Math.max(
    ...dailyActivity.map((d) => d.watchTimeSeconds || 0),
    1
  );

  const statCards = [
    {
      icon: <ClockCircleOutlined />,
      label: 'Watch Time',
      value: formatDuration(s.totalWatchTimeSeconds || 0),
    },
    {
      icon: <PlayCircleOutlined />,
      label: 'Videos Watched',
      value: String(s.totalVideosWatched || 0),
    },
    {
      icon: <MessageOutlined />,
      label: 'Comments',
      value: String(s.totalCommentsMade || 0),
    },
    {
      icon: <HeartOutlined />,
      label: 'Reactions',
      value: String(s.totalUpvotesGiven || 0),
    },
    {
      icon: <TrophyOutlined />,
      label: 'Completed',
      value: String(s.totalFinishes || 0),
    },
    {
      icon: <FireOutlined />,
      label: 'Streak',
      value: `${s.currentDayStreak || 0}d / ${s.longestDayStreak || 0}d`,
    },
  ];

  return (
    <div style={{ maxWidth: 960, margin: '0 auto', padding: isMobile ? '16px 8px' : '24px 16px' }}>
      {/* Header */}
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 24,
          flexWrap: 'wrap',
          gap: 12,
        }}
      >
        <Title level={3} style={{ margin: 0, color: token.colorText }}>
          My Stats
        </Title>
        <Button
          icon={<ReloadOutlined />}
          onClick={handleRecalculate}
          loading={recalculating}
          size="small"
        >
          Recalculate
        </Button>
      </div>

      {/* Stat Cards */}
      <Row gutter={[12, 12]} style={{ marginBottom: 24 }}>
        {statCards.map((card) => (
          <Col xs={12} sm={8} key={card.label}>
            <Card
              size="small"
              style={{
                background: 'rgba(255,255,255,0.04)',
                border: '1px solid rgba(255,255,255,0.08)',
                borderRadius: 10,
                textAlign: 'center',
              }}
              styles={{ body: { padding: '16px 12px' } }}
            >
              <div style={{ fontSize: 24, color: token.colorPrimary, marginBottom: 4 }}>
                {card.icon}
              </div>
              <div
                style={{
                  fontSize: 22,
                  fontWeight: 700,
                  color: token.colorText,
                  lineHeight: 1.2,
                }}
              >
                {card.value}
              </div>
              <Text
                type="secondary"
                style={{ fontSize: 12, color: 'rgba(255,255,255,0.5)' }}
              >
                {card.label}
              </Text>
            </Card>
          </Col>
        ))}
      </Row>

      {/* Activity Chart (CSS bar chart) */}
      <Card
        size="small"
        title={
          <Text strong style={{ color: token.colorText }}>
            <HistoryOutlined style={{ marginRight: 8 }} />
            Last 30 Days Activity
          </Text>
        }
        style={{
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid rgba(255,255,255,0.08)',
          borderRadius: 10,
          marginBottom: 24,
        }}
        styles={{ body: { padding: '12px 16px' } }}
      >
        {dailyActivity.length === 0 ? (
          <Text type="secondary" style={{ color: 'rgba(255,255,255,0.4)' }}>
            No activity recorded yet. Start watching to see your chart!
          </Text>
        ) : (
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 2, height: 100 }}>
            {dailyActivity.map((day) => {
              const pct = ((day.watchTimeSeconds || 0) / maxDailyWatch) * 100;
              return (
                <div
                  key={day.activityDate}
                  title={`${day.activityDate}: ${formatDuration(day.watchTimeSeconds || 0)}`}
                  style={{
                    flex: 1,
                    minWidth: 4,
                    maxWidth: 20,
                    height: `${Math.max(pct, 4)}%`,
                    background: token.colorPrimary,
                    borderRadius: '3px 3px 0 0',
                    opacity: pct > 0 ? 0.5 + (pct / 200) : 0.15,
                    transition: 'height 0.3s ease',
                  }}
                />
              );
            })}
          </div>
        )}
      </Card>

      {/* Habits Section */}
      <Card
        size="small"
        title={
          <Text strong style={{ color: token.colorText }}>
            <ThunderboltOutlined style={{ marginRight: 8 }} />
            Habits
          </Text>
        }
        style={{
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid rgba(255,255,255,0.08)',
          borderRadius: 10,
          marginBottom: 24,
        }}
        styles={{ body: { padding: '16px' } }}
      >
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={8}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ display: 'flex', justifyContent: 'center', gap: 16, marginBottom: 8 }}>
                <div>
                  <MoonOutlined
                    style={{
                      fontSize: 20,
                      color:
                        (s.nightOwlCount || 0) >= (s.earlyBirdCount || 0)
                          ? token.colorPrimary
                          : 'rgba(255,255,255,0.3)',
                    }}
                  />
                  <div style={{ fontSize: 18, fontWeight: 700, color: token.colorText }}>
                    {s.nightOwlCount || 0}
                  </div>
                  <Text style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>Night Owl</Text>
                </div>
                <div>
                  <SunOutlined
                    style={{
                      fontSize: 20,
                      color:
                        (s.earlyBirdCount || 0) > (s.nightOwlCount || 0)
                          ? '#f59e0b'
                          : 'rgba(255,255,255,0.3)',
                    }}
                  />
                  <div style={{ fontSize: 18, fontWeight: 700, color: token.colorText }}>
                    {s.earlyBirdCount || 0}
                  </div>
                  <Text style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>Early Bird</Text>
                </div>
              </div>
            </div>
          </Col>
          <Col xs={24} sm={8}>
            <div style={{ textAlign: 'center' }}>
              <ClockCircleOutlined style={{ fontSize: 20, color: token.colorPrimary }} />
              <div style={{ fontSize: 18, fontWeight: 700, color: token.colorText }}>
                {formatDuration(s.longestSingleSession || 0)}
              </div>
              <Text style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>
                Longest Session
              </Text>
            </div>
          </Col>
          <Col xs={24} sm={8}>
            <div style={{ textAlign: 'center' }}>
              <TrophyOutlined style={{ fontSize: 20, color: '#f59e0b' }} />
              <div style={{ fontSize: 18, fontWeight: 700, color: token.colorText }}>
                {achievementCount}
              </div>
              <Text style={{ fontSize: 11, color: 'rgba(255,255,255,0.5)' }}>Achievements</Text>
            </div>
          </Col>
        </Row>
      </Card>

      {/* Watch History */}
      <Card
        size="small"
        title={
          <Text strong style={{ color: token.colorText }}>
            <PlayCircleOutlined style={{ marginRight: 8 }} />
            Watch History ({historyTotal})
          </Text>
        }
        style={{
          background: 'rgba(255,255,255,0.04)',
          border: '1px solid rgba(255,255,255,0.08)',
          borderRadius: 10,
        }}
        styles={{ body: { padding: 0 } }}
      >
        {history.length === 0 ? (
          <div style={{ padding: 24, textAlign: 'center' }}>
            <Text type="secondary" style={{ color: 'rgba(255,255,255,0.4)' }}>
              No watch history yet
            </Text>
          </div>
        ) : (
          <>
            {history.map((item) => (
              <div
                key={item.id}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 12,
                  padding: '12px 16px',
                  borderBottom: '1px solid rgba(255,255,255,0.06)',
                }}
              >
                {/* Thumbnail placeholder */}
                <div
                  style={{
                    width: 56,
                    height: 36,
                    borderRadius: 6,
                    background: 'rgba(255,255,255,0.08)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    flexShrink: 0,
                  }}
                >
                  <PlayCircleOutlined
                    style={{ fontSize: 16, color: 'rgba(255,255,255,0.3)' }}
                  />
                </div>
                {/* Info */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <Text
                    ellipsis
                    style={{
                      display: 'block',
                      fontSize: 13,
                      fontWeight: 500,
                      color: token.colorText,
                    }}
                  >
                    {item.video.title || item.video.filename}
                  </Text>
                  <Text style={{ fontSize: 11, color: 'rgba(255,255,255,0.4)' }}>
                    {formatDuration(item.watchTimeSeconds)}
                    {item.video.durationSeconds
                      ? ` / ${formatDuration(item.video.durationSeconds)}`
                      : ''}
                    {item.completed && (
                      <TrophyOutlined
                        style={{ marginLeft: 6, color: '#f59e0b', fontSize: 11 }}
                      />
                    )}
                  </Text>
                </div>
                {/* Date */}
                <Text
                  style={{
                    fontSize: 11,
                    color: 'rgba(255,255,255,0.35)',
                    flexShrink: 0,
                  }}
                >
                  {formatDate(item.createdAt)}
                </Text>
              </div>
            ))}
            {history.length < historyTotal && (
              <div style={{ padding: 12, textAlign: 'center' }}>
                <Button
                  type="link"
                  onClick={() => fetchHistory(history.length)}
                  loading={historyLoading}
                >
                  Load more
                </Button>
              </div>
            )}
          </>
        )}
      </Card>
    </div>
  );
}
