import { IItemPack, IPurchase, IProductBlueprint, ItemRarities, ItemSubType, ItemType, UserAccountTypes, PaymentCurrency, PurchaseType } from '@rpg-engine/shared';
import React, { ReactNode, useMemo, useState } from 'react';
import { FaHistory, 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 { MetadataCollector } from './MetadataCollector';
import { StoreItemsSection } from './sections/StoreItemsSection';
import { StorePacksSection } from './sections/StorePacksSection';
import { StoreItemDetails } from './StoreItemDetails';

// Define TabId union type for tab identifiers
type TabId = 'premium' | 'packs' | 'items';

// Define IStoreProps locally as a workaround
export interface IStoreProps {
  items: IProductBlueprint[];
  packs?: IItemPack[];
  atlasJSON: any;
  atlasIMG: string;
  onPurchase: (purchase: Partial<IPurchase>) => Promise<boolean>;
  onShowHistory?: () => void; // Add the new optional prop
  userAccountType: UserAccountTypes;
  loading?: boolean;
  error?: string;
  onClose?: () => void;
  hidePremiumTab?: boolean;
  tabOrder?: TabId[];
  defaultActiveTab?: TabId;
  textInputItemKeys?: string[];
}

export const Store: React.FC<IStoreProps> = ({
  items,
  packs = [],
  atlasJSON,
  atlasIMG,
  onPurchase,
  onShowHistory, // Destructure the new prop
  userAccountType,
  loading = false,
  error,
  onClose,
  hidePremiumTab = false,
  tabOrder,
  defaultActiveTab,
  textInputItemKeys = [],
}) => {
  const [selectedPack, setSelectedPack] = useState<IItemPack | null>(null);
  const [activeTab, setActiveTab] = useState<TabId>(() => {
    const initialTabs = (tabOrder ?? ['premium', 'packs', 'items']).filter(id => !(hidePremiumTab && id === 'premium'));
    if (defaultActiveTab && initialTabs.includes(defaultActiveTab)) {
      return defaultActiveTab;
    }
    return hidePremiumTab ? 'items' : 'premium';
  });
  const {
    cartItems,
    handleAddToCart,
    handleRemoveFromCart,
    handlePurchase: handleCartPurchase,
    openCart,
    closeCart,
    getTotalItems,
    getTotalPrice,
    isCartOpen,
  } = useStoreCart();
  const [isCollectingMetadata, setIsCollectingMetadata] = useState(false);
  const [currentMetadataItem, setCurrentMetadataItem] = useState<IProductBlueprint | null>(null);

  const handleAddPackToCart = (pack: IItemPack) => {
    const packItem: IProductBlueprint = {
      key: pack.key,
      name: pack.title,
      description: pack.description || '',
      price: pack.priceUSD,
      currency: PaymentCurrency.USD,
      texturePath: pack.image.default || pack.image.src,
      type: PurchaseType.Pack,
      onPurchase: async () => {},
      itemType: ItemType.Consumable,
      itemSubType: ItemSubType.Other,
      rarity: ItemRarities.Common,
      weight: 0,
      isStackable: false,
      maxStackSize: 1,
      isUsable: false,
    };
    handleAddToCart(packItem, 1);
  };

  const filterItems = (
    itemsToFilter: IProductBlueprint[],
    type: 'items' | 'premium'
  ): IProductBlueprint[] => {
    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]
  );

  const handleMetadataCollected = (metadata: Record<string, any>) => {
    if (currentMetadataItem && window.__metadataResolvers) {
      // Resolve the promise in the useStoreMetadata hook
      window.__metadataResolvers.resolve(metadata);
      
      // Reset the metadata collection state
      setCurrentMetadataItem(null);
      // Removed unused setPendingMetadataQuantity call
    }
  };

  const handleMetadataCancel = () => {
    if (window.__metadataResolvers) {
      // Resolve with null to indicate cancellation
      window.__metadataResolvers.resolve(null);
    }
    
    // Reset the metadata collection state
    setCurrentMetadataItem(null);
    // Removed unused setPendingMetadataQuantity call
    setIsCollectingMetadata(false);
  };

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

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

  // Build tabs dynamically based on props
  const tabIds: TabId[] = tabOrder ?? ['premium', 'packs', 'items'];
  const availableTabIds: TabId[] = tabIds.filter(id => !(hidePremiumTab && id === 'premium'));

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

  const tabs = availableTabIds.map(id => tabsMap[id]);

  return (
    <DraggableContainer
      title="Store"
      onCloseButton={onClose}
      width="850px"
      minWidth="600px"
      height="auto"
      type={RPGUIContainerTypes.Framed}
      cancelDrag="[class*='Store__Container'], [class*='CartView'], [class*='StoreItemDetails'], .close-button"
    >
      {isCollectingMetadata && currentMetadataItem && currentMetadataItem.metadataType ? (
        <MetadataCollector
          metadataType={currentMetadataItem.metadataType}
          config={currentMetadataItem.metadataConfig || {}}
          onCollect={handleMetadataCollected}
          onCancel={handleMetadataCancel}
        />
      ) : 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>
            <HistoryButton>
              {onShowHistory && (
                <CTAButton
                  icon={<FaHistory />}
                  label="History"
                  onClick={onShowHistory}
                />
              )}
            </HistoryButton>
            <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={(tabId: string) => setActiveTab(tabId as TabId)}
            />
          </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;
  position: relative;
`;

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

const HistoryButton = styled.div`
  min-width: fit-content;
  margin-right: auto;
`;

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;
`;
