import React, { useEffect, useRef, useState } from 'react';
import { Icon } from '../shared/Icon';
import { getTeam, getTeams, updateTeam } from '../../api/Teams';
import { useToast } from '../Toast/ToastContext';
import { OverlayTrigger, Tooltip } from 'react-bootstrap';

interface Props {
  team_id: number;
  locker: number;
  onClick: () => void;
}

const LockerInputGroup = React.memo(({ team_id, locker }: Props) => {
  const [inputValue, setInputValue] = useState('');
  const [initial, setInitial] = useState(true);
  const [isValid, setIsValid] = useState(true);
  const [lockerNum, setLockerNum] = useState<number | null>(locker);
  const [hovered, setHovered] = useState(false); // hover over LockFill blue icon
  const inputRef = useRef<HTMLInputElement | null>(null);
  const [lockers, setLockers] = useState<Number[]>();
  const { addToast } = useToast();

  useEffect(() => {
    //console.log(locker);
    const l = team_id ? applyLocker() : null;
    if (l !== undefined && l !== null) {
      setHovered(false);
    } else {
      setInitial(true);
      setIsValid(true);
      setInputValue('');
    }
  }, [locker]);

  const applyLocker = async () => {
    const team = await getTeam(team_id);
    setLockerNum(team.locker_num || null);

    const teams = await getTeams();
    let lockers: number[] = [];
    teams.forEach((team) => {
      if (team.locker_num) lockers.push(team.locker_num);
    });
    setLockers(lockers);

    return team.locker_num;
  };

  const validateInput = async (e: { target: { value: any } }) => {
    const value = e.target.value;
    setInputValue(value);

    const numberPattern = /^[+-]?\d+(\.\d+)?$/; // Matches integers or decimals
    if (value.trim() == '')
      setInitial(true); // if empty input revert to initial state
    else setInitial(false);

    if (parseInt(value) <= 0) {
      addToast('Locker number must be at least 1.', 'danger');
      setIsValid(false);
    } else if (lockers?.includes(parseInt(value))) {
      addToast('Locker already in use.', 'danger');
      setIsValid(false); // check for prexisting locker if valid number
    } else if (value.trim() === '' || numberPattern.test(value))
      setIsValid(true);
    else setIsValid(false);
  };

  const handleClick = async (
    e?: React.MouseEvent<HTMLSpanElement, MouseEvent>
  ) => {
    if (lockerNum === null) {
      setLockerNum(parseInt(inputValue)); // Locker assigned
      setHovered(false);

      // Add locker to team
      try {
        const team = await getTeam(team_id);
        if (team.team_id !== undefined && inputValue !== null) {
          await updateTeam(team.team_id, {
            locker_num: parseInt(inputValue),
          });
          addToast('Locker assigned to team.', 'success');
        }
      } catch (error) {
        addToast('Failed to assign locker.', 'danger');
        console.error('Error assigning locker to team:', error);
      }
    }
    // Remove locker assignment from team
    else {
      const team = await getTeam(team_id);
      if (inputRef.current) {
        inputRef.current.value = ''; // Clear the input field
      }
      setLockerNum(null); // Unassign locker
      setInputValue(''); // Clear the input
      setIsValid(true); // Reset validation state
      setInitial(true); // Reset initial state

      try {
        if (team.team_id !== undefined) {
          await updateTeam(team.team_id, {
            locker_num: 'unset',
          });

          setLockers((prev) => prev?.filter((item) => item !== locker));

          addToast('Locker unassigned from team.', 'success');
        }
      } catch (error) {
        addToast('Failed to unassign locker.', 'danger');
        console.error('Error assigning locker to team:', error);
      }
    }
  };

  // Function to clear input text when losing focus
  const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
    e.target.value = ''; // Clear the input value
    setIsValid(true);
    setInputValue('');
    setInitial(true);
  };

  return (
    <div
      className='input-container'
      style={{
        position: 'relative',
        display: 'flex',
        justifyContent: 'flex-end',
      }}
    >
      <label htmlFor='lockerInput' className='form-label'></label>
      <div className='input-group'>
        <span
          className={`input-group-text bg-${
            lockerNum !== null
              ? hovered
                ? 'danger'
                : 'success'
              : `${isValid && inputValue !== '' ? 'success' : 'secondary'}`
          } text-white border rounded-start d-flex align-items-center`}
          id='inputGroupPrepend'
          style={{
            cursor:
              (isValid && !initial) || lockerNum !== null
                ? 'pointer'
                : 'default',
          }}
          onMouseDown={(e) => {
            if (lockerNum === null) {
              if (inputValue === '' || !isValid) {
                e.preventDefault(); // Prevent the click from firing when it's the 'Unlock' state
              } else {
                handleClick(e);
              }
            } else {
              // lockerNum current assignment, Delete Icon
              handleClick(e);
            }
          }}
          onMouseEnter={() => setHovered(true)}
          onMouseLeave={() => setHovered(false)}
        >
          {lockerNum === null && isValid && !initial ? (
            <OverlayTrigger
              placement='top'
              overlay={<Tooltip>Click to assign locker to team.</Tooltip>}
            >
              <span className='d-flex justify-content-center align-items-center'>
                Assign
              </span>
            </OverlayTrigger>
          ) : lockerNum !== null ? (
            hovered ? (
              <OverlayTrigger
                placement='top'
                overlay={
                  <Tooltip>
                    Click on the{' '}
                    <Icon
                      iconName={'TrashFill'}
                      style={{ fontSize: '20px', color: 'white' }}
                    />{' '}
                    to remove team locker assignment.
                  </Tooltip>
                }
              >
                <span className='d-flex justify-content-center align-items-center'>
                  <Icon
                    iconName={'TrashFill'}
                    style={{ fontSize: '20px', color: 'white' }}
                  />
                </span>
              </OverlayTrigger>
            ) : (
              <OverlayTrigger
                placement='top'
                overlay={<Tooltip>Locker assigned to team.</Tooltip>}
              >
                <span className='d-flex justify-content-center align-items-center'>
                  <Icon
                    iconName={'LockFill'}
                    style={{ fontSize: '20px', color: 'white' }}
                  />
                </span>
              </OverlayTrigger>
            )
          ) : (
            <span className='d-flex justify-content-center align-items-center'>
              <Icon
                iconName={'Unlock'}
                style={{ fontSize: '20px', color: 'white' }}
              />
            </span>
          )}
        </span>
        <OverlayTrigger
          placement='top'
          overlay={
            lockerNum !== null ? (
              <Tooltip>Team assigned locker #{lockerNum}.</Tooltip>
            ) : inputValue === '' ? (
              <Tooltip>No locker assignment for team.</Tooltip>
            ) : (
              <></>
            )
          }
        >
          <input
            ref={inputRef}
            type='locker'
            id='lockerInput'
            placeholder={lockerNum !== null ? `${lockerNum}` : 'N/A'}
            aria-describedby='inputGroupPrepend'
            maxLength={3}
            style={{
              maxWidth: lockerNum
                ? `${Math.max(lockerNum.toString().length * 10 + 25, 30)}px`
                : inputValue !== null && !initial
                  ? `${Math.max(inputValue.toString().length * 10 + 25, 30)}px`
                  : '55px',

              outline: 'none',
              boxShadow: 'none',
              backgroundColor: isValid
                ? 'transparent'
                : 'rgba(var(--bs-danger-rgb), 0.5)',
            }}
            onInput={validateInput}
            onBlur={handleBlur} // Clear text on blur
            className={`form-control border rounded-end ${!isValid && !initial ? 'feedback-form' : ''}`}
            disabled={lockerNum !== null}
            required
          />
        </OverlayTrigger>
      </div>
    </div>
  );
});

export default LockerInputGroup;
