import { IEquipmentSet, IItem, IMarketplaceItem } from '@rpg-engine/shared';
import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { uiFonts } from '../../constants/uiFonts';
import { Button, ButtonTypes } from '../Button';
import { ConfirmModal } from '../ConfirmModal';
import { Input } from '../Input';
import { ItemSlot } from '../Item/Inventory/ItemSlot';
import { MarketplaceRows } from './MarketplaceRows';

export interface IManagmentPanelProps {
  items: IMarketplaceItem[];
  atlasJSON: any;
  atlasIMG: any;
  onChangeNameInput: (value: string) => void;
  equipmentSet?: IEquipmentSet | null;
  availableGold: number;
  onMarketPlaceItemRemove?: (marketPlaceItemId: string) => void;
  selectedItemToSell: IItem | null;
  onSelectedItemToSellRemove: (item: IItem) => void;
  onAddItemToMarketplace: (item: IItem, price: number) => void;
  enableHotkeys?: () => void;
  disableHotkeys?: () => void;
  onMoneyWithdraw: () => void;
  currentPage: number;
}

export const ManagmentPanel: React.FC<IManagmentPanelProps> = ({
  items,
  atlasIMG,
  atlasJSON,
  onChangeNameInput,
  equipmentSet,
  availableGold,
  onMarketPlaceItemRemove,
  selectedItemToSell,
  onSelectedItemToSellRemove,
  onAddItemToMarketplace,
  enableHotkeys,
  disableHotkeys,
  onMoneyWithdraw,
  currentPage,
}) => {
  const [name, setName] = useState('');
  const [price, setPrice] = useState('');
  const [isCreatingOffer, setIsCreatingOffer] = useState(false);
  const [removingItemId, setRemovingItemId] = useState<string | null>(null);

  const itemsContainer = useRef<HTMLDivElement>(null);

  useEffect(() => {
    itemsContainer.current?.scrollTo(0, 0);
  }, [currentPage]);

  return (
    <>
      {isCreatingOffer && (
        <ConfirmModal
          onClose={setIsCreatingOffer.bind(null, false)}
          onConfirm={() => {
            if (selectedItemToSell && price && Number(price)) {
              onAddItemToMarketplace(selectedItemToSell, Number(price));
              setPrice('');
              onSelectedItemToSellRemove(selectedItemToSell);
              setIsCreatingOffer(false);
              enableHotkeys?.();
            }
          }}
          message="Are you sure to create this offer?"
        />
      )}
      {removingItemId && (
        <ConfirmModal
          onClose={setRemovingItemId.bind(null, null)}
          onConfirm={() => {
            onMarketPlaceItemRemove?.(removingItemId);
            setRemovingItemId(null);
            enableHotkeys?.();
          }}
          message="Are you sure to remove this item?"
        />
      )}
      <InputWrapper>
        <p>Search By Name</p>
        <Input
          onChange={e => {
            setName(e.target.value);
            onChangeNameInput(e.target.value);
          }}
          value={name}
          placeholder="Enter name..."
          onBlur={enableHotkeys}
          onFocus={disableHotkeys}
        />
      </InputWrapper>

      <OptionsWrapper>
        <InnerOptionsWrapper>
          <SellDescription>
            Click on item in inventory to sell it
          </SellDescription>
          <Flex>
            <ItemSlot
              slotIndex={0}
              atlasIMG={atlasIMG}
              atlasJSON={atlasJSON}
              onPointerDown={(_, __, item) => onSelectedItemToSellRemove(item)}
              item={selectedItemToSell}
            />
            <PriceInputWrapper>
              <p>Enter price</p>
              <Flex>
                <Input
                  onChange={e => {
                    setPrice(e.target.value);
                  }}
                  value={price}
                  placeholder="Enter price..."
                  type="number"
                  disabled={!selectedItemToSell}
                  onBlur={enableHotkeys}
                  onFocus={disableHotkeys}
                />
                <Button
                  buttonType={ButtonTypes.RPGUIButton}
                  disabled={!selectedItemToSell || !price}
                  onPointerDown={() => {
                    if (selectedItemToSell && price && Number(price)) {
                      setIsCreatingOffer(true);
                    }
                  }}
                >
                  Create offer
                </Button>
              </Flex>
            </PriceInputWrapper>
          </Flex>
        </InnerOptionsWrapper>
        <InnerOptionsWrapper>
          <AvailableGold $disabled={availableGold === 0}>
            <p>Available gold</p>
            <p className="center">${availableGold}</p>
            <Button
              buttonType={ButtonTypes.RPGUIButton}
              disabled={availableGold === 0}
              onPointerDown={() => availableGold > 0 && onMoneyWithdraw()}
            >
              Withdraw
            </Button>
          </AvailableGold>
        </InnerOptionsWrapper>
      </OptionsWrapper>

      <ItemComponentScrollWrapper id="MarketContainer" ref={itemsContainer}>
        {items?.map(({ item, price, _id }, index) => (
          <MarketplaceRows
            key={`${item.key}_${index}`}
            atlasIMG={atlasIMG}
            atlasJSON={atlasJSON}
            item={item}
            itemPrice={price}
            equipmentSet={equipmentSet}
            onMarketPlaceItemRemove={setRemovingItemId.bind(null, _id)}
          />
        ))}
      </ItemComponentScrollWrapper>
    </>
  );
};

const Flex = styled.div`
  display: flex;
  gap: 5px;
  align-items: center;
`;

const InputWrapper = styled.div`
  width: 95%;
  display: flex !important;
  justify-content: flex-start;
  align-items: center;
  margin: auto;

  p {
    width: auto;
    margin-right: 20px;
  }

  input {
    width: 68%;
    height: 10px;
  }
`;

const OptionsWrapper = styled.div`
  width: 100%;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: space-around;
`;

const InnerOptionsWrapper = styled.div`
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  height: 100%;
`;

const ItemComponentScrollWrapper = styled.div`
  overflow-y: scroll;
  height: 390px;
  width: 100%;
  margin-top: 1rem;

  @media (max-width: 950px) {
    height: 250px;
  }
`;

const PriceInputWrapper = styled.div`
  p {
    margin: 0;
  }

  input {
    width: 200px;
  }
`;

const SellDescription = styled.p`
  margin: 0;
  font-size: ${uiFonts.size.xsmall} !important;
`;

const AvailableGold = styled.div<{ $disabled: boolean }>`
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  p {
    margin: 0;
    color: ${props =>
      props.$disabled ? uiColors.lightGray : 'white'} !important;
  }

  .center {
    text-align: center;
    font-size: ${uiFonts.size.large} !important;
    color: ${props =>
      props.$disabled ? uiColors.lightGray : uiColors.lightGreen} !important;
  }
`;
