import { IEquipmentSet, IItem } from '@rpg-engine/shared';
import React, { useRef } from 'react';
import styled from 'styled-components';
import ModalPortal from '../../Abstractions/ModalPortal';
import { ItemInfoDisplay } from './ItemInfoDisplay';

interface IListMenuOption {
  id: string;
  text: string;
}

export interface MobileItemTooltipProps {
  item: IItem;
  atlasIMG: any;
  atlasJSON: any;
  closeTooltip: () => void;
  equipmentSet?: IEquipmentSet | null;
  scale?: number;
  options?: IListMenuOption[];
  onSelected?: (selectedOptionId: string) => void;
}

export const MobileItemTooltip: React.FC<MobileItemTooltipProps> = ({
  item,
  atlasIMG,
  atlasJSON,
  closeTooltip,
  equipmentSet,
  scale = 1,
  options,
  onSelected,
}) => {
  const ref = useRef<HTMLDivElement>(null);

  const handleFadeOut = () => {
    ref.current?.classList.add('fadeOut');
  };

  return (
    <ModalPortal>
      <Container
        ref={ref}
        onTouchEnd={() => {
          handleFadeOut();
          setTimeout(() => {
            closeTooltip();
          }, 100);
        }}
        scale={scale}
      >
        <ItemInfoDisplay
          item={item}
          atlasIMG={atlasIMG}
          atlasJSON={atlasJSON}
          equipmentSet={equipmentSet}
          isMobile
        />
        <OptionsContainer>
          {options?.map(option => (
            <Option
              key={option.id}
              onTouchEnd={() => {
                handleFadeOut();
                setTimeout(() => {
                  onSelected?.(option.id);
                  closeTooltip();
                }, 100);
              }}
            >
              {option.text}
            </Option>
          ))}
        </OptionsContainer>
      </Container>
    </ModalPortal>
  );
};

const Container = styled.div<{ scale: number }>`
  position: absolute;
  z-index: 100;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0 0 0 / 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 0.5rem;
  transition: opacity 0.08s;
  animation: fadeIn 0.1s forwards;

  @keyframes fadeIn {
    0% {
      opacity: 0;
    }
    100% {
      opacity: 0.92;
    }
  }

  @keyframes fadeOut {
    0% {
      opacity: 0.92;
    }
    100% {
      opacity: 0;
    }
  }

  &.fadeOut {
    animation: fadeOut 0.1s forwards;
  }

  @media (max-width: 640px) {
    flex-direction: column;
  }
`;

const OptionsContainer = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  flex-wrap: wrap;

  @media (max-width: 640px) {
    flex-direction: row;
    justify-content: center;
  }
`;

const Option = styled.button`
  padding: 1rem;
  background-color: #333;
  color: white;
  border: none;
  border-radius: 3px;
  width: 8rem;
  transition: background-color 0.1s;

  &:hover {
    background-color: #555;
  }

  @media (max-width: 640px) {
    padding: 1rem 0.5rem;
  }
`;
