import { ITaskReward, RewardType, isMobileOrTablet } from '@rpg-engine/shared';
import React from 'react';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { Ellipsis } from '../shared/Ellipsis';
import { SpriteFromAtlas } from '../shared/SpriteFromAtlas';
import { formatTaskKey } from './utils/dailyTasks.utils';

interface IDailyRewardsTooltipProps {
  rewards: ITaskReward[];
  itemsAtlasJSON: Record<string, any>;
  itemsAtlasIMG: string;
  iconAtlasJSON?: Record<string, any>;
  iconAtlasIMG?: string;
}

export const DailyRewardsTooltip: React.FC<IDailyRewardsTooltipProps> = ({
  rewards,
  itemsAtlasJSON,
  itemsAtlasIMG,
}) => {
  const [isExpanded, setIsExpanded] = React.useState(true);
  const isMobile = isMobileOrTablet();

  const sortedRewards = React.useMemo(() => {
    if (!rewards) return [];

    const REWARD_PRIORITY = {
      [RewardType.Item]: 1,
      [RewardType.Gold]: 2,
      [RewardType.Experience]: 3,
    } as const;

    const getPriority = (type: RewardType) =>
      REWARD_PRIORITY[type] ?? Number.MAX_SAFE_INTEGER;

    return [...rewards].sort((a, b) => {
      return getPriority(a.type) - getPriority(b.type);
    });
  }, [rewards]);

  const toggleExpand = () => {
    setIsExpanded(!isExpanded);
  };

  return (
    <TooltipContainer>
      <CollapsibleHeader onClick={toggleExpand}>
        <HeaderText>Rewards?</HeaderText>
        <ExpandIcon>{isExpanded ? '▼' : '▶'}</ExpandIcon>
      </CollapsibleHeader>

      {isExpanded && (
        <CollapsibleContent>
          <RewardsList isMobile={isMobile} rewardCount={sortedRewards.length}>
            {sortedRewards.map((reward: ITaskReward, index: number) => (
              <RewardItem key={index}>
                <RewardIcon>
                  <SpriteFromAtlas
                    atlasJSON={itemsAtlasJSON}
                    atlasIMG={itemsAtlasIMG}
                    spriteKey={reward.texturePath ?? 'check.png'}
                    width={isMobile ? 16 : 18}
                    height={isMobile ? 16 : 18}
                    imgScale={isMobile ? 1.5 : 1.5}
                  />
                </RewardIcon>
                <RewardContent>
                  <RewardLabel isMobile={isMobile}>
                    <Ellipsis maxWidth="100%" maxLines={1}>
                      {formatTaskKey(reward.key ?? reward.type)}
                    </Ellipsis>
                  </RewardLabel>
                  <RewardValue isMobile={isMobile}>×{reward.quantity}</RewardValue>
                </RewardContent>
              </RewardItem>
            ))}
          </RewardsList>
        </CollapsibleContent>
      )}
    </TooltipContainer>
  );
};

const TooltipContainer = styled.div`
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
`;

const RewardsList = styled.div<{ isMobile: boolean; rewardCount: number }>`
  display: grid;
  grid-template-columns: ${props =>
    props.rewardCount > 2 && !props.isMobile ? 'repeat(2, 1fr)' : '1fr'
  };
  gap: ${props => props.isMobile ? '6px' : '8px'};
  column-gap: ${props => props.rewardCount > 2 && !props.isMobile ? '16px' : '8px'};
  width: 100%;
`;

const CollapsibleHeader = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  border-bottom: 1px solid ${uiColors.darkGray};
  width: 100%;
`;

const HeaderText = styled.span`
  color: ${uiColors.yellow} !important;
  font-size: 0.75rem;
  font-weight: 500;
`;

const ExpandIcon = styled.span`
  color: ${uiColors.yellow};
  font-size: 0.7rem;
  margin-left: 8px;
`;

const CollapsibleContent = styled.div`
  display: block;
  padding-top: 6px;
  width: 100%;
`;

const RewardItem = styled.div`
  display: flex;
  align-items: center;
  gap: 4px;
  width: 100%;
  padding: 2px;
  min-height: 22px;
`;

const RewardIcon = styled.div`
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  font-style: normal;
  margin-right: 4px;
  
  * {
    font-style: normal !important;
  }

    position: relative;
  left: -0.5rem;
  top: -0.4rem;
`;

const RewardContent = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;
  min-width: 0;
`;

const RewardLabel = styled.span<{ isMobile: boolean }>`
  color: ${uiColors.yellow};
  font-size: ${props => props.isMobile ? '0.65rem' : '0.7rem'};
  line-height: 1.2;
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
`;

const RewardValue = styled.span<{ isMobile: boolean }>`
  color: ${uiColors.green};
  font-size: ${props => props.isMobile ? '0.6rem' : '0.65rem'};
  line-height: 1.2;
  display: flex;
  align-items: center;
  font-weight: 600;
  flex-shrink: 0;
  margin-left: 8px;
`;
