import { useCallback } from "react";
import { observer } from "mobx-react-lite";
import {
  ListGroup,
  Nav,
  NavItem,
  NavLink,
  TabContent,
  TabPane,
} from "reactstrap";

import { useAvatarStore } from "src/Stores";
import NoteItem from "src/note/NoteItem";
import { NoteLoading } from "src/Loading";
import { GetAvatar } from "src/avatar/useGetAvatar";
import useGetAvatarAbility from "src/avatar/useGetAvatarAbility";
import { getAbilityInputMode } from "src/Utility";

export default observer(({ avatar: { avatarID } }: { avatar: GetAvatar }) => {
  const { abilitiesTabPosition, tabPosition, setAbilitiesTabPosition } =
    useAvatarStore();

  const getProperties = (i: number) => ({
    className: abilitiesTabPosition === i ? "active route" : "route",
    onClick: () => {
      setAbilitiesTabPosition(i);
    },
  });

  const { isFetched: isAvatarAbilityLoaded, data: avatarAbility } =
    useGetAvatarAbility(
      getAbilityInputMode(abilitiesTabPosition),
      tabPosition === 2 ? avatarID : undefined,
    );

  const AbilityView = useCallback(
    ({ tabPosition }: { tabPosition: number }) => {
      return (
        <TabPane tabId={tabPosition}>
          <ListGroup>
            {isAvatarAbilityLoaded ? (
              avatarAbility.map((avatarAbility) => (
                <NoteItem
                  {...avatarAbility}
                  key={avatarAbility.noteID}
                  wantAvatarID={avatarID}
                />
              ))
            ) : (
              <NoteLoading loadingCount={50} />
            )}
          </ListGroup>
        </TabPane>
      );
    },
    [avatarID, avatarAbility, isAvatarAbilityLoaded],
  );

  return (
    <>
      <Nav tabs>
        <NavItem>
          <NavLink {...getProperties(0)}>⑤K</NavLink>
        </NavItem>
        <NavItem>
          <NavLink {...getProperties(1)}>⑦K</NavLink>
        </NavItem>
        <NavItem>
          <NavLink {...getProperties(2)}>9K</NavLink>
        </NavItem>
      </Nav>
      <TabContent activeTab={abilitiesTabPosition}>
        <AbilityView tabPosition={0} />
        <AbilityView tabPosition={1} />
        <AbilityView tabPosition={2} />
      </TabContent>
    </>
  );
});
