import React, { useState } from 'react';
import { FaShoppingBag, FaTimes, FaTrash } from 'react-icons/fa';
import styled from 'styled-components';
import { CTAButton } from '../shared/CTAButton/CTAButton';
import { SpriteFromAtlas } from '../shared/SpriteFromAtlas';
import { IStoreItem } from './StoreTypes';

interface ICartViewProps {
  cartItems: { item: IStoreItem; quantity: number }[];
  onRemoveFromCart: (itemKey: string) => void;
  onClose: () => void;
  onPurchase: () => Promise<boolean>;
  atlasJSON: Record<string, any>;
  atlasIMG: string;
}

export const CartView: React.FC<ICartViewProps> = ({
  cartItems,
  onRemoveFromCart,
  onClose,
  onPurchase,
  atlasJSON,
  atlasIMG,
}) => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const total = cartItems.reduce(
    (sum, cartItem) => sum + cartItem.item.price * cartItem.quantity,
    0
  );

  const formatPrice = (price: number) => price.toFixed(2);

  const handlePurchase = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const success = await onPurchase();

      if (!success) {
        setError('Purchase failed. Please try again.');
      }
    } catch (err) {
      setError('An error occurred during purchase. Please try again.');
      console.error('Purchase error:', err);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Container>
      <Header>
        <Title>Shopping Cart</Title>
        <CloseButton onPointerDown={onClose}>
          <FaTimes />
        </CloseButton>
      </Header>

      <CartItems>
        {cartItems.length === 0 ? (
          <EmptyCart>Your cart is empty</EmptyCart>
        ) : (
          cartItems.map(cartItem => (
            <CartItemRow key={cartItem.item.key}>
              <ItemIconContainer>
                <SpriteFromAtlas
                  atlasJSON={atlasJSON}
                  atlasIMG={atlasIMG}
                  spriteKey={cartItem.item.texturePath}
                  width={32}
                  height={32}
                  imgScale={2}
                  centered
                />
              </ItemIconContainer>
              <ItemDetails>
                <ItemName>{cartItem.item.name}</ItemName>
                <ItemInfo>
                  <span>${formatPrice(cartItem.item.price)}</span>
                  <span>×</span>
                  <span>{cartItem.quantity}</span>
                  <span>=</span>
                  <span>
                    ${formatPrice(cartItem.item.price * cartItem.quantity)}
                  </span>
                </ItemInfo>
              </ItemDetails>

              <CTAButton
                icon={<FaTrash />}
                onClick={e => {
                  e.stopPropagation();
                  onRemoveFromCart(cartItem.item.key);
                }}
              />
            </CartItemRow>
          ))
        )}
      </CartItems>

      <Footer>
        <TotalInfo>
          <TotalRow>
            <span>Total:</span>
            <span>${formatPrice(total)}</span>
          </TotalRow>
          {error && <ErrorMessage>{error}</ErrorMessage>}
        </TotalInfo>
        <CTAButton
          icon={<FaShoppingBag />}
          label={isLoading ? 'Processing...' : 'Complete Purchase'}
          onClick={handlePurchase}
          fullWidth
          disabled={cartItems.length === 0 || isLoading}
        />
      </Footer>
    </Container>
  );
};

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

const Header = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const Title = styled.h2`
  font-family: 'Press Start 2P', cursive;
  font-size: 1rem;
  color: #ffffff;
  margin: 0;
`;

const CloseButton = styled.div`
  padding: 0.5rem;
  min-width: unset;
  width: 42px;
  height: 42px;
  display: flex;
  font-size: 1.5rem;
  align-items: center;
  color: white;
  justify-content: center;
`;

const CartItems = styled.div`
  display: flex;
  flex-direction: column;
  gap: 1rem;
  overflow-y: auto;
  flex: 1;
  min-height: 200px;
  padding-right: 0.5rem;

  /* Custom scrollbar styling */
  &::-webkit-scrollbar {
    width: 8px;
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 4px;

    &:hover {
      background-color: rgba(255, 255, 255, 0.3);
    }
  }

  /* Firefox scrollbar styling */
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.2) rgba(0, 0, 0, 0.2);
`;

const EmptyCart = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #ffffff;
  font-family: 'Press Start 2P', cursive;
  font-size: 0.875rem;
  opacity: 0.7;
`;

const CartItemRow = styled.div`
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
`;

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.5rem;
`;

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

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

const Footer = styled.div`
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  padding-top: 1.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
`;

const TotalInfo = styled.div`
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
`;

const TotalRow = styled.div`
  display: flex;
  justify-content: space-between;
  font-family: 'Press Start 2P', cursive;
  font-size: 0.875rem;
  color: #ffffff;

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

const ErrorMessage = styled.div`
  color: #ef4444;
  font-family: 'Press Start 2P', cursive;
  font-size: 0.75rem;
  margin-top: 0.5rem;
  text-align: center;
`;
