import React from "react";
import { connect, DispatchProp } from "react-redux";
import { AnyAction } from "redux";

import {
  characterActions,
  CharacterConfiguration,
  Constants,
  HelperUtils,
  HtmlSelectOption,
  rulesEngineSelectors,
} from "@dndbeyond/character-rules-engine/es";

import { Select } from "~/components/Select";

import { BuilderAppState } from "../../typings";
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> {
  configuration: CharacterConfiguration;
  initialOptionRemoved: boolean;
  onScoreMethodChange?: (value: number | null) => void;
  hideTilAbilityScoreTypeSet: boolean;
}
class AbilityScoreTypeChooser extends React.PureComponent<Props> {
  static defaultProps = {
    initialOptionRemoved: true,
    hideTilAbilityScoreTypeSet: false,
  };

  handleScoreMethodChange = (value: string): void => {
    const { dispatch, onScoreMethodChange } = this.props;

    const parsedValue = HelperUtils.parseInputInt(value);

    dispatch(characterActions.abilityScoreTypeSetRequest(parsedValue));

    // We need to reset the ability scores value based on which option is selected

    if (onScoreMethodChange) {
      onScoreMethodChange(parsedValue);
    }
  };

  render() {
    const { configuration, initialOptionRemoved, hideTilAbilityScoreTypeSet } =
      this.props;

    const scoreMethodOptions: Array<HtmlSelectOption> = [
      {
        label: "Standard Array",
        value: Constants.AbilityScoreTypeEnum.STANDARD_ARRAY,
      },
      {
        label: "Manual/Rolled",
        value: Constants.AbilityScoreTypeEnum.MANUAL,
      },
      {
        label: "Point Buy",
        value: Constants.AbilityScoreTypeEnum.POINT_BUY,
      },
    ];

    if (hideTilAbilityScoreTypeSet && configuration.abilityScoreType === null) {
      return null;
    }

    return (
      <div className={styles.typeChooser}>
        <Select
          options={scoreMethodOptions}
          onChange={this.handleScoreMethodChange}
          value={configuration.abilityScoreType}
          placeholder="-- Choose a Generation Method --"
          name="ability-score-type"
          hidePlaceholderOption={initialOptionRemoved}
        />
      </div>
    );
  }
}

function mapStateToProps(state: BuilderAppState) {
  return {
    configuration: rulesEngineSelectors.getCharacterConfiguration(state),
  };
}

export default connect(mapStateToProps)(AbilityScoreTypeChooser);
