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

import { Tooltip } from "@dndbeyond/character-common-components/es";
import {
  LightBuilderSvg,
  ThemedShareSvg,
  ThemedLongRestSvg,
  ThemedShortRestSvg,
} from "@dndbeyond/character-components/es";
import {
  characterActions,
  CampaignDataContract,
  CharacterPreferences,
  characterSelectors,
  CharacterStatusSlug,
  CharacterTheme,
  Constants,
  HitPointInfo,
  Item,
  ItemUtils,
  RuleData,
  rulesEngineSelectors,
} from "@dndbeyond/character-rules-engine/es";
import ListTimeline from "@dndbeyond/fontawesome-cache/svgs/light/list-timeline.svg";
import { GameLogNotificationWrapper } from "@dndbeyond/game-log-components";

import { Link } from "~/components/Link";
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";
import { GameLogState } from "~/tools/js/Shared/stores/typings";

import { appEnvSelectors } from "../../../Shared/selectors";
import StatusSummaryMobile from "../../components/StatusSummaryMobile";
import { sheetAppSelectors } from "../../selectors";
import { SheetAppState } from "../../typings";
import { CharacterHeaderInfo } from "../CharacterHeaderInfo";
import styles from "./styles.module.css";

// 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> {
  hitPointInfo: HitPointInfo;
  fails: number;
  successes: number;
  deathCause: Constants.DeathCauseEnum;
  inspiration: boolean;
  campaign: CampaignDataContract | null;
  builderUrl: string;
  items: Array<Item>;
  preferences: CharacterPreferences;
  ruleData: RuleData;
  isReadonly: boolean;
  theme: CharacterTheme;
  status: CharacterStatusSlug | null;
  paneHistoryStart: PaneInfo["paneHistoryStart"];
  gameLog?: GameLogState;
}
const CharacterHeaderTablet: FC<Props> = ({
  paneHistoryStart,
  isReadonly,
  dispatch,
  inspiration,
  items,
  hitPointInfo,
  fails,
  successes,
  deathCause,
  builderUrl,
  preferences,
  ruleData,
  theme,
  status,
  gameLog,
  campaign,
}) => {
  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 handleGameLogClick = (evt: React.MouseEvent): void => {
    evt.stopPropagation();
    evt.nativeEvent.stopImmediatePropagation();

    paneHistoryStart(PaneComponentEnum.GAME_LOG);
  };
  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 handleHealthSummaryClick = (): void => {
    if (!isReadonly) {
      paneHistoryStart(PaneComponentEnum.HEALTH_MANAGE);
    }
  };
  const handleInspirationClick = (): void => {
    dispatch(characterActions.inspirationSet(!inspiration));
  };
  const hasMagicItem = (): boolean => {
    return !!items.find((item) => ItemUtils.isMagic(item));
  };
  const renderSideContent = (): React.ReactNode => {
    if (isReadonly) {
      if (status === CharacterStatusSlug.PREMADE) {
        return (
          <div>
            <WatchTourDialog />
          </div>
        );
      }
      return (
        <>
          <div className="ct-character-header-tablet__group ct-character-header-tablet__group--summary">
            <StatusSummaryMobile
              hitPointInfo={hitPointInfo}
              fails={fails}
              successes={successes}
              inspiration={inspiration}
              ruleData={ruleData}
              deathCause={deathCause}
              onHealthClick={handleHealthSummaryClick}
              onInspirationClick={handleInspirationClick}
              isInteractive={!isReadonly}
            />
          </div>
        </>
      );
    }

    return (
      <>
        {preferences !== null &&
          preferences.privacyType ===
            Constants.PreferencePrivacyTypeEnum.PUBLIC && (
            <div className="ct-character-header-tablet__group ct-character-header-tablet__group--share">
              <div
                className="ct-character-header-tablet__button"
                onClick={handleShareClick}
                role="button"
                tabIndex={0}
              >
                <div className="ct-character-header-tablet__button-icon">
                  <ThemedShareSvg theme={theme} />
                </div>
                <span className="ct-character-header-tablet__button-label">
                  Share
                </span>
              </div>
            </div>
          )}
        <div
          className={clsx([
            "ct-character-header-tablet__group",
            "ct-character-header-tablet__group--short-rest",
            styles.shortRest,
          ])}
        >
          <div
            className="ct-character-header-tablet__button"
            onClick={handleShortResetClick}
            role="button"
            tabIndex={0}
          >
            <div className="ct-character-header-tablet__button-icon">
              <ThemedShortRestSvg theme={theme} />
            </div>
            <span className="ct-character-header-tablet__button-label">
              Short Rest
            </span>
          </div>
        </div>
        <div className="ct-character-header-tablet__group ct-character-header-tablet__group--long-rest">
          <div
            className="ct-character-header-tablet__button"
            onClick={handleLongResetClick}
            role="button"
            tabIndex={0}
          >
            <div className="ct-character-header-tablet__button-icon">
              <ThemedLongRestSvg theme={theme} />
            </div>
            <span className="ct-character-header-tablet__button-label">
              Long Rest
            </span>
          </div>
        </div>
        {!isVttView && (
          <div className={styles.campaignButtonContainer}>
            <GameLogNotificationWrapper
              themeColor={theme.themeColor}
              gameLogIsOpen={gameLog?.isOpen ?? false}
              notificationOnClick={handleGameLogClick}
            >
              <div
                role="button"
                aria-roledescription="Game Log"
                className={clsx(styles.campaignButtonGroup)}
                onClick={handleGameLogClick}
              >
                <div className={clsx(styles.campaignButton)}>
                  <ListTimeline className={clsx(styles.campaignButtonIcon)} />
                </div>
              </div>
            </GameLogNotificationWrapper>
          </div>
        )}
        <div className="ct-character-header-tablet__group ct-character-header-tablet__group--builder">
          <Tooltip
            isDarkMode={theme.isDarkMode}
            title="Go to builder"
            className="ct-character-header-tablet__builder"
          >
            <Link
              href={builderUrl}
              className="ct-character-header-tablet__builder-link"
              userouter
            >
              <LightBuilderSvg />
            </Link>
          </Tooltip>
        </div>
        <div className="ct-character-header-tablet__group ct-character-header-tablet__group--summary">
          <StatusSummaryMobile
            hitPointInfo={hitPointInfo}
            fails={fails}
            successes={successes}
            deathCause={deathCause}
            inspiration={inspiration}
            ruleData={ruleData}
            onHealthClick={handleHealthSummaryClick}
            onInspirationClick={handleInspirationClick}
            isInteractive={!isReadonly}
          />
        </div>
      </>
    );
  };

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

function mapStateToProps(state: SheetAppState) {
  return {
    hitPointInfo: rulesEngineSelectors.getHitPointInfo(state),
    fails: rulesEngineSelectors.getDeathSavesFailCount(state),
    successes: rulesEngineSelectors.getDeathSavesSuccessCount(state),
    inspiration: rulesEngineSelectors.getInspiration(state),
    builderUrl: sheetAppSelectors.getBuilderUrl(state),
    campaign: rulesEngineSelectors.getCampaign(state),
    items: rulesEngineSelectors.getInventory(state),
    preferences: rulesEngineSelectors.getCharacterPreferences(state),
    isReadonly: appEnvSelectors.getIsReadonly(state),
    ruleData: rulesEngineSelectors.getRuleData(state),
    deathCause: rulesEngineSelectors.getDeathCause(state),
    theme: rulesEngineSelectors.getCharacterTheme(state),
    status: characterSelectors.getStatusSlug(state),
    gameLog: appEnvSelectors.getGameLog(state),
  };
}

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

export default connect(mapStateToProps)(CharacterHeaderTabletContainer);
