import { getSPForLevel } from '@rpg-engine/shared';
import React from 'react';
import styled from 'styled-components';
import { uiColors } from '../constants/uiColors';
import { ErrorBoundary } from './Item/Inventory/ErrorBoundary';
import { SpriteFromAtlas } from './shared/SpriteFromAtlas';
import { SimpleProgressBar } from './SimpleProgressBar';
import { Tooltip } from './Tooltip/Tooltip';

export interface ISkillProgressBarProps {
  skillName: string;
  bgColor: string;
  level: number;
  skillPoints: number;
  texturePath: string;
  showSkillPoints?: boolean;
  skillPointsToNextLevel: number;
  atlasJSON: any;
  atlasIMG: any;
  buffAndDebuff?: number;
}

export const SkillProgressBar: React.FC<ISkillProgressBarProps> = ({
  bgColor,
  skillName,
  level,
  skillPoints: currentSkillPoints,
  skillPointsToNextLevel,
  texturePath,
  showSkillPoints = true,
  atlasIMG,
  atlasJSON,

  buffAndDebuff,
}) => {
  // Skill points needed to start the current level
  const baseSkillPoints = getSPForLevel(level);
  const calculateProgress = (): number => {
    const totalPointsForLevelUp = Math.max(
      1,
      skillPointsToNextLevel - baseSkillPoints
    );
    const excessSkillPoints = Math.max(0, currentSkillPoints - baseSkillPoints);

    return Math.min(
      100,
      Math.max(0, (excessSkillPoints / totalPointsForLevelUp) * 100)
    );
  };

  const progress = calculateProgress();

  const formatBuffAndDebuff = (value?: number): string =>
    value !== undefined ? value.toFixed(2) : '0';

  const skillsBuffsCalc = (level: number, buffAndDebuff: number): string => {
    if (buffAndDebuff === 0) return '0';
    const result = level * (buffAndDebuff / 100);
    return result > 0 ? `+${result.toFixed(2)}` : `${result.toFixed(2)}`;
  };

  return (
    <>
      <ProgressTitle>
        {buffAndDebuff !== undefined && (
          <>
            {buffAndDebuff > 0 ? (
              <BuffAndDebuffContainer>
                <TitleNameContainer>
                  <TitleNameBuff>{skillName}</TitleNameBuff>
                  <TitleNameBuff>
                    lv {level} ({skillsBuffsCalc(level, buffAndDebuff)})
                  </TitleNameBuff>
                </TitleNameContainer>
                <TitleNameBuffContainer>
                  <TitleNameBuff>
                    (+{formatBuffAndDebuff(buffAndDebuff)}%)
                  </TitleNameBuff>
                </TitleNameBuffContainer>
              </BuffAndDebuffContainer>
            ) : buffAndDebuff < 0 ? (
              <>
                <TitleNameContainer>
                  <TitleNameDebuff>{skillName}</TitleNameDebuff>
                  <TitleNameDebuff>
                    lv {level} ({skillsBuffsCalc(level, buffAndDebuff)})
                  </TitleNameDebuff>
                </TitleNameContainer>
                <div>
                  <TitleNameDebuff>
                    ({formatBuffAndDebuff(buffAndDebuff)}%)
                  </TitleNameDebuff>
                </div>
              </>
            ) : (
              <TitleName>{skillName}</TitleName>
            )}
          </>
        )}
        {!buffAndDebuff && (
          <TitleNameContainer>
            <TitleName>{skillName}</TitleName>
            <ValueDisplay>lv {level}</ValueDisplay>
          </TitleNameContainer>
        )}
      </ProgressTitle>

      <ProgressBody>
        <ProgressIconContainer>
          {atlasIMG && atlasJSON ? (
            <SpriteContainer>
              <ErrorBoundary>
                <SpriteFromAtlas
                  atlasIMG={atlasIMG}
                  atlasJSON={atlasJSON}
                  spriteKey={texturePath}
                  imgScale={1}
                  grayScale
                  opacity={0.5}
                />
              </ErrorBoundary>
            </SpriteContainer>
          ) : (
            <></>
          )}
        </ProgressIconContainer>

        <ProgressBarWrapper>
          <SimpleProgressBar value={progress} bgColor={bgColor} />
          <Tooltip>SP: {currentSkillPoints}</Tooltip>
        </ProgressBarWrapper>
      </ProgressBody>
      {showSkillPoints && (
        <SkillDisplayContainer>
          <SkillPointsDisplay>{progress.toFixed(2)}%</SkillPointsDisplay>
        </SkillDisplayContainer>
      )}
    </>
  );
};

const ProgressBarWrapper = styled.div`
  position: relative;

  &:hover ${Tooltip}, &:active ${Tooltip} {
    visibility: visible;
  }
  width: 100%;
  height: auto;
  top: 8px;
`;

const SpriteContainer = styled.div`
  position: relative;
  top: -3px;
  left: 0;
`;

const SkillDisplayContainer = styled.div`
  margin: 0 auto;

  p {
    margin: 0;
  }
`;

const SkillPointsDisplay = styled.p`
  font-size: 0.55rem !important;
  font-weight: bold;
  text-align: center;
`;

const TitleName = styled.span`
  margin-left: 5px;
`;

const TitleNameBuff = styled.span`
  margin-left: 5px;
  color: ${uiColors.lightGreen} !important;
`;

const TitleNameDebuff = styled.span`
  margin-left: 5px;
  color: ${uiColors.red} !important;
`;

const ValueDisplay = styled.span``;

const ProgressIconContainer = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
`;

const ProgressBody = styled.div`
  display: flex;
  flex-direction: row;
  width: 100%;
`;

const ProgressTitle = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  span {
    font-size: 0.6rem;
  }
`;

const BuffAndDebuffContainer = styled.div``;

const TitleNameBuffContainer = styled.div``;

const TitleNameContainer = styled.div`
  display: flex;
  justify-content: space-between;
`;
