import { useEffect, useState } from 'react';
import { updateStudent, getStudents, Student } from '../../api/Users';
import { RosterData } from '../../pages/Roster';
import { useToast } from '../Toast/ToastContext';
import { Form } from 'react-bootstrap';
import { getFormattedTeamName } from '../../api/Teams';

type TeamFormProps = {
  rosterData: RosterData[];
  id: number;
  onClose: () => void;
  onTeamChange: () => void;
  submit: boolean;
  setSubmit: (value: boolean) => void;
};

export default function ChangeTeamForm({
  rosterData,
  id,
  onClose,
  onTeamChange,
  submit,
  setSubmit,
}: TeamFormProps) {
  //const { user: authUser } = useAuth();
  const [section, setSection] = useState('');
  const [targetTeam, setTargetTeam] = useState('');
  const [currTeam, setCurrTeam] = useState<number | undefined>();
  const { addToast } = useToast();

  const [formErrors, setFormErrors] = useState<{
    section?: boolean;
    team?: boolean;
  }>({});

  const validateFields = () => {
    const errors: {
      section?: boolean;
      team?: boolean;
    } = {};

    if (!section) {
      errors.section = true;
    }

    if (!targetTeam) {
      errors.team = true;
    }

    setFormErrors(errors);
    setValidated(true);
    return Object.keys(errors).length === 0;
  };

  const getTeamId = async () => {
    const response = await getStudents();
    const student = response.find((student) => student.user_id === id);
    //console.log(student?.team_id);
    setCurrTeam(student?.team_id);
    //return student?.team_id;
  };

  const handleSubmit = async () => {
    if (validateFields()) {
      try {
        const response = await getStudents();
        const student = response.find((student) => student.user_id === id); // theoretically

        await updateStudent((student as Student).student_id, {
          team_id: parseInt(targetTeam),
        });
        addToast('Student team assignment updated.', 'success');
        onTeamChange();
        onClose();
      } catch (error) {
        addToast('Failed to update student team assignment.', 'danger');
        console.error('Error updating student team assignment:', error);
      }
    }
  };

  const handleFocus = (field: string) => {
    setFormErrors((prevErrors) => ({
      ...prevErrors,
      [field]: false, // Reset error for the specific field
    }));
  };

  // List of sections for modal
  const sections = rosterData.map((section) => ({
    id: section.id,
    label: `Section ${section.id}`, // Customize this if needed
  }));

  // Filter teams based on the selected section
  const filteredTeams = rosterData
    .filter((data) => data.id === parseInt(section)) // Filter rosterData based on selected section
    .flatMap((data) => data.teams); // Assuming 'teams' is a property in rosterData

  const [validated, setValidated] = useState(false);

  useEffect(() => {
    if (submit) {
      handleSubmit();
      setSubmit(false);
    }
  }, [submit]);

  return (
    <>
      <Form className={`${validated ? 'was-validated' : ''}`} noValidate>
        <Form.Group className='mb-3'>
          <Form.Label>Section:</Form.Label>
          <Form.Select
            value={section}
            onChange={(e) => {
              setSection(e.target.value);
              getTeamId();
            }}
            onFocus={() => handleFocus('section')}
            required
          >
            <option value='' disabled>
              Select a section...
            </option>
            {sections.map((section) => (
              <option key={section.id} value={section.id}>
                {section.label}
              </option>
            ))}
          </Form.Select>
          <Form.Control.Feedback type='invalid'>
            Please select a section.
          </Form.Control.Feedback>
        </Form.Group>
        <Form.Group>
          <Form.Label>Team:</Form.Label>
          <Form.Select
            value={targetTeam}
            onChange={(e) => setTargetTeam(e.target.value)}
            onFocus={() => handleFocus('team')}
            required
            disabled={
              !section ||
              !filteredTeams.filter((t) => t.team_id !== currTeam).length
            }
            isInvalid={
              Boolean(section) &&
              !filteredTeams.filter((t) => t.team_id !== currTeam).length
            }
          >
            <option value='' disabled>
              Select a team...
            </option>
            {filteredTeams
              .sort((a, b) => a.team_num - b.team_num)
              .map(
                (t) =>
                  t.team_id !== currTeam && (
                    <option key={t.team_id} value={t.team_id}>
                      {getFormattedTeamName(t, true)}
                    </option>
                  )
              )}
          </Form.Select>
          <Form.Control.Feedback type='invalid'>
            {filteredTeams.filter((t) => t.team_id !== currTeam).length
              ? 'Please select a team.'
              : 'There are no other teams in the selected section.'}
          </Form.Control.Feedback>
        </Form.Group>
      </Form>
    </>
  );
}
