import { ICraftableItem, IItemContainer, ISkill } from '@rpg-engine/shared';
import React, { useEffect, useRef } from 'react';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { countItemFromInventory } from '../../libs/itemCounter';
import { SpriteFromAtlas } from '../shared/SpriteFromAtlas';
import { modifyString } from './utils/modifyString';

interface ICraftingTooltipProps {
  x: number;
  y: number;
  recipe: ICraftableItem;
  inventory?: IItemContainer | null;
  skills?: ISkill | null;
  atlasIMG: any;
  atlasJSON: any;
}

const OFFSET = 20;

const TooltipContainer = styled.div<{
  x: number;
  y: number;
}>`
  position: fixed;
  left: ${props => props.x}px;
  top: ${props => props.y}px;
  background-color: rgba(0, 0, 0, 0.95);
  color: white;
  text-align: left;
  border-radius: 4px;
  padding: 10px;
  z-index: 1000;
  font-family: 'Press Start 2P', cursive;
  font-size: 0.6rem;
  width: max-content;
  max-width: 250px;
  white-space: normal;
  border: 1px solid ${uiColors.darkGray};
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  line-height: 1.4;
`;

const MinCraftingRequirementsText = styled.div<{ levelIsOk: boolean }>`
  font-size: 0.55rem;
  margin: 0;
  margin-bottom: 12px;
  margin-left: 0.5rem;
  color: ${({ levelIsOk }) =>
    levelIsOk ? uiColors.lightGreen : uiColors.lightGray} !important;
`;

const TooltipTitle = styled.div`
  color: ${uiColors.yellow};
  font-size: 0.6rem;
  margin-bottom: 12px;
  letter-spacing: 0.5px;
`;

const Recipe = styled.div`
  display: flex;
  align-items: center;
  font-size: 0.55rem;
  margin-bottom: 8px;
  margin-left: 4px;

  &:last-child {
    margin-bottom: 0;
  }

  .sprite-from-atlas-img {
    top: 0px;
    left: 0px;
  }
`;

const Ingredient = styled.div<{ isQuantityOk: boolean }>`
  margin: 0;
  margin-left: 14px;
  color: ${({ isQuantityOk }) =>
    isQuantityOk ? uiColors.lightGreen : uiColors.lightGray} !important;
`;

export const CraftingTooltip: React.FC<ICraftingTooltipProps> = ({
  x,
  y,
  recipe,
  inventory,
  skills,
  atlasIMG,
  atlasJSON,
}) => {
  const tooltipRef = useRef<HTMLDivElement>(null);
  const [adjustedPosition, setAdjustedPosition] = React.useState({ x, y });

  useEffect(() => {
    const tooltipElement = tooltipRef.current;
    if (tooltipElement) {
      const rect = tooltipElement.getBoundingClientRect();
      const tooltipWidth = rect.width;
      const tooltipHeight = rect.height;

      let adjustedX = x;
      let adjustedY = y;

      // If tooltip would go off the right edge, show it on the left side of the cursor
      if (x + tooltipWidth + OFFSET > window.innerWidth) {
        adjustedX = x - tooltipWidth - OFFSET;
      } else {
        // Otherwise, show it on the right side of the cursor
        adjustedX = x + OFFSET;
      }

      // Vertical positioning
      if (y + tooltipHeight > window.innerHeight) {
        adjustedY = window.innerHeight - tooltipHeight - OFFSET;
      }
      if (y < OFFSET) {
        adjustedY = OFFSET;
      }

      setAdjustedPosition({ x: adjustedX, y: adjustedY });
    }
  }, [x, y]);

  const levelInSkill =
    (skills?.[
      (recipe?.minCraftingRequirements?.[0] ?? '') as keyof ISkill
    ] as any)?.level ?? 1;

  const levelIsOk = recipe?.levelIsOk ?? false;

  return (
    <TooltipContainer
      ref={tooltipRef}
      x={adjustedPosition.x}
      y={adjustedPosition.y}
    >
      <TooltipTitle>Skill Requirements</TooltipTitle>
      <MinCraftingRequirementsText levelIsOk={levelIsOk}>
        {modifyString(`${recipe?.minCraftingRequirements?.[0] ?? ''}`)} lvl{' '}
        {recipe?.minCraftingRequirements?.[1] ?? 0} ({levelInSkill})
      </MinCraftingRequirementsText>

      <TooltipTitle>Ingredients</TooltipTitle>
      {recipe.ingredients.map((ingredient, index) => {
        const itemQtyInInventory = !inventory
          ? 0
          : countItemFromInventory(ingredient.key, inventory);
        const isQuantityOk = ingredient.qty <= itemQtyInInventory;

        return (
          <Recipe key={index}>
            <SpriteFromAtlas
              atlasIMG={atlasIMG}
              atlasJSON={atlasJSON}
              spriteKey={ingredient.texturePath}
              imgScale={1.2}
            />
            <Ingredient isQuantityOk={isQuantityOk}>
              {modifyString(ingredient.key)} x{ingredient.qty} (
              {itemQtyInInventory})
            </Ingredient>
          </Recipe>
        );
      })}
    </TooltipContainer>
  );
};
