import clsx from "clsx";
import { FC, HTMLAttributes, useContext } from "react";
import { useSearchParams } from "react-router-dom";

import {
  CampaignUtils,
  CharacterCurrencyContract,
  RuleDataUtils,
} from "@dndbeyond/character-rules-engine";

import { Button } from "~/components/Button";
import { NumberDisplay } from "~/components/NumberDisplay";
import { useCharacterTheme } from "~/contexts/CharacterTheme";
import { useSidebar } from "~/contexts/Sidebar";
import { useCharacterEngine } from "~/hooks/useCharacterEngine";
import CurrencyButton from "~/tools/js/CharacterSheet/components/CurrencyButton";
import { CoinManagerContext } from "~/tools/js/Shared/managers/CoinManagerContext";
import { InventoryManagerContext } from "~/tools/js/Shared/managers/InventoryManagerContext";
import { PaneIdentifierUtils } from "~/tools/js/Shared/utils";

import { PaneComponentEnum } from "../../Sidebar/types";
import styles from "./styles.module.css";

export interface EquipmentOverviewProps extends HTMLAttributes<HTMLDivElement> {
  activeEquipmentTab: "character" | "party";
}

export const EquipmentOverview: FC<EquipmentOverviewProps> = ({
  className,
  activeEquipmentTab,
  ...props
}) => {
  const {
    partyInfo,
    currencies,
    totalCarriedWeight,
    currentCarriedWeightType,
  } = useCharacterEngine();
  const { isDarkMode } = useCharacterTheme();
  const {
    pane: { paneHistoryStart },
  } = useSidebar();
  const { coinManager } = useContext(CoinManagerContext);
  const { inventoryManager } = useContext(InventoryManagerContext);
  const [searchParams] = useSearchParams();
  const isVttView = searchParams.get("view") === "vtt";

  const isPartyTab = activeEquipmentTab === "party";
  const campaignName = partyInfo ? CampaignUtils.getName(partyInfo) : null;

  const weightSpeedLabel = RuleDataUtils.getWeightSpeedTypeLabel(
    currentCarriedWeightType
  );

  let coin: CharacterCurrencyContract | null = currencies;
  //if "coins in containers" is enabled, get the total coin for either the player or party
  if (isPartyTab && partyInfo) {
    coin = CampaignUtils.getCoin(partyInfo);
  }
  if (coinManager?.canUseCointainers()) {
    coin =
      isPartyTab && partyInfo
        ? coinManager.getAllPartyCoin()
        : coinManager.getAllCharacterCoin();
  }

  const handlePrimaryButtonClick = (
    evt: React.MouseEvent | React.KeyboardEvent
  ): void => {
    evt.stopPropagation();
    evt.nativeEvent.stopImmediatePropagation();
    if (isPartyTab) {
      paneHistoryStart(PaneComponentEnum.CAMPAIGN);
    } else {
      paneHistoryStart(PaneComponentEnum.ENCUMBRANCE);
    }
  };

  const handleCurrencyClick = (
    evt: React.MouseEvent | React.KeyboardEvent
  ): void => {
    evt.stopPropagation();
    evt.nativeEvent.stopImmediatePropagation();

    const partyContainerKey =
      inventoryManager.getPartyEquipmentContainerDefinitionKey();
    const characterContainerKey =
      inventoryManager.getCharacterContainerDefinitionKey();

    paneHistoryStart(
      PaneComponentEnum.CURRENCY,
      PaneIdentifierUtils.generateCurrencyContext(
        isPartyTab && partyContainerKey
          ? partyContainerKey
          : characterContainerKey
      )
    );
  };

  return (
    <div className={clsx([styles.equipmentOverview, className])} {...props}>
      {isPartyTab ? (
        !isVttView ? (
          <Button
            variant="text"
            themed
            className={styles.overviewPrimaryButton}
            onClick={handlePrimaryButtonClick}
            size="x-small"
          >
            {`Campaign: ${campaignName}`}
          </Button>
        ) : (
          <p className={styles.overviewText}>{`Campaign: ${campaignName}`}</p>
        )
      ) : (
        <Button
          variant="text"
          themed
          className={styles.overviewPrimaryButton}
          onClick={handlePrimaryButtonClick}
          size="x-small"
        >
          <div className={styles.weightButton}>
            <span className={styles.weightButtonText}>
              Weight Carried:{" "}
              <NumberDisplay
                className={styles.weight}
                data-testid="weight-carried-number"
                type="weightInLb"
                number={totalCarriedWeight}
              />
            </span>
            <span className={styles.weightSecondaryText}>
              {weightSpeedLabel}
            </span>
          </div>
        </Button>
      )}
      <CurrencyButton
        handleCurrencyClick={handleCurrencyClick}
        coin={coin}
        isDarkMode={isDarkMode}
        shouldShowPartyInventory={isPartyTab}
      />
    </div>
  );
};
