import { useState, useEffect } from 'react';
import { getStudents, getUsers } from '../../api/Users';
import { User } from '../../api/Users';
import Select from 'react-select';

type UserDirectoryProps = {
  onSelectUser: (user: User | undefined) => void;
  compact?: boolean;
  label?: string;
  placeholder?: string;
  team_id?: number;
  refreshKey?: boolean;
};

export default function UserDirectory({
  onSelectUser,
  compact = false,
  label = 'Select a student:',
  placeholder = 'Select a student...',
  team_id,
  refreshKey,
}: UserDirectoryProps) {
  const [users, setUsers] = useState<User[]>([]);

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const users =
          (team_id && (await getUsers('student', team_id))) ||
          (await getUsers('student'));
        const students =
          (team_id && (await getStudents(team_id))) || (await getStudents());
        if (users && students) {
          const usersWithStudentId = users.map((user) => {
            const student = students.find(
              (student) => student.user_id === user.user_id
            );
            return {
              ...user,
              student_id: student ? student.student_id : undefined,
              team_id: student ? student.team_id : undefined,
            };
          });
          setUsers(usersWithStudentId);
        } else {
          console.error('Error fetching users:', users, students);
          setUsers([]);
        }
      } catch (error) {
        console.error('Unexpected error fetching users:', error);
        setUsers([]);
      }
    };

    fetchUsers();
  }, [refreshKey]);

  const userOptions = users.map((user) => ({
    value: user,
    label: `${user.first_name} ${user.last_name}, ${user.email_address}`,
  }));

  return (
    <div className='mb-3'>
      {!compact && <label>{label}</label>}
      <Select
        name='users'
        className='react-select-container'
        classNamePrefix='react-select'
        options={userOptions}
        placeholder={placeholder}
        menuPortalTarget={document.body}
        styles={{
          menuPortal: (base) => ({ ...base, zIndex: 100 }),
        }}
        isClearable
        onChange={(selectedOption) => {
          onSelectUser(selectedOption?.value);
        }}
      />
    </div>
  );
}
