
// imports
import clsx from 'clsx';
import Link from 'next/link';
import React from 'react';
import initials from 'initials';
import IconPlus from '@chirper/react/src/icons/Plus';
import { useParams } from 'next/navigation';
import { ReactSortable } from 'react-sortablejs';

// locals
import Tooltip from '../../Tooltip';
import useTeam from '../../../hooks/useTeam';
import ApiSignal from '../../../signals/Api';
import { useSignal } from '../../../signal';
import { update as TeamUpdateSignal } from '../../Team/Globals';
import TeamsSignal, { onUpdate as onUpdateTeam } from '../../../signals/Teams';

/**
 * component app teams
 *
 * @param props 
 */
const ComponentAppTeams = (props = {}) => {
  // use signal
  const [sApi] = useSignal(ApiSignal);
  const [sTeams] = useSignal(TeamsSignal);
  const [,setTeamUpdate] = useSignal(TeamUpdateSignal);

  // sorted teams
  const sortedTeams = sTeams.sort((a, b) => {
    // check if a or b is root
    if (a.order < b.order) return -1;
    if (a.order > b.order) return 1;
    return 0;
  });

  // params
  const params = useParams();

  // use team
  const team = useTeam(params.team);

  // handle sort
  const handleSort = (e) => {
    // set indexes
    const newIndex = e.newIndex;
    const currentIndex = e.oldIndex;

    // actual item
    const actualItem = sortedTeams[currentIndex];

    // slot into new index
    if (newIndex < currentIndex) {
      // If moving the item to an earlier position
      sortedTeams.splice(currentIndex, 1); // Remove the item from its current position
      sortedTeams.splice(newIndex, 0, actualItem); // Insert the item at the new position
    } else {
      // If moving the item to a later position
      // We need to adjust the insertion index because removing the item first will shift the array
      sortedTeams.splice(newIndex + 1, 0, actualItem); // Insert the item at the adjusted new position
      sortedTeams.splice(currentIndex, 1); // Remove the item from its original position
    }
    
    // create updates
    const updates = [];

    // loop through sorted teams
    sortedTeams.forEach((team, index) => {
      // check order
      if (team.order !== index) {
        // set order
        team.order = index;
        updates.push(team);
      }
    });

    // loop updates
    updates.forEach(onUpdateTeam);

    // push to api
    sApi.Team.order(updates.map((team) => ({
      id    : team.id,
      order : team.order,
    })));
  };

  // return jsx
  return (
    <div className="flex flex-col p-3 space-y-3 w-16 border-r border-gray-400 min-w-16 max-w-16 dark:border-gray-600">
      {!!sortedTeams.length && (
        <ReactSortable
          list={sortedTeams}
          onEnd={handleSort}
          setList={() => {}}
          className="flex flex-col space-y-3"
        >
          {sortedTeams.map((item) => (
            <Tooltip key={item.id} position="right" title={item.name}>
              <Link
                href={`/${item.id}`}
                className={clsx(
                  'w-10 h-10 font-semibold card group hover:bg-primary-600 hover:!visiblering-primary-600',
                  'flex justify-center items-center p-2 min-w-0',
                  (team?.id === item?.id) && '!text-white !bg-primary-500 hover:!bg-primary-600 !ring-primary-500',
                )}
              >
                <span className="truncate">
                  {initials(item.name)}
                </span>
              </Link>
            </Tooltip>
          ))}
        </ReactSortable>
      )}

      <button
        onClick={() => setTeamUpdate({})}
        className={clsx(
          'w-10 h-10 rounded-lg transition-all duration-300 group hover:bg-primary-500',
          'flex justify-center items-center p-2 min-w-0',
        )}
      >
        <IconPlus className="w-5 h-5" />
      </button>
    </div>
  );
};

/**
 * export default
 */
export default ComponentAppTeams;