import { Card, Tag, Typography, Space, Badge } from 'antd';
import {
  HomeOutlined,
  MailOutlined,
  ScheduleOutlined,
  MessageOutlined,
  UserAddOutlined,
  ClockCircleOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';

export interface ChallengeMetricInfo {
  icon: React.ReactNode;
  label: string;
  color: string;
}

export const METRIC_MAP: Record<string, ChallengeMetricInfo> = {
  DOORS_KNOCKED: { icon: <HomeOutlined />, label: 'Doors Knocked', color: '#52c41a' },
  EMAILS_SENT: { icon: <MailOutlined />, label: 'Emails Sent', color: '#1890ff' },
  SHIFTS_ATTENDED: { icon: <ScheduleOutlined />, label: 'Shifts Attended', color: '#fa8c16' },
  RESPONSES_SUBMITTED: { icon: <MessageOutlined />, label: 'Responses', color: '#722ed1' },
  REFERRALS_MADE: { icon: <UserAddOutlined />, label: 'Referrals', color: '#eb2f96' },
};

export const STATUS_COLORS: Record<string, string> = {
  DRAFT: 'default',
  UPCOMING: 'blue',
  ACTIVE: 'green',
  COMPLETED: 'gold',
  CANCELLED: 'red',
};

interface ChallengeCardProps {
  challenge: {
    id: string;
    title: string;
    metric: string;
    status: string;
    startsAt: string;
    endsAt: string;
    _count?: { teams: number };
    teams?: unknown[];
  };
  myTeam?: { id: string; name: string } | null;
}

function CountdownTimer({ target, label }: { target: string; label: string }) {
  const diff = dayjs(target).diff(dayjs(), 'second');
  if (diff <= 0) return null;

  const days = Math.floor(diff / 86400);
  const hours = Math.floor((diff % 86400) / 3600);

  return (
    <span style={{ fontSize: 12, opacity: 0.8 }}>
      <ClockCircleOutlined style={{ marginRight: 4 }} />
      {label}: {days > 0 ? `${days}d ` : ''}{hours}h
    </span>
  );
}

export default function ChallengeCard({ challenge, myTeam }: ChallengeCardProps) {
  const navigate = useNavigate();
  const metric = (METRIC_MAP[challenge.metric] || METRIC_MAP.DOORS_KNOCKED)!;
  const teamCount = challenge._count?.teams ?? challenge.teams?.length ?? 0;

  const isActive = challenge.status === 'ACTIVE';
  const isUpcoming = challenge.status === 'UPCOMING';

  return (
    <Card
      hoverable
      size="small"
      onClick={() => navigate(`/volunteer/challenges/${challenge.id}`)}
      style={{ cursor: 'pointer' }}
    >
      <Space direction="vertical" size={4} style={{ width: '100%' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <Typography.Text strong style={{ fontSize: 15 }}>
            {challenge.title}
          </Typography.Text>
          <Tag color={STATUS_COLORS[challenge.status]}>{challenge.status}</Tag>
        </div>

        <Space size={8} wrap>
          <Tag icon={metric.icon} color={metric.color}>
            {metric.label}
          </Tag>
          <span style={{ fontSize: 12, opacity: 0.7 }}>
            <TeamOutlined style={{ marginRight: 4 }} />
            {teamCount} team{teamCount !== 1 ? 's' : ''}
          </span>
        </Space>

        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          {dayjs(challenge.startsAt).format('MMM D')} - {dayjs(challenge.endsAt).format('MMM D, YYYY')}
        </Typography.Text>

        {isUpcoming && <CountdownTimer target={challenge.startsAt} label="Starts in" />}
        {isActive && <CountdownTimer target={challenge.endsAt} label="Ends in" />}

        {myTeam && (
          <Badge
            count={`My Team: ${myTeam.name}`}
            style={{ backgroundColor: '#1890ff', fontSize: 11 }}
          />
        )}
      </Space>
    </Card>
  );
}
