import {
  ICraftableItem,
  IEquipmentSet,
  IItemContainer,
  ISkill,
} from '@rpg-engine/shared';
import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import styled from 'styled-components';
import { ItemInfoWrapper } from '../Item/Cards/ItemInfoWrapper';
import { SpriteFromAtlas } from '../shared/SpriteFromAtlas';
import { CraftingTooltip } from './CraftingTooltip';
import { modifyString } from './utils/modifyString';

interface ICraftingRecipeProps {
  atlasJSON: any;
  atlasIMG: any;
  equipmentSet?: IEquipmentSet | null;
  recipe: ICraftableItem;
  scale?: number;
  handleRecipeSelect: () => void;
  selectedCraftItemKey?: string;
  inventory?: IItemContainer | null;
  skills?: ISkill | null;
}

const RadioOptionsWrapper = styled.div`
  display: flex;
  align-items: stretch;
  margin-bottom: 0.5rem;
  padding: 8px;
  position: relative;
  cursor: pointer;
`;

const SpriteAtlasWrapper = styled.div`
  margin-right: 40px;
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
`;

const MainContent = styled.div`
  flex: 1;
  min-width: 0;
`;

const ItemHeader = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;

  label {
    font-size: 0.8rem;
    font-weight: bold;
    display: flex;
    align-items: center;
    padding-right: 1rem;
  }
`;

export const CraftingRecipe: React.FC<ICraftingRecipeProps> = ({
  atlasIMG,
  atlasJSON,
  equipmentSet,
  recipe,
  scale,
  handleRecipeSelect,
  selectedCraftItemKey,
  inventory,
  skills,
}) => {
  const [showTooltip, setShowTooltip] = useState(false);
  const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 });
  const wrapperRef = useRef<HTMLDivElement>(null);

  const isSelected = selectedCraftItemKey === recipe.key;

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        wrapperRef.current &&
        !wrapperRef.current.contains(event.target as Node)
      ) {
        setShowTooltip(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const handleClick = () => {
    if (wrapperRef.current) {
      const rect = wrapperRef.current.getBoundingClientRect();
      setTooltipPosition({
        x: rect.right + 10,
        y: rect.top,
      });
      setShowTooltip(true);
    }
  };

  return (
    <RadioOptionsWrapper ref={wrapperRef} onClick={handleClick}>
      <SpriteAtlasWrapper>
        <ItemInfoWrapper
          item={recipe}
          atlasIMG={atlasIMG}
          atlasJSON={atlasJSON}
          equipmentSet={equipmentSet}
          scale={scale}
        >
          <SpriteFromAtlas
            atlasIMG={atlasIMG}
            atlasJSON={atlasJSON}
            spriteKey={recipe.texturePath}
            imgScale={3}
            grayScale={!recipe.canCraft}
          />
        </ItemInfoWrapper>
      </SpriteAtlasWrapper>

      <MainContent>
        <ItemHeader
          onPointerUp={recipe.canCraft ? handleRecipeSelect : undefined}
        >
          <input
            className="rpgui-radio"
            type="radio"
            value={recipe.name}
            name="test"
            disabled={!recipe.canCraft}
            checked={isSelected}
            onChange={handleRecipeSelect}
          />
          <label>{modifyString(recipe.name)}</label>
        </ItemHeader>
      </MainContent>

      {showTooltip &&
        createPortal(
          <CraftingTooltip
            x={tooltipPosition.x}
            y={tooltipPosition.y}
            recipe={recipe}
            inventory={inventory}
            skills={skills}
            atlasIMG={atlasIMG}
            atlasJSON={atlasJSON}
          />,
          document.body
        )}
    </RadioOptionsWrapper>
  );
};
