import { ItemsById, itemsPerSlot } from "../lib/items";
import type { State } from "../lib/state";
import { Slots, type Item, type Slot } from "../lib/types";
import { ItemLink } from "./ItemLink";
import { ItemTypeahead } from "./ItemTypeahead";
import styles from "./Equipment.module.css";
import { QualitySelector } from "./QualitySelector";

export type Props = {
  state: State;
  onEquip: (item: Item) => void;
  onUnequip: (item: Item) => void;
};

export const Equipment = ({ state, onEquip, onUnequip }: Props) => {
  return (
    <div>
      <ItemTypeahead value={null} onSelect={(item) => item && onEquip(item)} />
      <div className={styles.equipedItems}>
        {Slots.map((slot) => {
          if (itemsPerSlot(slot, state.weaponConfig) > 0) {
            return (
              <Slot
                state={state}
                slot={slot}
                onUnequip={onUnequip}
                key={slot}
              />
            );
          }
          return null;
        })}
      </div>
    </div>
  );
};

type SlotProps = {
  state: State;
  slot: Slot;
  onUnequip: (item: Item) => void;
};

const Slot = ({ state, slot, onUnequip }: SlotProps) => {
  const items = state.equipedItems
    .map((item) => ({ ...item, item: ItemsById[item.id] }))
    .filter((item) => item && item.item.slot === slot);

  return (
    <>
      <div className={`${styles.slot} ${styles.gridItem}`}>{slot}</div>
      {
        // Show placeholder if there are no items
        items.length === 0 && (
          <>
            <div className={`${styles.gridItem} ${styles.item}`}></div>
            <div className={`${styles.gridItem} ${styles.quality}`}></div>
            <div className={`${styles.gridItem} ${styles.actions}`}></div>
          </>
        )
      }
      {items.map((item) => (
        <>
          <div className={`${styles.gridItem} ${styles.item}`}>
            <ItemLink item={item.item} />
          </div>
          <div className={`${styles.gridItem} ${styles.quality}`}>
            <QualitySelector item={item} />
          </div>
          <div className={`${styles.gridItem} ${styles.actions}`}>
            <button onClick={() => onUnequip(item.item)}>X</button>
          </div>
        </>
      ))}
    </>
  );
};
