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

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

export const StoreItemRow: React.FC<IStoreItemRowProps> = ({
  item,
  atlasJSON,
  atlasIMG,
  onAddToCart,
  userAccountType,
  showTextInput = false,
  textInputPlaceholder = item.inputPlaceholder,
}) => {
  const [textInputValue, setTextInputValue] = useState('');
  const {
    quantity,
    handleQuantityChange,
    handleBlur,
    incrementQuantity,
    decrementQuantity,
    resetQuantity,
  } = useQuantityControl();

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

  const handleAddToCartInternal = () => {
    if (!hasRequiredAccount) return;
    if (showTextInput) {
      onAddToCart(item, 1, { inputValue: textInputValue });
      setTextInputValue('');
    } else {
      onAddToCart(item, quantity);
      resetQuantity();
    }
  };

  return (
    <ItemWrapper $isHighlighted={item.store?.isHighlighted || false}>
      <ItemIconContainer>
        <SpriteFromAtlas
          atlasJSON={atlasJSON}
          atlasIMG={atlasIMG}
          spriteKey={item.texturePath}
          width={32}
          height={32}
          imgScale={2}
          centered
        />
      </ItemIconContainer>

      <ItemDetails>
        <ItemName>{item.name}</ItemName>
        <ItemPrice>${item.price}</ItemPrice>
        <ItemDescription>{item.description}</ItemDescription>
      </ItemDetails>

      <Controls>
        {/* Show text input if configured, else show arrows only for stackable items */}
        {showTextInput ? (
          <TextInput
            type="text"
            value={textInputValue}
            placeholder={textInputPlaceholder}
            onChange={e => setTextInputValue(e.target.value)}
            className="rpgui-input"
          />
        ) : item.isStackable ? (
          <ArrowsContainer>
            <SelectArrow
              direction="left"
              onPointerDown={decrementQuantity}
              size={24}
            />

            <QuantityInput
              type="number"
              value={quantity}
              onChange={handleQuantityChange}
              onBlur={handleBlur}
              min={1}
              max={99}
              className="rpgui-input"
            />

            <SelectArrow
              direction="right"
              onPointerDown={incrementQuantity}
              size={24}
            />
          </ArrowsContainer>
        ) : null}

        <CTAButton
          icon={<FaCartPlus />}
          label="Add"
          onClick={handleAddToCartInternal}
          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 ItemPrice = styled.div`
  font-family: 'Press Start 2P', cursive;
  font-size: 0.625rem;
  color: #fef08a;
`;

const ItemDescription = styled.div`
  font-family: 'Press Start 2P', cursive;
  font-size: 0.625rem;
  color: rgba(255, 255, 255, 0.7);
  line-height: 1.4;
`;

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

const ArrowsContainer = styled.div`
  position: relative;
  display: flex;
  align-items: center;
  width: 120px;
  height: 42px;
  justify-content: space-between;
`;

const QuantityInput = styled.input`
  width: 40px;
  text-align: center;
  margin: 0 auto;
  font-size: 0.875rem;
  background: rgba(0, 0, 0, 0.2);
  color: #ffffff;
  border: none;
  padding: 0.25rem;

  &::-webkit-inner-spin-button,
  &::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
`;

const TextInput = styled.input`
  width: 120px;
  text-align: center;
  margin: 0 auto;
  font-size: 0.875rem;
  background: rgba(0, 0, 0, 0.2);
  color: #ffffff;
  border: none;
  padding: 0.25rem;
`;
