import { IEquipmentSet, IMarketplaceItem } from '@rpg-engine/shared';
import React, { useEffect, useRef, useState } from 'react';
import { AiFillCaretRight } from 'react-icons/ai';
import styled from 'styled-components';
import { ConfirmModal } from '../ConfirmModal';
import { Dropdown } from '../Dropdown';
import { Input } from '../Input';
import { MarketplaceRows } from './MarketplaceRows';
import { itemRarityOptions, itemTypeOptions, orderByOptions } from './filters';

export interface IBuyPanelProps {
  items: IMarketplaceItem[];
  atlasJSON: any;
  atlasIMG: any;
  onClose: () => void;
  onChangeType: (value: string) => void;
  onChangeRarity: (value: string) => void;
  onChangeOrder: (value: string) => void;
  onChangeNameInput: (value: string) => void;
  onChangeMainLevelInput: (
    value: [number | undefined, number | undefined]
  ) => void;
  onChangeSecondaryLevelInput: (
    value: [number | undefined, number | undefined]
  ) => void;
  onChangePriceInput: (value: [number | undefined, number | undefined]) => void;
  scale?: number;
  equipmentSet?: IEquipmentSet | null;
  onMarketPlaceItemBuy?: (marketPlaceItemId: string) => void;
  characterId: string;
  enableHotkeys?: () => void;
  disableHotkeys?: () => void;
  currentPage: number;
}

export const BuyPanel: React.FC<IBuyPanelProps> = ({
  items,
  atlasIMG,
  atlasJSON,
  onChangeType,
  onChangeRarity,
  onChangeOrder,
  onChangeNameInput,
  onChangeMainLevelInput,
  onChangeSecondaryLevelInput,
  onChangePriceInput,
  equipmentSet,
  onMarketPlaceItemBuy,
  characterId,
  enableHotkeys,
  disableHotkeys,
  currentPage,
}) => {
  const [name, setName] = useState('');
  const [mainLevel, setMainLevel] = useState<
    [number | undefined, number | undefined]
  >([undefined, undefined]);
  const [secondaryLevel, setSecondaryLevel] = useState<
    [number | undefined, number | undefined]
  >([undefined, undefined]);
  const [price, setPrice] = useState<[number | undefined, number | undefined]>([
    undefined,
    undefined,
  ]);
  const [buyingItemId, setBuyingItemId] = useState<string | null>(null);

  const itemsContainer = useRef<HTMLDivElement>(null);

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

  return (
    <>
      {buyingItemId && (
        <ConfirmModal
          onClose={setBuyingItemId.bind(null, null)}
          onConfirm={() => {
            onMarketPlaceItemBuy?.(buyingItemId);
            setBuyingItemId(null);
            enableHotkeys?.();
          }}
          message="Are you sure to buy 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>
        <FilterInputsWrapper>
          <div>
            <p>Main level</p>
            <Input
              onChange={e => {
                setMainLevel([Number(e.target.value), mainLevel[1]]);
                onChangeMainLevelInput([Number(e.target.value), mainLevel[1]]);
              }}
              placeholder="Min"
              type="number"
              min={0}
              onBlur={enableHotkeys}
              onFocus={disableHotkeys}
            />
            <AiFillCaretRight />
            <Input
              onChange={e => {
                setMainLevel([mainLevel[0], Number(e.target.value)]);
                onChangeMainLevelInput([mainLevel[0], Number(e.target.value)]);
              }}
              placeholder="Max"
              type="number"
              min={0}
              onBlur={enableHotkeys}
              onFocus={disableHotkeys}
            />
          </div>

          <div>
            <p>Secondary level</p>
            <Input
              onChange={e => {
                setSecondaryLevel([Number(e.target.value), secondaryLevel[1]]);
                onChangeSecondaryLevelInput([
                  Number(e.target.value),
                  secondaryLevel[1],
                ]);
              }}
              placeholder="Min"
              type="number"
              min={0}
              onBlur={enableHotkeys}
              onFocus={disableHotkeys}
            />
            <AiFillCaretRight />
            <Input
              onChange={e => {
                setSecondaryLevel([secondaryLevel[0], Number(e.target.value)]);
                onChangeSecondaryLevelInput([
                  secondaryLevel[0],
                  Number(e.target.value),
                ]);
              }}
              placeholder="Max"
              type="number"
              min={0}
              onBlur={enableHotkeys}
              onFocus={disableHotkeys}
            />
          </div>

          <div>
            <p>Price</p>
            <Input
              onChange={e => {
                setPrice([Number(e.target.value), price[1]]);
                onChangePriceInput([Number(e.target.value), price[1]]);
              }}
              placeholder="Min"
              type="number"
              min={0}
              className="big-input"
              onBlur={enableHotkeys}
              onFocus={disableHotkeys}
            />
            <AiFillCaretRight />
            <Input
              onChange={e => {
                setPrice([price[0], Number(e.target.value)]);
                onChangePriceInput([price[0], Number(e.target.value)]);
              }}
              placeholder="Max"
              type="number"
              min={0}
              className="big-input"
              onBlur={enableHotkeys}
              onFocus={disableHotkeys}
            />
          </div>
        </FilterInputsWrapper>

        <WrapperContainer>
          <StyledDropdown
            options={itemTypeOptions}
            onChange={onChangeType}
            width="95%"
          />
          <StyledDropdown
            options={itemRarityOptions}
            onChange={onChangeRarity}
            width="95%"
          />
          <StyledDropdown
            options={orderByOptions}
            onChange={onChangeOrder}
            width="100%"
          />
        </WrapperContainer>
      </OptionsWrapper>

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

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

const FilterInputsWrapper = styled.div`
  width: 95%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  margin-left: 10px;
  gap: 5px;
  color: white;
  flex-wrap: wrap;

  p {
    width: auto;
    margin: 0;
  }

  input {
    width: 75px;
    height: 10px;
  }

  .big-input {
    width: 130px;
  }
`;

const WrapperContainer = styled.div`
  display: grid;
  grid-template-columns: 40% 30% 30%;
  justify-content: space-between;
  width: calc(100% - 40px);
  margin-left: 10px;

  .rpgui-content .rpgui-dropdown-imp-header {
    padding: 0px 10px 0 !important;
  }
`;

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

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

const StyledDropdown = styled(Dropdown)`
  margin: 3px !important;
  width: 170px !important;
`;
