import {
  IRankingTopCharacterEntry,
  IRankingTopSkillEntry,
} from '@rpg-engine/shared';
import React, { useEffect, useRef } from 'react';
import styled from 'styled-components';
import { Dropdown, IOptionsProps } from '../Dropdown';
import { LeaderboardTable } from './LeaderboardTable';

export interface ILeaderboardProps {
  items: Set<IRankingTopCharacterEntry> | Set<IRankingTopSkillEntry> | null;
  onChangeClassType: (value: string) => void;
  onChangeRankType: (value: string) => void;
  onChangeSkillType: (value: string) => void;
  skillOptions: string[];
  rankOptions: string[];
  classOptions: string[];
  rankType: string;
}

export const Leaderboard = (props: ILeaderboardProps) => {
  const {
    items,
    onChangeRankType,
    onChangeClassType,
    rankType,
    skillOptions,
    onChangeSkillType,
    classOptions,
    rankOptions,
  } = props;
  const itemsContainer = useRef<HTMLDivElement>(null);

  useEffect(() => {
    itemsContainer.current?.scrollTo(0, 0);
  }, []);

  const rankTypeOptions: IOptionsProps[] = rankOptions.map(
    (itemType, index) => ({
      id: index + 1,
      value: itemType,
      option: itemType,
    })
  );

  const skillTypeOptions: IOptionsProps[] = skillOptions.map(
    (itemType, index) => ({
      id: index + 1,
      value: itemType,
      option: itemType,
    })
  );

  const classTypeOptions: IOptionsProps[] = classOptions.map(
    (itemType, index) => ({
      id: index + 1,
      value: itemType,
      option: itemType,
    })
  );

  return (
    <>
      <WrapperContainer>
        <StyledDropdown
          options={rankTypeOptions}
          onChange={onChangeRankType}
          width="80%"
        />
        {rankType === 'Class' ? (
          <StyledDropdown
            options={classTypeOptions}
            onChange={onChangeClassType}
            width="100%"
          />
        ) : null}
        {rankType === 'Skill' ? (
          <StyledDropdown
            options={skillTypeOptions}
            onChange={onChangeSkillType}
            width="100%"
          />
        ) : null}
      </WrapperContainer>
      <ItemComponentScrollWrapper
        id="LeaderboardContainer"
        ref={itemsContainer}
      >
        <TableWrapper>
          <LeaderboardTable items={items} rankType={rankType} />
        </TableWrapper>
      </ItemComponentScrollWrapper>
    </>
  );
};

const WrapperContainer = styled.div`
  display: grid;
  grid-template-columns: 50% 50%;
  justify-content: space-between;
  width: calc(100% - 40px);
  margin-left: 10px;

  .rpgui-content .rpgui-dropdown-imp-header {
    padding: 0px 10px 0 !important;
  }
`;

const StyledDropdown = styled(Dropdown)`
  margin: 3px !important;
  width: 170px !important;
`;

const ItemComponentScrollWrapper = styled.div`
  overflow-y: auto;
  height: 390px;
  width: 100%;
  margin-top: 1rem;

  @media (max-width: 950px) {
    height: 250px;
  }
`;

const TableWrapper = styled.table`
  margin: auto;
  width: 100%;
`;
