import RosterGrid from '../components/roster/RosterGrid';
import ContentCard from '../components/shared/ContentCard';

import { Team, getTeams } from '../api/Teams';
import { User, getStudents, getUsers } from '../api/Users';

import { useEffect, useState } from 'react';
import { FetchError } from '../utils/FetchHelper';
import UserDirectory from '../components/RequestForm/UserDirectory';
import Breadcrumbs from '../components/roster/Breadcrumbs';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../auth/AuthProvider';
import { Icon } from '../components/shared/Icon';

//import ProfileCard from './ProfileCard';

interface TeamWithStudents extends Team {
  students: User[];
}

export interface RosterData {
  id: number;
  count: number;
  teams: TeamWithStudents[];
  color?: string;
}

interface AdminData {
  admins: User[];
}

export const Roster = () => {
  const [rosterData, setRosterData] = useState<RosterData[]>([]);
  const [adminData, setAdminData] = useState<User[]>([]);
  //const [directoryURL, setDirectoryURL] = useState('');
  const [loading, setLoading] = useState(true);
  const [refreshKey, setRefreshKey] = useState(false);

  const [selectDirectory, setSelectDirectory] = useState<User | undefined>(
    undefined
  ); // directory

  const [breadcrumbItems, setBreadcrumbItems] = useState<
    { label: string; href: string }[]
  >([{ label: 'Roster', href: '/roster' }]);

  // Update the breadcrumb items from a child component
  const updateBreadcrumbs = (newItems: { label: string; href: string }[]) => {
    setBreadcrumbItems(newItems);
  };

  const navigate = useNavigate();
  const { user } = useAuth();

  //let colors = ['#00205B', '#333333', '#F56600', '#8C8279', '#522D80']; // https://www.clemson.edu/brand/color/index.html
  let color = '#cfb991';

  useEffect(() => {
    const fetchData = async () => {
      await getTeamsAndSetRoster();
      await getAdmins();
      setLoading(false); // Only set to false once both are done
    };

    setLoading(true);
    fetchData();
  }, []);

  useEffect(() => {
    const navigateToUser = async () => {
      const freshRoster = await getTeamsAndSetRoster(true);

      for (const section of freshRoster as RosterData[]) {
        for (const team of section.teams) {
          const found = team.students.find(
            (s) => s.user_id === selectDirectory?.user_id
          );
          if (found) {
            navigate(
              `/roster/section/${team.section_id}/team/${team.team_num}`
            );
            return;
          }
        }
      }
    };

    if (selectDirectory) {
      navigateToUser();
      setSelectDirectory(undefined);
    }
  }, [selectDirectory]);

  const getTeamsAndSetRoster = async (skipSetRosterData?: boolean) => {
    const result = await getTeams();

    // Error checking
    if (result instanceof FetchError) {
      if (result.status === undefined) {
        console.error(result.message);
      } else {
        console.error(`HTTP error ${result.status}: ${result.message}`);
      }
    } else {
      // Get all unique sections
      const sectionIds = Array.from(
        new Set(result.map((team: { section_id: number }) => team.section_id))
      ).sort((a, b) => a - b); // Sort numerically

      const rosterData: RosterData[] = await Promise.all(
        sectionIds.map(async (sectionId) => {
          // Add async here
          const teamsForSection = result.filter(
            (team) => team.section_id === sectionId
          );

          // Fetch students for each team
          const teamsWithStudents = await Promise.all(
            teamsForSection.map(async (team) => {
              // Add async here
              const students = await getUsers('student', team.team_id); // Fetch students for the team
              return {
                ...team,
                students: students instanceof FetchError ? [] : students, // Handle errors if needed
              };
            })
          );

          return {
            id: sectionId,
            count: teamsForSection.length,
            teams: teamsWithStudents,
            color: color,
          };
        })
      );

      if (!skipSetRosterData) {
        setRosterData(rosterData);
      }
      return rosterData;
    }
  };

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

  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
    }
  };

  const updateStudent = async (team: TeamWithStudents) => {
    const students = await getStudents(team.team_id);
    if (team.students.length !== students.length) await getTeamsAndSetRoster();
  };

  return (
    <>
      <ContentCard
        title='Roster'
        description='Click into each card to navigate your roster and edit team assignments.'
        fullPage
      >
        {!loading && rosterData.length > 0 ? (
          <div>
            <div className='row g-2 g-md-3'>
              <div className='col-md-6'>
                <Breadcrumbs items={breadcrumbItems}></Breadcrumbs>
              </div>
              <div className='col-md-6'>
                <UserDirectory
                  onSelectUser={async (user) => {
                    if (!user || !rosterData.length) return;

                    setSelectDirectory(user);
                  }}
                  compact
                  refreshKey={refreshKey}
                />
              </div>
            </div>
            <hr className='mt-0' />
            <div style={{ minHeight: '240px' }}>
              <RosterGrid
                roster={rosterData}
                updateBreadcrumbs={updateBreadcrumbs}
                onTriggerRefresh={handleRefresh}
              />
            </div>
          </div>
        ) : (
          rosterData.length === 0 &&
          !loading && (
            <div className='d-flex flex-column justify-content-center align-items-center pt-3'>
              <Icon
                iconName='BackpackFill'
                size={64}
                className='text-warning mb-3'
              />
              <p className='lead text-center'>
                Import your roster to view your course!
              </p>
            </div>
          )
        )}
      </ContentCard>
      <ContentCard
        title='Faculty'
        description={
          user?.type === 'ta'
            ? 'View your course teaching staff.'
            : 'View and manage your course teaching staff.'
        }
        fullPage
      >
        <RosterGrid
          roster={adminData}
          showInstructorsOnly={true}
          updateBreadcrumbs={updateBreadcrumbs}
        />
      </ContentCard>
    </>
  );
};
