/* eslint-disable react/button-has-type */
import React, { useCallback, useEffect } from 'react';

import {
  getAvatars, updateAgent, updateAgentProperty
} from '../api';
import { ALL_TEXTS } from '../constants';
import { useAvatarFocus, useWizard } from '../hooks';
import { ACTION_CREATORS } from '../store';
import {
  prepareAvatarPayload, swapItem, t
} from '../utils';
import Button from './UI/Button';

const Avatar = () => {
  const { state, asyncDispatch, dispatch } = useWizard();

  const {
    avatars,
    agentRole,
    selectedAvatar,
    avatarsOffset,
    previewAgentId,
    areAvatarsLoading,
    allAvatarsFetched,
    platformSettings: { PROVIDER_API_KEY }
  } = state;

  const { id: selectedAvatarId } = selectedAvatar;

  const { isShowMoreClicked, avatarButtonRefs, prevAvatarsCount } = useAvatarFocus(avatars.length);

  const fetchAvatars = useCallback(async () => {
    if (areAvatarsLoading) return;

    const data = { limit: 17, nextPageOffset: avatarsOffset };
    await asyncDispatch(
      () => getAvatars(previewAgentId, data, PROVIDER_API_KEY),
      ACTION_CREATORS.getAvatarsRequest,
      ACTION_CREATORS.getAvatarsSuccess,
      ACTION_CREATORS.getAvatarsError
    );
  }, [previewAgentId, avatarsOffset, areAvatarsLoading, asyncDispatch, PROVIDER_API_KEY]);

  // initial fetch
  useEffect(() => {
    fetchAvatars();
  }, []);

  // show more button function
  const handleShowMoreClick = () => {
    isShowMoreClicked.current = true;
    prevAvatarsCount.current = avatars.length;
    fetchAvatars();
  };

  // select avatar
  const handleAvatarClick = async nextAvatar => {
    const avatarsWithNewOrder = swapItem(avatars, nextAvatar.id);
    dispatch(ACTION_CREATORS.setAvatars(avatarsWithNewOrder, nextAvatar));
    // update avatar
    const data = prepareAvatarPayload(nextAvatar);
    asyncDispatch(
      () => updateAgentProperty(previewAgentId, data, PROVIDER_API_KEY),
      ACTION_CREATORS.updateAgentPropertyRequest,
      ACTION_CREATORS.updateAgentPropertySuccess,
      ACTION_CREATORS.updateAgentPropertyError,
      { isAvatar: true, agentName: nextAvatar.avatarName }
    );
    // update agent name
    asyncDispatch(
      () => updateAgent(previewAgentId, { name: nextAvatar.avatarName }, PROVIDER_API_KEY),
      ACTION_CREATORS.updateAgentRequest,
      ACTION_CREATORS.updateAgentSuccess,
      ACTION_CREATORS.updateAgentError
    );
    // update agent title
    asyncDispatch(
      () => updateAgent(previewAgentId, { title: `${nextAvatar.avatarName}: ${agentRole}` }, PROVIDER_API_KEY),
      ACTION_CREATORS.updateAgentRequest,
      ACTION_CREATORS.updateAgentSuccess,
      ACTION_CREATORS.updateAgentError
    );
  };

  const handleAvatarKeyDown = (e, avatar) => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      handleAvatarClick(avatar);
    }
  };

  return (
    <>
      <div className='jfpContent-wrapper--ai-persona-title'>
        <div>
          <h3>{ALL_TEXTS.AGENT_AVATAR}</h3>
          <p>{ALL_TEXTS.SELECT_AN_AVATAR}</p>
        </div>
        <div
          className='jfpContent-wrapper--avatar-gallery'
          role='radiogroup'
          aria-label={ALL_TEXTS.AGENT_AVATAR}
        >
          {avatars
            .map((avatar, index) => (
              <button
                ref={el => { avatarButtonRefs.current[index] = el; }}
                className='avatar-button'
                type='button'
                key={avatar.id}
                onClick={() => handleAvatarClick(avatar)}
                onKeyDown={e => handleAvatarKeyDown(e, avatar)}
                aria-pressed={selectedAvatarId === avatar.id}
                aria-label={`${avatar.avatarName} ${selectedAvatarId === avatar.id ? ALL_TEXTS.CURRENT_AVATAR : ''}`}
                tabIndex={0}
              >
                <img src={avatar.avatarIconLink} alt={`Avatar ${avatar.avatarName}`} />
                {selectedAvatarId === avatar.id && (
                  <div className='avatar-button--selected'>
                    <span>{ALL_TEXTS.CURRENT_AVATAR}</span>
                  </div>
                )}
              </button>
            ))}
        </div>
        <div className='jfpContent-wrapper--ai-persona-show-more'>
          {!allAvatarsFetched && (
            <Button
              colorStyle='primary'
              variant='ghost'
              fullWidth
              onClick={handleShowMoreClick}
              disabled={areAvatarsLoading}
            >
              {areAvatarsLoading ? t(ALL_TEXTS.LOADING) : t(ALL_TEXTS.SHOW_MORE)}
            </Button>
          )}
        </div>
      </div>
    </>
  );
};

export default Avatar;
