import { useEffect, useState } from 'react';
import { Typography, Skeleton, Empty, Pagination, Button, Space, Card, List, Tag } from 'antd';
import { TeamOutlined, CompassOutlined, TrophyOutlined, FlagOutlined, ThunderboltOutlined, GiftOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import FeedCard from '@/components/social/FeedCard';
import FriendSuggestions from '@/components/social/FriendSuggestions';
import UserAvatar from '@/components/social/UserAvatar';
import type { PaginationMeta } from '@/types/api';
import type { LeaderboardEntry } from '@/types/social';

interface FeedItem {
  id: string;
  type: string;
  userId: string;
  userName: string | null;
  userEmail: string;
  title: string;
  description: string;
  metadata: Record<string, unknown>;
  timestamp: string;
}

export default function SocialFeedPage() {
  const navigate = useNavigate();
  const [items, setItems] = useState<FeedItem[]>([]);
  const [pagination, setPagination] = useState<PaginationMeta | null>(null);
  const [topVolunteers, setTopVolunteers] = useState<LeaderboardEntry[]>([]);
  const [activeChallenge, setActiveChallenge] = useState<{ id: string; title: string; teamName: string; score: number } | null>(null);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);

  useEffect(() => {
    loadFeed(page);
    loadTopVolunteers();
    loadActiveChallenge();
  }, [page]);

  const loadFeed = async (p: number) => {
    setLoading(true);
    try {
      const { data } = await api.get('/social/feed', { params: { page: p, limit: 20 } });
      setItems(data.items);
      setPagination(data.pagination);
    } catch {} finally {
      setLoading(false);
    }
  };

  const loadTopVolunteers = async () => {
    try {
      const { data } = await api.get('/social/achievements/leaderboard', { params: { type: 'canvass', limit: 3 } });
      setTopVolunteers(data.leaderboard);
    } catch {}
  };

  const loadActiveChallenge = async () => {
    try {
      const { data } = await api.get('/social/challenges', { params: { status: 'ACTIVE' } });
      const challenges = data.challenges || [];
      for (const c of challenges) {
        try {
          const { data: teamData } = await api.get(`/social/challenges/${c.id}/my-team`);
          if (teamData.team) {
            setActiveChallenge({ id: c.id, title: c.title, teamName: teamData.team.name, score: teamData.team.score });
            break;
          }
        } catch {}
      }
    } catch {}
  };

  return (
    <div style={{ padding: '12px 0' }}>
      <Space style={{ width: '100%', justifyContent: 'space-between', marginBottom: 12 }}>
        <Typography.Title level={4} style={{ margin: 0 }}>Activity Feed</Typography.Title>
        <Space>
          <Button size="small" icon={<CompassOutlined />} onClick={() => navigate('/volunteer/discover')}>
            Discover
          </Button>
          <Button size="small" icon={<TeamOutlined />} onClick={() => navigate('/volunteer/friends')}>
            Friends
          </Button>
          <Button size="small" icon={<GiftOutlined />} onClick={() => navigate('/volunteer/referrals')}>
            Referrals
          </Button>
        </Space>
      </Space>

      {activeChallenge && (
        <Card
          size="small"
          style={{
            marginBottom: 12,
            borderLeft: '3px solid #52c41a',
            cursor: 'pointer',
          }}
          onClick={() => navigate(`/volunteer/challenges/${activeChallenge.id}`)}
        >
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <ThunderboltOutlined style={{ color: '#52c41a', fontSize: 18 }} />
            <div style={{ flex: 1 }}>
              <Typography.Text strong style={{ fontSize: 13 }}>
                <FlagOutlined style={{ marginRight: 4 }} />
                Active Challenge: {activeChallenge.title}
              </Typography.Text>
              <Typography.Text type="secondary" style={{ display: 'block', fontSize: 12 }}>
                Team "{activeChallenge.teamName}" — {activeChallenge.score} pts
              </Typography.Text>
            </div>
            <Tag color="green">LIVE</Tag>
          </div>
        </Card>
      )}

      <FriendSuggestions limit={5} />

      {topVolunteers.length > 0 && (
        <Card
          size="small"
          title={<><TrophyOutlined /> Top Canvassers</>}
          extra={<Button type="link" size="small" onClick={() => navigate('/volunteer/achievements')}>All</Button>}
          style={{ marginBottom: 12 }}
        >
          <List
            size="small"
            dataSource={topVolunteers}
            renderItem={(entry) => (
              <List.Item extra={<Typography.Text strong>{entry.score} doors</Typography.Text>}>
                <List.Item.Meta
                  avatar={<UserAvatar userId={entry.userId} name={entry.name} email={entry.email} size={28} />}
                  title={<Typography.Text style={{ fontSize: 13 }}>#{entry.rank} {entry.name || entry.email}</Typography.Text>}
                />
              </List.Item>
            )}
          />
        </Card>
      )}

      {loading ? (
        <Skeleton active paragraph={{ rows: 6 }} />
      ) : items.length === 0 ? (
        <Empty
          description={
            <div style={{ textAlign: 'center' }}>
              <Typography.Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
                Your feed is empty
              </Typography.Text>
              <Typography.Text type="secondary" style={{ fontSize: 13 }}>
                Add friends to see their activity here
              </Typography.Text>
              <div style={{ marginTop: 12 }}>
                <Button type="primary" onClick={() => navigate('/volunteer/discover')}>
                  Find Friends
                </Button>
              </div>
            </div>
          }
        />
      ) : (
        <>
          {items.map((item) => (
            <FeedCard key={item.id} item={item} />
          ))}

          {pagination && pagination.totalPages > 1 && (
            <div style={{ textAlign: 'center', marginTop: 12 }}>
              <Pagination
                current={page}
                total={pagination.total}
                pageSize={20}
                onChange={setPage}
                size="small"
                showSizeChanger={false}
              />
            </div>
          )}
        </>
      )}
    </div>
  );
}
