import { IGemSchema, IItem } from '@rpg-engine/shared';
import React, { useState } from 'react';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { Button, ButtonTypes } from '../Button';
import { CheckItem } from '../CheckItem';
import { useResponsiveSize } from '../CraftBook/hooks/useResponsiveSize';
import { DraggableContainer } from '../DraggableContainer';
import { RPGUIContainerTypes } from '../RPGUI/RPGUIContainer';
import { SpriteFromAtlas } from '../shared/SpriteFromAtlas';

export interface IGemSelectorProps {
  atlasJSON: any;
  atlasIMG: any;
  item: IItem;
  scale?: number;
  onClose: () => void;
  onSelect: (selectedGems: IGemSchema[]) => void;
}

export const GemSelector: React.FC<IGemSelectorProps> = ({
  atlasJSON,
  atlasIMG,
  item,
  scale,
  onClose,
  onSelect,
}) => {
  const [selectedGems, setSelectedGems] = useState<IGemSchema[]>([]);
  const size = useResponsiveSize(scale);

  const handleGemToggle = (gem: IGemSchema) => {
    setSelectedGems(prev =>
      prev.some(selected => selected.key === gem.key)
        ? prev.filter(selected => selected.key !== gem.key)
        : [...prev, gem]
    );
  };

  const handleConfirm = () => {
    onSelect(selectedGems);
    onClose();
  };

  if (!size) return null;

  return (
    <DraggableContainer
      type={RPGUIContainerTypes.Framed}
      width="450px"
      height={size.height}
      scale={scale}
      cancelDrag=".gem-selector-container"
      onCloseButton={onClose}
    >
      <ContentWrapper>
        <Header>
          <Title>GEM SELECTION</Title>
          <Subtitle>Select gems to detach</Subtitle>
        </Header>

        <GemGrid>
          {item.attachedGems?.map((gem, index) => {
            return (
              <GemItem key={`${gem.key}-${index}`}>
                <CheckItemWrapper>
                  <CheckItem
                    defaultValue={selectedGems.some(
                      selected => selected.key === gem.key
                    )}
                    onChange={() => {
                      handleGemToggle(gem);
                    }}
                  />
                </CheckItemWrapper>
                <SpriteWrapper>
                  <SpriteFromAtlas
                    atlasIMG={atlasIMG}
                    atlasJSON={atlasJSON}
                    spriteKey={`gems/${gem.key}.png`}
                    imgScale={2}
                    imgClassname="gem-sprite"
                    centered={true}
                  />
                </SpriteWrapper>
                <GemName>
                  {gem.name.replace(/ of /gi, '\n').toUpperCase()}
                </GemName>
              </GemItem>
            );
          })}
        </GemGrid>

        <ButtonWrapper>
          <Button
            buttonType={ButtonTypes.RPGUIButton}
            onPointerDown={() => {
              onClose();
            }}
          >
            Cancel
          </Button>
          <Button
            buttonType={ButtonTypes.RPGUIButton}
            onPointerDown={() => {
              handleConfirm();
            }}
            disabled={selectedGems.length === 0}
          >
            Confirm
          </Button>
        </ButtonWrapper>
      </ContentWrapper>
    </DraggableContainer>
  );
};

const Title = styled.h1`
  font-size: 0.8rem;
  color: ${uiColors.yellow} !important;
`;

const Subtitle = styled.h2`
  font-size: 0.6rem;
  color: ${uiColors.white};
  margin: 0;
`;

const Header = styled.div`
  text-align: center;
  padding: 5px;
  border-bottom: 2px solid #444;
`;

const GemGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-bottom: 20px;
  margin-top: 10px;
  min-height: 150px;
  overflow-y: auto;
`;

const ContentWrapper = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-left: 20px;
  justify-content: space-between;
  height: 100%;
`;

const GemItem = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  background-color: ${uiColors.darkGray} !important;
  height: 100px;
  width: 90px;
  padding: 5px;
`;

const GemName = styled.div`
  font-size: 0.5rem;
  color: ${uiColors.yellow} !important;
  text-align: center;
  text-transform: uppercase;
  line-height: 1.2;
  width: 100%;
  min-height: 30px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  word-break: break-word;
`;

const ButtonWrapper = styled.div`
  display: flex;
  justify-content: center;
  align-self: center;
`;

const CheckItemWrapper = styled.div`
  display: flex;
  justify-content: center;
  width: 100%;
  height: 20px;

  input.rpgui-checkbox + label {
    margin: 0 !important;
    padding-left: 23px !important;
  }
`;

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