import ContentCard from '../components/shared/ContentCard';
import { getStudents, getUsers, User } from '../api/Users';
import { getFormattedTeamName, getTeam } from '../api/Teams';
import { useAuth } from '../auth/AuthProvider';
import { useEffect, useState } from 'react';
import RosterGrid from '../components/roster/RosterGrid';

export interface TeamData {
  students: User[];
}

interface AdminData {
  admins: User[];
}

export const Team = () => {
  const [teamData, setTeamData] = useState<User[]>([]);
  const [adminData, setAdminData] = useState<User[]>([]);
  const [teamName, setTeamName] = useState<string>();
  //const [userId, setUserId] = useState<number>();
  const [teamId, setTeamId] = useState<number>();
  const [refreshKey, setRefreshKey] = useState(false);

  const { user } = useAuth();

  useEffect(() => {
    getAdmins();
  }, []);

  useEffect(() => {
    if (!user?.user_id) return;
    else {
      getRoster();
    }
  }, [user, refreshKey]);

  const handleRefresh = () => {
    setRefreshKey((prev) => !prev);
  };

  const getRoster = async () => {
    try {
      const students = await getStudents();
      const student = students.find((s) => s.user_id === user?.user_id);

      const team = await getTeam(student?.team_id as number);
      setTeamName(getFormattedTeamName(team));
      const teamMembers = await getUsers('student', team.team_id);
      setTeamId(team.team_id);
      setTeamData(teamMembers); // Ensure an array of team data
    } catch (error) {
      console.error('Error fetching team data:', error);
      setTeamData([]);
    }
  };

  const getAdmins = async () => {
    try {
      const tas = await getUsers('ta');
      const instructors = await getUsers('instructor');
      const adminData = [...tas, ...instructors];

      // Update state
      setAdminData(adminData);
      return adminData;
    } catch (error) {
      console.error('Error fetching admins:', error);
      setAdminData([]); // Ensure state is updated even if an error occurs
    }
  };

  return (
    <>
      <ContentCard
        title={teamName || 'Your Team'}
        description='View the students in your team.'
      >
        <RosterGrid
          roster={teamData}
          isStudentView={true}
          isStudentViewTeamNum={teamId}
          onTriggerRefresh={handleRefresh}
        />
      </ContentCard>
      <ContentCard
        title='Faculty'
        description='View your course instructors and TAs.'
      >
        <RosterGrid
          roster={adminData}
          isStudentView={true}
          isStudentAdmins={true}
        />
      </ContentCard>
    </>
  );
};
