import clsx from "clsx";
import React, { FC } from "react";
import { connect, DispatchProp } from "react-redux";
import { Link as RouterLink, useSearchParams } from "react-router-dom";
import { AnyAction } from "redux";

import { Tooltip } from "@dndbeyond/character-common-components/es";
import {
  CampaignSummary,
  LightBuilderSvg,
  ThemedLongRestSvg,
  ThemedShareSvg,
  ThemedShortRestSvg,
} from "@dndbeyond/character-components/es";
import {
  CampaignDataContract,
  CharacterPreferences,
  characterSelectors,
  CharacterStatusSlug,
  CharacterTheme,
  Constants,
  Item,
  ItemUtils,
  rulesEngineSelectors,
} from "@dndbeyond/character-rules-engine/es";

import { useSidebar } from "~/contexts/Sidebar";
import { PaneInfo } from "~/contexts/Sidebar/Sidebar";
import { PaneComponentEnum } from "~/subApps/sheet/components/Sidebar/types";
import { WatchTourDialog } from "~/subApps/sheet/components/WatchTourDialog/WatchTourDialog";

import { appEnvSelectors } from "../../../Shared/selectors";
import { GameLogState } from "../../../Shared/stores/typings";
import { sheetAppSelectors } from "../../selectors";
import { SheetAppState } from "../../typings";
import CharacterHeaderInfo from "../CharacterHeaderInfo";

// TODO: We are typing with AnyAction here to work around issues with UnknownAction, the type that was introduced in Redux 5.
// If we decide to modernize to Redux 5, we will need to refactor much of the Rules Engine redux usage.
interface Props extends DispatchProp<AnyAction> {
  campaign: CampaignDataContract | null;
  builderUrl: string;
  items: Array<Item>;
  preferences: CharacterPreferences;
  theme: CharacterTheme;
  isReadonly: boolean;
  gameLog: GameLogState;
  status: CharacterStatusSlug | null;
  paneHistoryStart: PaneInfo["paneHistoryStart"];
}

const CharacterHeaderDesktop: FC<Props> = ({
  paneHistoryStart,
  items,
  builderUrl,
  campaign,
  preferences,
  isReadonly,
  theme,
  gameLog,
  status,
}) => {
  const [searchParams] = useSearchParams();
  const isVttView = searchParams.get("view") === "vtt";
  const handleCampaignShow = (): void => {
    paneHistoryStart(PaneComponentEnum.CAMPAIGN);
  };
  const handleShortResetClick = (evt: React.MouseEvent): void => {
    evt.stopPropagation();
    evt.nativeEvent.stopImmediatePropagation();

    paneHistoryStart(PaneComponentEnum.SHORT_REST);
  };
  const handleLongResetClick = (evt: React.MouseEvent): void => {
    evt.stopPropagation();
    evt.nativeEvent.stopImmediatePropagation();

    paneHistoryStart(PaneComponentEnum.LONG_REST);
  };
  const handleShareClick = (evt: React.MouseEvent): void => {
    evt.stopPropagation();
    evt.nativeEvent.stopImmediatePropagation();

    paneHistoryStart(PaneComponentEnum.SHARE_URL);
  };
  const hasMagicItem = (): boolean => {
    return !!items.find((item) => ItemUtils.isMagic(item));
  };
  const renderSideContent = (): React.ReactNode => {
    if (isReadonly) {
      if (status === CharacterStatusSlug.PREMADE) {
        return <WatchTourDialog />;
      }

      return (
        <CampaignSummary
          campaign={campaign}
          onCampaignShow={handleCampaignShow}
          gameLog={gameLog}
          theme={theme}
          isDesktop
        />
      );
    }

    return (
      <>
        {preferences !== null &&
          preferences.privacyType ===
            Constants.PreferencePrivacyTypeEnum.PUBLIC && (
            <div className="ct-character-header-desktop__group ct-character-header-desktop__group--share">
              <div
                className="ct-character-header-desktop__button"
                onClick={handleShareClick}
                role="button"
                tabIndex={0}
              >
                <div className="ct-character-header-desktop__button-icon">
                  <ThemedShareSvg theme={theme} />
                </div>
                <span className="ct-character-header-desktop__button-label">
                  Share
                </span>
              </div>
            </div>
          )}
        <div className="ct-character-header-desktop__group ct-character-header-desktop__group--short-rest">
          <div
            className="ct-character-header-desktop__button"
            onClick={handleShortResetClick}
            role="button"
            tabIndex={0}
          >
            <div className="ct-character-header-desktop__button-icon">
              <ThemedShortRestSvg theme={theme} />
            </div>
            <span className="ct-character-header-desktop__button-label">
              Short Rest
            </span>
          </div>
        </div>
        <div className="ct-character-header-desktop__group ct-character-header-desktop__group--long-rest">
          <div
            className={clsx([
              "ct-character-header-desktop__button",
              isVttView && "ct-character-header-desktop__button--vttView",
            ])}
            onClick={handleLongResetClick}
            role="button"
            tabIndex={0}
          >
            <div className="ct-character-header-desktop__button-icon">
              <ThemedLongRestSvg theme={theme} />
            </div>
            <span className="ct-character-header-desktop__button-label">
              Long Rest
            </span>
          </div>
        </div>
        {/*{this.hasMagicItem() &&*/}
        {/*<div className="ct-character-header-desktop__group">*/}
        {/*<div className="ct-character-header-desktop__button" onClick={this.handleDawnClick}>*/}
        {/*<i className="i-menu-dawn" />*/}
        {/*<span className="ct-character-header-desktop__button-label">Dawn</span>*/}
        {/*</div>*/}
        {/*</div>*/}
        {/*}*/}
        {!isVttView && (
          <CampaignSummary
            campaign={campaign}
            onCampaignShow={handleCampaignShow}
            gameLog={gameLog}
            theme={theme}
            isDesktop
          />
        )}
        {!isVttView && (
          <div className="ct-character-header-desktop__group ct-character-header-desktop__group--builder">
            <Tooltip
              isDarkMode={theme.isDarkMode}
              title="Go to builder"
              className="ct-character-header-desktop__builder"
            >
              <RouterLink
                to={builderUrl}
                className="ct-character-header-desktop__builder-link"
                aria-label="Go to builder"
              >
                <LightBuilderSvg />
              </RouterLink>
            </Tooltip>
          </div>
        )}
      </>
    );
  };

  return (
    <div className="ct-character-header-desktop">
      <div className="ct-character-header-desktop__group ct-character-header-desktop__group-tidbits">
        <CharacterHeaderInfo />
      </div>
      <div className="ct-character-header-desktop__group ct-character-header-desktop__group--gap" />
      {renderSideContent()}
    </div>
  );
};

function mapStateToProps(state: SheetAppState) {
  return {
    builderUrl: sheetAppSelectors.getBuilderUrl(state),
    campaign: rulesEngineSelectors.getCampaign(state),
    items: rulesEngineSelectors.getInventory(state),
    preferences: rulesEngineSelectors.getCharacterPreferences(state),
    theme: rulesEngineSelectors.getCharacterTheme(state),
    isReadonly: appEnvSelectors.getIsReadonly(state),
    gameLog: appEnvSelectors.getGameLog(state),
    status: characterSelectors.getStatusSlug(state),
  };
}

const CharacterHeaderDesktopContainer = (props) => {
  const {
    pane: { paneHistoryStart },
  } = useSidebar();
  return (
    <CharacterHeaderDesktop paneHistoryStart={paneHistoryStart} {...props} />
  );
};

export default connect(mapStateToProps)(CharacterHeaderDesktopContainer);
