import { useState, useEffect, useCallback } from 'react';
import {
  Typography, Row, Col, Spin, Empty, Tabs, Pagination, Grid, message, theme,
} from 'antd';
import {
  StarFilled, TrophyOutlined, EnvironmentOutlined, CalendarOutlined, MailOutlined,
} from '@ant-design/icons';
import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth.store';
import SpotlightCard from '@/components/social/SpotlightCard';
import PublicLeaderboard from '@/components/social/PublicLeaderboard';

const { Title, Text } = Typography;

interface FeaturedSpotlight {
  id: string;
  userId: string;
  headline: string | null;
  story: string | null;
  featuredMonth: string | null;
  user: { id: string; name: string | null };
}

export default function WallOfFamePage() {
  const { token: themeToken } = theme.useToken();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;
  const { user } = useAuthStore();
  const isLoggedIn = !!user;

  const [featured, setFeatured] = useState<FeaturedSpotlight[]>([]);
  const [wallOfFame, setWallOfFame] = useState<FeaturedSpotlight[]>([]);
  const [wallPage, setWallPage] = useState(1);
  const [wallTotal, setWallTotal] = useState(0);
  const [loadingFeatured, setLoadingFeatured] = useState(true);
  const [loadingWall, setLoadingWall] = useState(true);
  const [optedIn, setOptedIn] = useState(true);
  const [activeTab, setActiveTab] = useState('canvass');

  const fetchFeatured = useCallback(async () => {
    try {
      setLoadingFeatured(true);
      const { data } = await api.get('/social/spotlight/featured');
      setFeatured(data.spotlights || []);
    } catch {
      // Silently handle auth errors for unauthenticated users
    } finally {
      setLoadingFeatured(false);
    }
  }, []);

  const fetchWallOfFame = useCallback(async (page: number) => {
    try {
      setLoadingWall(true);
      const { data } = await api.get('/social/spotlight/wall-of-fame', {
        params: { page, limit: 12 },
      });
      setWallOfFame(data.spotlights || []);
      setWallTotal(data.pagination?.total || 0);
    } catch {
      // Silently handle
    } finally {
      setLoadingWall(false);
    }
  }, []);

  const fetchOptInStatus = useCallback(async () => {
    if (!isLoggedIn) return;
    try {
      const { data } = await api.get('/social/spotlight/opt-in-status');
      setOptedIn(data.showOnLeaderboard ?? true);
    } catch {
      // Ignore
    }
  }, [isLoggedIn]);

  useEffect(() => {
    fetchFeatured();
    fetchWallOfFame(1);
    fetchOptInStatus();
  }, [fetchFeatured, fetchWallOfFame, fetchOptInStatus]);

  const handleOptInChange = async (value: boolean) => {
    try {
      await api.post(value ? '/social/spotlight/opt-in' : '/social/spotlight/opt-out');
      setOptedIn(value);
      message.success(value ? 'You will appear on the leaderboard' : 'You have been removed from the leaderboard');
    } catch {
      message.error('Failed to update preference');
    }
  };

  const handleWallPageChange = (page: number) => {
    setWallPage(page);
    fetchWallOfFame(page);
  };

  const leaderboardTabs = [
    {
      key: 'canvass',
      label: (
        <span><EnvironmentOutlined style={{ marginRight: 4 }} />Canvass</span>
      ),
      children: (
        <PublicLeaderboard
          type="canvass"
          showOptIn={isLoggedIn}
          optedIn={optedIn}
          onOptInChange={handleOptInChange}
        />
      ),
    },
    {
      key: 'shifts',
      label: (
        <span><CalendarOutlined style={{ marginRight: 4 }} />Shifts</span>
      ),
      children: (
        <PublicLeaderboard
          type="shifts"
          showOptIn={isLoggedIn}
          optedIn={optedIn}
          onOptInChange={handleOptInChange}
        />
      ),
    },
    {
      key: 'campaigns',
      label: (
        <span><MailOutlined style={{ marginRight: 4 }} />Campaigns</span>
      ),
      children: (
        <PublicLeaderboard
          type="campaigns"
          showOptIn={isLoggedIn}
          optedIn={optedIn}
          onOptInChange={handleOptInChange}
        />
      ),
    },
  ];

  return (
    <div style={{ maxWidth: 1000, margin: '0 auto', padding: isMobile ? '16px' : '24px 16px' }}>
      {/* Featured Volunteers Section */}
      <div style={{ textAlign: 'center', marginBottom: 32 }}>
        <StarFilled style={{ fontSize: 32, color: '#d4a017', marginBottom: 8 }} />
        <Title level={2} style={{ margin: 0 }}>Volunteer Spotlight</Title>
        <Text type="secondary">Recognizing the outstanding volunteers making a difference</Text>
      </div>

      {loadingFeatured ? (
        <Spin style={{ display: 'block', margin: '24px auto' }} />
      ) : featured.length > 0 ? (
        <div style={{ marginBottom: 40 }}>
          <Title level={4} style={{ marginBottom: 16 }}>
            <StarFilled style={{ color: '#d4a017', marginRight: 8 }} />
            This Month's Featured Volunteers
          </Title>
          <Row gutter={[16, 16]}>
            {featured.map((s) => (
              <Col key={s.id} xs={24} md={12}>
                <SpotlightCard
                  spotlight={{
                    id: s.id,
                    userId: s.userId,
                    userName: s.user?.name,
                    headline: s.headline,
                    story: s.story,
                    featuredMonth: s.featuredMonth,
                  }}
                />
              </Col>
            ))}
          </Row>
        </div>
      ) : (
        <Empty
          description="No featured volunteers this month"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          style={{ marginBottom: 40 }}
        />
      )}

      {/* Leaderboard Section */}
      <div style={{
        background: themeToken.colorBgContainer,
        borderRadius: 12,
        padding: isMobile ? 16 : 24,
        marginBottom: 40,
      }}>
        <Title level={4} style={{ marginBottom: 16 }}>
          <TrophyOutlined style={{ color: '#d4a017', marginRight: 8 }} />
          Leaderboard
        </Title>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={leaderboardTabs}
        />
      </div>

      {/* Wall of Fame Section */}
      {wallTotal > 0 && (
        <div>
          <Title level={4} style={{ marginBottom: 16 }}>
            <StarFilled style={{ color: '#d4a017', marginRight: 8 }} />
            Wall of Fame
          </Title>
          {loadingWall ? (
            <Spin style={{ display: 'block', margin: '24px auto' }} />
          ) : (
            <>
              <Row gutter={[16, 16]}>
                {wallOfFame.map((s) => (
                  <Col key={s.id} xs={24} md={12}>
                    <SpotlightCard
                      spotlight={{
                        id: s.id,
                        userId: s.userId,
                        userName: s.user?.name,
                        headline: s.headline,
                        story: s.story,
                        featuredMonth: s.featuredMonth,
                      }}
                    />
                  </Col>
                ))}
              </Row>
              {wallTotal > 12 && (
                <div style={{ textAlign: 'center', marginTop: 24 }}>
                  <Pagination
                    current={wallPage}
                    total={wallTotal}
                    pageSize={12}
                    onChange={handleWallPageChange}
                    showSizeChanger={false}
                  />
                </div>
              )}
            </>
          )}
        </div>
      )}
    </div>
  );
}
