import Button from "@/components/button";
import Sheet from "@/components/sheet/sheet";
import { useAuth } from "@/contexts/auth-context";
import { useSheet } from "@/hooks/use-sheet";
import { useMemo, useState, useCallback, useEffect } from "react";
import TeamSelectionView from "./team-selection-view";
import TeamForm from "@/features/teams/components/team-form";
import { teamQueries } from "@/features/teams/queries";
import { Team } from "@/features/teams/types";
import { useQuery } from "@tanstack/react-query";
import { Loader } from "@mantine/core";
import useEnrollTeam from "@/features/tournaments/hooks/use-enroll-team";
import { useServerQuery } from "@/lib/tanstack-query/hooks";
import { Trans, useLingui } from "@lingui/react/macro";

interface EnrollTeamProps {
  tournamentId: string;
  onSubmit: () => void;
}

const EnrollTeam = ({ tournamentId, onSubmit }: EnrollTeamProps) => {
  const { open, isOpen, toggle } = useSheet();
  const { user } = useAuth();
  const { t } = useLingui();

  const hasTeams = useMemo(() => !!user?.teams?.length, [user?.teams]);
  const [selectedTeamId, setSelectedTeamId] = useState<string>();
  const [showTeamForm, setShowTeamForm] = useState<boolean>(!hasTeams);
  const [selectedTeam, setSelectedTeam] = useState<Team | null>(null);

  const { data: teamData } = useServerQuery({
    ...teamQueries.details(selectedTeamId || ''),
    options: { enabled: !!selectedTeamId }
  });

  useEffect(() => {
    if (teamData) {
      setSelectedTeam(teamData);
      setShowTeamForm(true);
    }
  }, [teamData]);

  const teamOptions = useMemo(() =>
    user?.teams?.map(team => ({
      value: team.id,
      label: team.name
    })) || [],
    [user?.teams]
  );

  const handleBack = useCallback(() => {
    setSelectedTeamId(undefined);
    setSelectedTeam(null);
    setShowTeamForm(false);
  }, []);

  const handleSelect = useCallback((teamId: string | undefined) => {
    setSelectedTeamId(teamId);
    if (!teamId) {
      setShowTeamForm(true);
    }
  }, []);

  const initialValues = useMemo(() => {
    if (!selectedTeam) return undefined;

    return {
      name: selectedTeam.name,
      song_id: selectedTeam.song_id,
      song_name: selectedTeam.song_name,
      song_artist: selectedTeam.song_artist,
      song_album: selectedTeam.song_album,
      song_start: selectedTeam.song_start,
      song_end: selectedTeam.song_end,
      song_image_url: selectedTeam.song_image_url,
      players: selectedTeam.players.map(player => player.id),
    };
  }, [selectedTeam]);

  const { mutate: enrollTeam, isPending: isEnrolling } = useEnrollTeam();
  const handleEnrollTeam = (teamId: string) => {
    enrollTeam({ tournamentId, teamId }, {
      onSuccess: () => {
        toggle();
        onSubmit();
      }
    });
  }

  return (
    <>
      <Button size="sm" onClick={open}>
        <Trans>Enroll Your Team</Trans>
      </Button>

      <Sheet title={showTeamForm ? t`Team Details` : t`Enroll Team`} opened={isOpen} onChange={toggle}>
        { isEnrolling && <Loader size="lg" /> }
        {showTeamForm && !isEnrolling ? (
          <TeamForm
            close={handleBack}
            tournamentId={tournamentId}
            initialValues={initialValues}
            teamId={selectedTeamId}
            onSubmit={handleEnrollTeam}
          />
        ) : (
          <>
            <TeamSelectionView
              options={teamOptions}
              onSelect={handleSelect}
            />
            <Button mt='sm' variant="subtle" color='red' size="sm" onClick={toggle}>
              <Trans>Cancel</Trans>
            </Button>
          </>
        )}
        
      </Sheet>
    </>
  );
};

export default EnrollTeam;
