import { FC, HTMLAttributes } from "react";
import { useDispatch } from "react-redux";

import {
  characterActions,
  ChoiceUtils,
  FeatManager,
} from "@dndbeyond/character-rules-engine/es";

import { HtmlContent } from "~/components/HtmlContent";
import { useCharacterEngine } from "~/hooks/useCharacterEngine";
import { DetailChoice } from "~/tools/js/Shared/containers/DetailChoice";

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

interface Props extends HTMLAttributes<HTMLDivElement> {
  featManager: FeatManager;
}

export const FeatDetail: FC<Props> = ({ featManager, className, ...props }) => {
  const dispatch = useDispatch();
  const { ruleData, entityRestrictionData, choiceInfo } = useCharacterEngine();

  const prerequisiteDescription = featManager.getPrerequisiteDescription();
  const featDescription = featManager.getDescription();

  const handleChoiceChange = (
    id: string | null,
    type: number,
    value: any
  ): void => {
    if (featManager && id !== null) {
      dispatch(
        characterActions.featChoiceSetRequest(
          featManager.getId(),
          type,
          id,
          value
        )
      );
    }
  };
  return (
    <div className={className} {...props}>
      {prerequisiteDescription && (
        <div className={styles.prereq}>
          Prerequisite: {prerequisiteDescription}
        </div>
      )}
      {featDescription && (
        <HtmlContent html={featDescription} withoutTooltips />
      )}
      {featManager.getChoices().length > 0 && (
        <div className={styles.choices}>
          {featManager.getChoices().map((choice) => {
            const id = ChoiceUtils.getId(choice);

            const { description, options: featChoiceOptions } =
              ChoiceUtils.getSortedChoiceOptionsForFeatsInfo(
                featManager.getId(),
                choice,
                ruleData,
                entityRestrictionData
              );

            return (
              <DetailChoice
                {...choice}
                label={choice.label}
                choice={choice}
                key={id !== null ? id : ""}
                options={featChoiceOptions}
                onChange={handleChoiceChange}
                choiceInfo={choiceInfo}
                showBackgroundProficiencyOptions={true}
                description={description}
              />
            );
          })}
        </div>
      )}
    </div>
  );
};
