import { useEffect, useState } from 'react';
import { useToast } from '../Toast/ToastContext';
import {
  getFormattedTeamName,
  getTeam,
  getTeams,
  updateTeam,
} from '../../api/Teams';
import { Form } from 'react-bootstrap';

type TeamNameFormProps = {
  currName: string;
  setCurrName: (value: string) => void;
  team_id: number;
  onClose: () => void;
  onAdminAdded: () => void;
  submit: boolean;
  setSubmit: (value: boolean) => void;
};

export default function TeamNameForm({
  currName,
  setCurrName,
  team_id,
  onClose,
  onAdminAdded,
  submit,
  setSubmit,
}: TeamNameFormProps) {
  const [name, setName] = useState('');
  const { addToast } = useToast();
  const [formErrors, setFormErrors] = useState<{
    name?: boolean;
    length?: boolean;
    empty?: boolean;
    str?: boolean;
    unique?: boolean;
  }>({});

  const validateFields = async () => {
    const errors: {
      name?: boolean;
      length?: boolean;
      empty?: boolean;
      str?: boolean;
      unique?: boolean;
    } = {};

    if (!name.trim()) {
      errors.empty = true;
      errors.name = true;
    }
    if (name.trim().length > 25) {
      errors.length = true;
      errors.name = true;
    }
    if (typeof name !== 'string') {
      errors.str = true;
      errors.name = true;
    }

    const teams = await getTeams();
    if (!teams) return;
    const names = teams
      .map((team) => team.name)
      .filter((name) => name != null && name.trim() !== '');
    const upperNames = names.map((str) => str?.toUpperCase());
    if (upperNames.includes(name.trim().toUpperCase())) {
      errors.unique = true;
      errors.name = true;
    }

    setFormErrors(errors);
    if (Object.keys(errors).length === 0) {
      setValid(true);
    } else {
      setValid(false);
    }
    return Object.keys(errors).length === 0;
  };

  const handleSubmit = async () => {
    const isValid = await validateFields();
    setValidated(true);

    if (isValid) {
      try {
        await updateTeam(team_id, {
          name: name.trim(),
        });
        addToast('Team name updated.', 'success');
        onAdminAdded();
        onClose();
      } catch (error) {
        addToast('Failed to change team name.', 'danger');
      }
    }
  };

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

  useEffect(() => {
    const retrieveTeamName = async () => {
      const team = await getTeam(team_id);
      setCurrName(getFormattedTeamName(team));
    };

    if (!currName) {
      retrieveTeamName();
    }
  }, [currName]);

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

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

  return (
    <>
      <Form
        onSubmit={(event) => {
          event.preventDefault();
        }}
      >
        <Form.Group>
          <Form.Label>Team name:</Form.Label>
          <Form.Control
            type='text'
            value={name}
            placeholder={
              currName.slice(0, currName.indexOf('(')).trim() || 'Team name...'
            }
            isValid={validated && valid}
            isInvalid={validated && !valid}
            onChange={(e) => setName(e.target.value.trimStart())}
            onFocus={() => handleFocus('name')}
            required
          />
          <Form.Control.Feedback type='invalid'>
            {formErrors.unique
              ? 'Team name already in use. Please enter a different name.'
              : 'Please enter a team name (25 characters or less).'}
          </Form.Control.Feedback>
        </Form.Group>
      </Form>
    </>
  );
}
