import { useEffect, useState } from 'react';
import { Typography, Spin, Row, Col, Collapse, Empty, App } from 'antd';
import { api } from '@/lib/api';
import ChallengeCard from '@/components/social/ChallengeCard';

interface ChallengeListItem {
  id: string;
  title: string;
  metric: string;
  status: string;
  startsAt: string;
  endsAt: string;
  _count?: { teams: number };
}

interface MyTeamMap {
  [challengeId: string]: { id: string; name: string } | null;
}

export default function ChallengesPage() {
  const { message } = App.useApp();
  const [challenges, setChallenges] = useState<ChallengeListItem[]>([]);
  const [myTeams, setMyTeams] = useState<MyTeamMap>({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadChallenges();
  }, []);

  const loadChallenges = async () => {
    setLoading(true);
    try {
      const res = await api.get('/social/challenges', { params: { limit: 100 } });
      const all: ChallengeListItem[] = res.data.challenges;
      setChallenges(all);

      // Fetch my team for UPCOMING/ACTIVE challenges
      const relevant = all.filter((c) => c.status === 'UPCOMING' || c.status === 'ACTIVE');
      const teamMap: MyTeamMap = {};
      await Promise.all(
        relevant.map(async (c) => {
          try {
            const r = await api.get(`/social/challenges/${c.id}/my-team`);
            teamMap[c.id] = r.data.team;
          } catch {
            teamMap[c.id] = null;
          }
        }),
      );
      setMyTeams(teamMap);
    } catch {
      message.error('Failed to load challenges');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <div style={{ textAlign: 'center', padding: 48 }}><Spin size="large" /></div>;
  }

  const active = challenges.filter((c) => c.status === 'ACTIVE');
  const upcoming = challenges.filter((c) => c.status === 'UPCOMING');
  const past = challenges.filter((c) => c.status === 'COMPLETED');

  return (
    <div>
      <Typography.Title level={3} style={{ marginBottom: 16 }}>
        Team Challenges
      </Typography.Title>

      {active.length > 0 && (
        <div style={{ marginBottom: 24 }}>
          <Typography.Title level={5} style={{ marginBottom: 8 }}>Active Challenges</Typography.Title>
          <Row gutter={[12, 12]}>
            {active.map((c) => (
              <Col xs={24} sm={12} lg={8} key={c.id}>
                <ChallengeCard challenge={c} myTeam={myTeams[c.id]} />
              </Col>
            ))}
          </Row>
        </div>
      )}

      {upcoming.length > 0 && (
        <div style={{ marginBottom: 24 }}>
          <Typography.Title level={5} style={{ marginBottom: 8 }}>Upcoming</Typography.Title>
          <Row gutter={[12, 12]}>
            {upcoming.map((c) => (
              <Col xs={24} sm={12} lg={8} key={c.id}>
                <ChallengeCard challenge={c} myTeam={myTeams[c.id]} />
              </Col>
            ))}
          </Row>
        </div>
      )}

      {past.length > 0 && (
        <Collapse
          ghost
          items={[
            {
              key: 'past',
              label: <Typography.Text type="secondary">Past Challenges ({past.length})</Typography.Text>,
              children: (
                <Row gutter={[12, 12]}>
                  {past.map((c) => (
                    <Col xs={24} sm={12} lg={8} key={c.id}>
                      <ChallengeCard challenge={c} />
                    </Col>
                  ))}
                </Row>
              ),
            },
          ]}
        />
      )}

      {challenges.length === 0 && (
        <Empty description="No challenges yet" />
      )}
    </div>
  );
}
