'use client';

import Tag, { tagColorCssVariables } from '@/components/tag/Tag';
import type { components } from '@/lib/gen';

type ContestSchema = components['schemas']['ContestSchema'];

interface ContestListProps {
  contests: ContestSchema[];
  selectedContest: ContestSchema | null;
  onSelectContest: (contest: ContestSchema) => void;
  isCreating: boolean;
}

export default function ContestList({
  contests,
  selectedContest,
  onSelectContest,
  isCreating,
}: ContestListProps) {
  const getContestStatus = (contest: ContestSchema) => {
    const now = new Date();
    const startTime = contest.start_time ? new Date(contest.start_time) : null;
    const endTime = contest.end_time ? new Date(contest.end_time) : null;

    if (!startTime || !endTime)
      return {
        label: 'Draft',
        style: tagColorCssVariables({
          background: '#6b7280',
          foreground: '#ffffff',
          border: '#6b7280',
        }),
      };
    if (now < startTime)
      return {
        label: 'Upcoming',
        style: tagColorCssVariables({
          background: '#3b82f6',
          foreground: '#ffffff',
          border: '#3b82f6',
        }),
      };
    if (now > endTime)
      return {
        label: 'Ended',
        style: tagColorCssVariables({
          background: '#6b7280',
          foreground: '#ffffff',
          border: '#6b7280',
        }),
      };
    return {
      label: 'Active',
      style: tagColorCssVariables({
        background: '#10b981',
        foreground: '#ffffff',
        border: '#10b981',
      }),
    };
  };

  const formatDate = (dateString: string | null) => {
    if (!dateString) return 'Not set';
    return new Date(dateString).toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
    });
  };

  const sortedContests = [...contests].sort((a, b) => {
    const aStart = a.start_time ? new Date(a.start_time).getTime() : 0;
    const bStart = b.start_time ? new Date(b.start_time).getTime() : 0;
    return bStart - aStart; // Most recent first
  });

  return (
    <div className='p-2'>
      {sortedContests.length === 0 ? (
        <div className='p-4 text-center text-sm text-foreground-secondary'>
          No contests yet. Create one to get started!
        </div>
      ) : (
        <div className='space-y-2'>
          {sortedContests.map((contest) => {
            const status = getContestStatus(contest);
            const isSelected = selectedContest?.id === contest.id;

            return (
              <button
                key={contest.id}
                type='button'
                onClick={() => onSelectContest(contest)}
                className={`w-full rounded-lg p-3 text-left transition-all ${
                  isSelected && !isCreating
                    ? 'border-2 border-blue-500 bg-blue-500/20'
                    : 'border-2 border-transparent bg-background-primary hover:border-border-secondary'
                }`}
              >
                <div className='mb-2 flex items-start justify-between gap-2'>
                  <div className='line-clamp-2 font-medium text-foreground-primary'>
                    {contest.name}
                  </div>
                  <Tag style={status.style} className='flex-shrink-0'>
                    {status.label}
                  </Tag>
                </div>
                <div className='space-y-1 text-xs text-foreground-secondary'>
                  <div>Start: {formatDate(contest.start_time)}</div>
                  <div>End: {formatDate(contest.end_time)}</div>
                </div>
                {contest.slug && (
                  <div className='mt-2 truncate text-xs text-blue-600 dark:text-blue-400'>
                    /collab/{contest.slug}
                  </div>
                )}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}
