import React from 'react';

import ContestLabel, {
  ContestLabelType,
} from '@/components/contest/ContestLabel';
import { ContestSectionVisibility } from '@/components/contest/util';

export type DiscoverContestCardLabelsProps = {
  startTime?: string;
  endTime?: string;
  judgingStart?: string;
  judgingEnd?: string;
  winnersAnnouncedDate?: string;
  contestCategory?: string;
  winnersPlaylistId?: string;
  contestVisibility?: ContestSectionVisibility;
  className?: string;
};

const DiscoverContestCardLabels: React.FC<DiscoverContestCardLabelsProps> = ({
  endTime,
  winnersAnnouncedDate,
  winnersPlaylistId,
  contestVisibility,
  contestCategory,
  className,
}) => {
  // Check if contest is over
  const isContestOver = endTime ? Date.now() > Date.parse(endTime) : false;

  // Check if winners have been announced
  const isWinnersAnnouncedDatePassed = winnersAnnouncedDate
    ? Date.now() > Date.parse(winnersAnnouncedDate)
    : false;

  // Format date as M/D
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  };

  // Determine the contest label text
  const getContestLabelText = () => {
    // 1. If contest is not over, show "Remix Contest"
    if (!isContestOver) {
      return 'Remix Contest';
    }

    // 2. If contest is over but before winners announced date, show "Winners announced M/D"
    if (
      isContestOver &&
      winnersAnnouncedDate &&
      !isWinnersAnnouncedDatePassed
    ) {
      return `Winners announced ${formatDate(winnersAnnouncedDate)}`;
    }

    // 3. If past winners announce date but no valid winner playlist id, show "Winners announced soon"
    if (isWinnersAnnouncedDatePassed && !winnersPlaylistId) {
      return 'Winners announced soon';
    }

    // 4. If both winners announced date passed and winner playlist exists, show "Contest Winners"
    if (isWinnersAnnouncedDatePassed && winnersPlaylistId) {
      return 'Contest Winners';
    }

    // Fallback
    return 'Remix Contest';
  };

  return (
    <div className={`flex h-[22px] items-center gap-[8px] ${className || ''}`}>
      {contestVisibility === ContestSectionVisibility.Staff && (
        <ContestLabel type={ContestLabelType.Staff} text={'STAFF'} />
      )}
      {!isContestOver && contestCategory !== 'community' && (
        <ContestLabel type={ContestLabelType.Collab} text={'Collabs'} />
      )}
      {!isContestOver && contestCategory === 'community' && (
        <ContestLabel type={ContestLabelType.Community} text={'Community'} />
      )}
      <ContestLabel
        type={ContestLabelType.General}
        text={getContestLabelText()}
      />
    </div>
  );
};

export default DiscoverContestCardLabels;
