import { useEffect, useMemo, useState } from "react";
import { Tournament } from "../../types";
import { useAuth } from "@/contexts/auth-context";
import {
  Box,
  Button,
  Card,
  Divider,
  Group,
  Stack,
  Title,
  Text,
  ThemeIcon,
} from "@mantine/core";
import Avatar from "@/components/avatar";
import Countdown from "@/components/countdown";
import ListLink from "@/components/list-link";
import ListButton from "@/components/list-button";
import {
  TrophyIcon,
  CalendarIcon,
  MapPinIcon,
  UsersIcon,
  ListIcon,
} from "@phosphor-icons/react";
import EnrollTeam from "../enroll-team";
import EnrollFreeAgent from "../enroll-free-agent";
import TeamListButton from "./team-list-button";
import Header from "./header";

const UpcomingTournament: React.FC<{ tournament: Tournament }> = ({
  tournament,
}) => {
  const { user, roles } = useAuth();

  const isAdmin = useMemo(() => roles.includes("Admin"), [roles]);
  const userTeam = useMemo(
    () =>
      tournament.teams?.find((team) =>
        team.players?.some((player) => player.id === user?.id)
      ),
    [tournament.teams, user?.id]
  );
  const isUserEnrolled = !!userTeam;

  const enrollmentDeadline = tournament.enroll_time
    ? new Date(tournament.enroll_time)
    : new Date(tournament.start_time);
  const isEnrollmentOpen = enrollmentDeadline > new Date();

  return (
    <Stack gap="lg">
      
      <Header tournament={tournament} />

      {tournament.desc && <Text size="sm">{tournament.desc}</Text>}

      <Card withBorder radius="md" p="lg">
        <Stack gap="md">
          <Group gap="xs" align="center">
            <UsersIcon size={16} />
            <Text size="sm" fw={500}>
              Enrollment
            </Text>
            {isEnrollmentOpen && (
              <Box ml="auto">
                <Countdown
                  date={enrollmentDeadline}
                  label="Time left"
                  color="yellow"
                />
              </Box>
            )}
          </Group>

          {!isUserEnrolled && isEnrollmentOpen && (
            <>
              <EnrollTeam />
              <Divider label="or" />
              <EnrollFreeAgent />
            </>
          )}
        </Stack>
      </Card>

      <Box>
        <Divider />
        {isAdmin && (
          <ListLink
            label={`Manage ${tournament.name}`}
            to={`/admin/tournaments/${tournament.id}`}
            Icon={UsersIcon}
          />
        )}
        <ListButton label="View Rules" Icon={ListIcon} onClick={() => {}} />
        <TeamListButton teams={tournament.teams || []} />
      </Box>
    </Stack>
  );
};

export default UpcomingTournament;
