import { ItemRarities, ItemSubType, ItemType } from '@rpg-engine/shared';
import React, { useMemo, useState } from 'react';
import { FaShoppingCart } from 'react-icons/fa';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { DraggableContainer } from '../DraggableContainer';
import { InternalTabs } from '../InternalTabs/InternalTabs';
import { RPGUIContainerTypes } from '../RPGUI/RPGUIContainer';
import { CTAButton } from '../shared/CTAButton/CTAButton';
import { CartView } from './CartView';
import { useStoreCart } from './hooks/useStoreCart';
import { StoreItemsSection } from './sections/StoreItemsSection';
import { StorePacksSection } from './sections/StorePacksSection';
import { StoreItemDetails } from './StoreItemDetails';
import { IItemPack, IStoreItem, IStoreProps } from './StoreTypes';

export const Store: React.FC<IStoreProps> = ({
  items,
  packs = [],
  atlasJSON,
  atlasIMG,
  onPurchase,
  userAccountType,
  loading = false,
  error,
  onClose,
}) => {
  const [selectedPack, setSelectedPack] = useState<IItemPack | null>(null);
  const [activeTab, setActiveTab] = useState('premium');
  const {
    cartItems,
    handleAddToCart,
    handleRemoveFromCart,
    handlePurchase: handleCartPurchase,
    openCart,
    closeCart,
    getTotalItems,
    getTotalPrice,
    isCartOpen,
  } = useStoreCart();

  const handleAddPackToCart = (pack: IItemPack) => {
    const packItem: IStoreItem = {
      _id: pack.key,
      key: pack.key,
      name: pack.title,
      price: pack.priceUSD,
      texturePath: pack.image.default || pack.image.src,
      textureKey: pack.image.default || pack.image.src,
      type: ItemType.Consumable,
      subType: ItemSubType.Other,
      description: pack.description || '',
      fullDescription: pack.description || '',
      textureAtlas: 'items',
      weight: 0,
      rarity: ItemRarities.Common,
      allowedEquipSlotType: [],
      isEquipable: false,
      isStackable: false,
      isTwoHanded: false,
      hasUseWith: false,
      maxStackSize: 1,
      isUsable: false,
      isStorable: true,
      isSolid: false,
      isItemContainer: false,
    };
    handleAddToCart(packItem, 1);
  };

  const filterItems = (
    itemsToFilter: IStoreItem[],
    type: 'items' | 'premium'
  ): IStoreItem[] => {
    return itemsToFilter.filter(item => {
      if (type === 'premium') {
        return item.requiredAccountType?.length ?? 0 > 0;
      }
      return true;
    });
  };

  const filteredItems = useMemo(
    () => ({
      items: filterItems(items, 'items'),
      premium: filterItems(items, 'premium'),
    }),
    [items]
  );

  if (loading) {
    return <LoadingMessage>Loading...</LoadingMessage>;
  }

  if (error) {
    return <ErrorMessage>{error}</ErrorMessage>;
  }

  const tabs = [
    {
      id: 'premium',
      title: 'Premium',
      content: (
        <StorePacksSection
          packs={packs.filter(pack => pack.priceUSD >= 9.99)}
          onAddToCart={handleAddPackToCart}
          onSelectPack={setSelectedPack}
        />
      ),
    },
    {
      id: 'packs',
      title: 'Packs',
      content: (
        <StorePacksSection
          packs={packs.filter(pack => pack.priceUSD < 9.99)}
          onAddToCart={handleAddPackToCart}
          onSelectPack={setSelectedPack}
        />
      ),
    },
    {
      id: 'items',
      title: 'Items',
      content: (
        <StoreItemsSection
          items={filteredItems.items}
          onAddToCart={handleAddToCart}
          atlasJSON={atlasJSON}
          atlasIMG={atlasIMG}
          userAccountType={userAccountType}
        />
      ),
    },
  ];

  return (
    <DraggableContainer
      title="Store"
      onCloseButton={onClose}
      width="850px"
      minWidth="600px"
      height="auto"
      type={RPGUIContainerTypes.Framed}
      cancelDrag="[class*='Store__Container'], [class*='CartView'], [class*='StoreItemDetails']"
    >
      {isCartOpen ? (
        <CartView
          cartItems={cartItems}
          onRemoveFromCart={handleRemoveFromCart}
          onClose={closeCart}
          onPurchase={async () => {
            await handleCartPurchase(onPurchase);
            return true;
          }}
          atlasJSON={atlasJSON}
          atlasIMG={atlasIMG}
        />
      ) : selectedPack ? (
        <StoreItemDetails
          item={{
            ...selectedPack,
            name: selectedPack.title,
            texturePath: selectedPack.image.default || selectedPack.image.src,
          }}
          imageUrl={selectedPack.image}
          onBack={() => setSelectedPack(null)}
          onAddToCart={() => handleAddPackToCart(selectedPack)}
        />
      ) : (
        <Container>
          <TopBar>
            <CartButton>
              <CTAButton
                icon={<FaShoppingCart />}
                label={`${getTotalItems()} items ($${getTotalPrice().toFixed(
                  2
                )})`}
                onClick={openCart}
              />
            </CartButton>
          </TopBar>
          <MainContent>
            <InternalTabs
              tabs={tabs}
              activeTextColor="#000000"
              activeColor="#fef08a"
              inactiveColor="#6b7280"
              borderColor="#f59e0b"
              hoverColor="#fef3c7"
              activeTab={activeTab}
              onTabChange={setActiveTab}
            />
          </MainContent>
          {cartItems.length > 0 && (
            <Footer>
              <CartSummary>
                <CartInfo>
                  <span>Items in cart:</span>
                  <span>{getTotalItems()}</span>
                </CartInfo>
                <CartInfo>
                  <span>Total:</span>
                  <span>${getTotalPrice().toFixed(2)}</span>
                </CartInfo>
              </CartSummary>
              <CTAButton
                icon={<FaShoppingCart />}
                label={`Proceed to Checkout ($${getTotalPrice().toFixed(2)})`}
                onClick={openCart}
                fullWidth
              />
            </Footer>
          )}
        </Container>
      )}
    </DraggableContainer>
  );
};

const Container = styled.div`
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  gap: 1rem;
`;

const TopBar = styled.div`
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 1rem;
  padding: 0 1rem;
  flex-shrink: 0;
`;

const CartButton = styled.div`
  min-width: fit-content;
`;

const MainContent = styled.div`
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;

  .rpgui-tabs-content {
    flex: 1;
    overflow-y: auto;
    padding-right: 0.5rem;
  }
`;

const Footer = styled.div`
  display: flex;
  flex-direction: column;
  gap: 1rem;
  padding: 1rem;
  border-top: 2px solid #f59e0b;
  background: rgba(0, 0, 0, 0.2);
  flex-shrink: 0;
`;

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

const CartInfo = styled.div`
  display: flex;
  align-items: center;
  gap: 0.75rem;
  font-family: 'Press Start 2P', cursive;
  font-size: 0.75rem;
  color: #ffffff;

  span:last-child {
    color: #fef08a;
  }
`;

const LoadingMessage = styled.div`
  text-align: center;
  color: ${uiColors.white};
  padding: 2rem;
`;

const ErrorMessage = styled.div`
  text-align: center;
  color: ${uiColors.red};
  padding: 2rem;
`;
