import { FocusEvent } from "react";

import {
  AbilityManager,
  HelperUtils,
} from "@dndbeyond/character-rules-engine/es";

import {
  InputField,
  InputElements,
} from "~/subApps/builder/components/InputField";

import styles from "./styles.module.css";

interface Props {
  abilities: Array<AbilityManager>;
  minScore?: number;
  maxScore?: number;
}

export default function AbilityScoreManagerManual({
  abilities,
  minScore = 3,
  maxScore = 18,
}: Props) {
  const handleBlur = (
    e: FocusEvent<InputElements>,
    abilityScore: AbilityManager
  ) => {
    // Get the int value from the input
    const parsedValue = HelperUtils.parseInputInt(e.target.value);
    // Create a clamped variable to hold the clamped value
    let clampedValue: number | null = null;
    // If the value is valid, clamp it to the min and max scores
    if (parsedValue !== null)
      clampedValue = HelperUtils.clampInt(parsedValue, minScore, maxScore);
    // Set the score change from the clampped value
    abilityScore.handleScoreChange(clampedValue);
  };

  return (
    <div className=" ability-score-manager ability-score-manager-manual">
      <div className="ability-score-manager-stats">
        {abilities.map((abilityScore) => (
          <div
            className="ability-score-manager-stat"
            key={abilityScore.getId()}
            data-stat-id={abilityScore.getId()}
          >
            <InputField
              className={styles.input}
              type="number"
              label={abilityScore.getLabel() ?? ""}
              initialValue={abilityScore.getBaseScore()}
              inputProps={{
                min: minScore,
                max: maxScore,
                autoComplete: "off",
              }}
              onBlur={(e) => handleBlur(e, abilityScore)}
            />
            <div className="ability-score-manager-stat-total">
              Total: {abilityScore.getTotalScore() ?? "--"}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
