import { IItemPack } from '@rpg-engine/shared';
import React, { useCallback, useMemo, useState } from 'react';
import { FaCartPlus } from 'react-icons/fa';
import styled from 'styled-components';
import { CTAButton } from '../../shared/CTAButton/CTAButton';
import { ScrollableContent } from '../../shared/ScrollableContent/ScrollableContent';
import { ShoppingCardHorizontal } from '../../shared/ShoppingCart/CartCardHorizontal';

interface IStorePacksSectionProps {
  packs: IItemPack[];
  onAddToCart: (pack: IItemPack) => void;
  onSelectPack?: (pack: IItemPack) => void;
}

export const StorePacksSection: React.FC<IStorePacksSectionProps> = ({
  packs,
  onAddToCart,
  onSelectPack,
}) => {
  const [searchQuery, setSearchQuery] = useState('');

  const renderPackFooter = useCallback(
    (pack: IItemPack) => (
      <FooterContainer>
        <Price>${pack.priceUSD}</Price>
        <CTAButton
          icon={<FaCartPlus />}
          label="Add"
          onClick={e => {
            e.stopPropagation();
            onAddToCart(pack);
          }}
        />
      </FooterContainer>
    ),
    [onAddToCart]
  );

  const renderPack = useCallback(
    (pack: IItemPack) => (
      <ShoppingCardHorizontal
        key={pack.key}
        title={pack.title}
        description={pack.description}
        imageUrl={pack.image}
        footer={renderPackFooter(pack)}
        onClick={() => onSelectPack?.(pack)}
      />
    ),
    [onSelectPack, renderPackFooter]
  );

  const filteredPacks = useMemo(
    () =>
      packs.filter(pack =>
        pack.title.toLowerCase().includes(searchQuery.toLowerCase())
      ),
    [packs, searchQuery]
  );

  return (
    <ScrollableContent
      items={filteredPacks}
      renderItem={renderPack}
      emptyMessage="No packs available."
      searchOptions={{
        value: searchQuery,
        onChange: setSearchQuery,
        placeholder: 'Search packs...',
      }}
      layout="grid"
      gridColumns={2}
      maxHeight="420px"
    />
  );
};

const FooterContainer = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
`;

const Price = styled.span`
  font-family: 'Press Start 2P', cursive;
  font-size: 0.6rem;
  color: #fef08a;
`;
