import Button from "@/components/button";
import Sheet from "@/components/sheet/sheet";
import { useAuth } from "@/contexts/auth-context";
import { useSheet } from "@/hooks/use-sheet";
import { Stack, Text } from "@mantine/core";
import useEnrollFreeAgent from "../../hooks/use-enroll-free-agent";

const EnrollFreeAgent = ({ tournamentId, isRegional }: {tournamentId: string, isRegional?: boolean} ) => {
  const { open, isOpen, toggle } = useSheet();
  const { user, phone } = useAuth();

  const { mutate: enrollFreeAgent, isPending: isEnrolling } = useEnrollFreeAgent(isRegional);
  const handleEnroll = () => {
    enrollFreeAgent({ playerId: user!.id, tournamentId, phone }, {
      onSuccess: () => {
        toggle();
      }
    });
  }

  return (
    <>
      <Button variant="subtle" size="sm" onClick={open}>
        {isRegional ? "Enroll" : "Enroll As Free Agent"}
      </Button>

      <Sheet title={isRegional ? "Enrollment" : "Free Agent Enrollment"} opened={isOpen} onChange={toggle}>
        <Stack gap="xs">
          {isRegional ? (
            <>
              <Text size="md">
                Enroll in this regional tournament to be assigned a random partner.
              </Text>
            </>
          ) : (
            <>
              <Text size="md">
                Enrolling as a free agent adds you to a pool of players looking for teammates.
              </Text>
              <Text size="sm" c='dimmed'>
                Once enrolled, you can view other free agents and their phone number in order to coordinate teams and walkout songs.
              </Text>
              <Text size="xs" c="dimmed">
                Important: Enrolling as a free agent does not guarantee a tournament spot. To secure a spot, one team member must register through the app and select a walkout song.
              </Text>
            </>
          )}
          <Button onClick={handleEnroll} loading={isEnrolling}>Confirm</Button>
          <Button variant="subtle" color="red" onClick={toggle}>Cancel</Button>
        </Stack>
      </Sheet>
    </>
  );
};

export default EnrollFreeAgent;
