import {
  IProductBlueprint,
  MetadataType,
  UserAccountTypes,
} from '@rpg-engine/shared';
import React from 'react';
import { FaCartPlus } from 'react-icons/fa';
import styled from 'styled-components';
import { SelectArrow } from '../Arrow/SelectArrow';
import { ICharacterProps } from '../Character/CharacterSelection';
import { CTAButton } from '../shared/CTAButton/CTAButton';
import { SpriteFromAtlas } from '../shared/SpriteFromAtlas';
import { useCharacterSkinNavigation } from '../../hooks/useCharacterSkinNavigation';

interface IStoreCharacterSkinRowProps {
  item: IProductBlueprint;
  atlasJSON: Record<string, any>;
  atlasIMG: string;
  onAddToCart: (
    item: IProductBlueprint,
    quantity: number,
    metadata?: Record<string, any>
  ) => void;
  userAccountType: UserAccountTypes;
}

export const StoreCharacterSkinRow: React.FC<IStoreCharacterSkinRowProps> = ({
  item,
  atlasJSON,
  atlasIMG,
  onAddToCart,
  userAccountType,
}) => {
  // Get available characters from metadata
  const availableCharacters: ICharacterProps[] =
    (item.metadataType === MetadataType.CharacterSkin &&
      item.metadataConfig?.availableCharacters) ||
    [];

  // Get the active character entity atlas info
  const entityAtlasJSON = item.metadataConfig?.atlasJSON;
  const entityAtlasIMG = item.metadataConfig?.atlasIMG;

  const {
    currentCharacter,
    handlePreviousSkin,
    handleNextSkin,
  } = useCharacterSkinNavigation(availableCharacters, item.key);

  const hasRequiredAccount =
    !item.requiredAccountType?.length ||
    item.requiredAccountType.includes(userAccountType);

  const handleAddToCart = () => {
    if (!hasRequiredAccount) return;

    // Always use a quantity of 1
    if (availableCharacters.length > 0 && currentCharacter) {
      onAddToCart(item, 1, {
        selectedSkinName: currentCharacter.name,
        selectedSkinTextureKey: currentCharacter.textureKey,
      });
    } else {
      onAddToCart(item, 1);
    }
  };

  const getSpriteKey = (textureKey: string) => {
    return textureKey + '/down/standing/0.png';
  };

  return (
    <ItemWrapper $isHighlighted={item.store?.isHighlighted || false}>
      <ItemIconContainer>
        {entityAtlasJSON && entityAtlasIMG && currentCharacter ? (
          <SpriteFromAtlas
            atlasJSON={entityAtlasJSON}
            atlasIMG={entityAtlasIMG}
            spriteKey={getSpriteKey(currentCharacter.textureKey)}
            width={32}
            height={32}
            imgScale={2}
            centered
          />
        ) : item.texturePath ? (
          <SpriteFromAtlas
            atlasJSON={atlasJSON}
            atlasIMG={atlasIMG}
            spriteKey={item.texturePath}
            width={32}
            height={32}
            imgScale={2}
            centered
          />
        ) : (
          <DefaultIcon>👤</DefaultIcon>
        )}
      </ItemIconContainer>

      <ItemDetails>
        <Header>
          <ItemName>{item.name}</ItemName>
        </Header>
        {availableCharacters.length > 0 && currentCharacter && (
          <SelectedSkinNav>
            <SelectedSkin>Selected:</SelectedSkin>
            <SkinNavArrow
              direction="left"
              onPointerDown={handlePreviousSkin}
              size={24}
            />
            <SelectedSkin>{currentCharacter.name}</SelectedSkin>
            <SkinNavArrow
              direction="right"
              onPointerDown={handleNextSkin}
              size={24}
            />
          </SelectedSkinNav>
        )}
        <ItemPrice>${item.price}</ItemPrice>
      </ItemDetails>
      <Controls>
        <CTAButton
          icon={<FaCartPlus />}
          label="Add"
          onClick={handleAddToCart}
          disabled={!hasRequiredAccount}
        />
      </Controls>
    </ItemWrapper>
  );
};

const ItemWrapper = styled.div<{ $isHighlighted: boolean }>`
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.5rem 1rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  background: ${props =>
    props.$isHighlighted ? 'rgba(255, 215, 0, 0.1)' : 'transparent'};
  border-left: ${props =>
    props.$isHighlighted ? '3px solid #ffd700' : '3px solid transparent'};

  &:last-child {
    border-bottom: none;
  }
`;

const ItemIconContainer = styled.div`
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  padding: 4px;
`;

const ItemDetails = styled.div`
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
`;

const ItemName = styled.div`
  font-family: 'Press Start 2P', cursive;
  font-size: 0.75rem;
  color: #ffffff;
`;

const SelectedSkin = styled.div`
  font-family: 'Press Start 2P', cursive;
  font-size: 0.5rem;
  color: #fef08a;
`;

const ItemPrice = styled.div`
  font-family: 'Press Start 2P', cursive;
  font-size: 0.625rem;
  color: #fef08a;
`;

const Controls = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
  min-width: fit-content;
`;

// Styled arrow override for inline nav arrows
const SkinNavArrow = styled(SelectArrow)`
  position: static;
`;

const Header = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
`;

const SelectedSkinNav = styled.div`
  display: flex;
  align-items: center;
  gap: 0.5rem;
`;

const DefaultIcon = styled.div`
  font-size: 1.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
`;
