import React, { useEffect, useState } from "react";
import { FormSelectField } from "@arcteryx/components-form";
import { useTranslation } from "react-i18next";
import subTopicOptions from "../../data/subTopicOptions";

const FsSubTopic = ({ id, label, list, required, defaultValue, name, errors, register, watch, topicSelected }) => {
  const { t } = useTranslation("components-formstack");
  const [ subTopicList, setSubTopicList ] = useState([]);
  const [currentValue] = watch([name]);
  const error = errors[name];
  const valid = error === undefined && currentValue;
  const validSimplePropsForm = {
    labelText: label,
    placeHolderText: t("Please choose a value"),
    list: ['Please choose a value', ...subTopicList],
    disallowEmptyOption: false,
  };
  
  useEffect(() => {
    if (topicSelected) {
    setSubTopicList(list.filter(option => subTopicOptions[topicSelected].includes(option.label)));
  }
  }, [topicSelected])
  
  return (
    <FormSelectField
      id={id}
      label={label}
      required={required}
      defaultValue={defaultValue}
      list={['Please choose a value', ...subTopicList]}
      valid={valid}
      error={errors[name]}
      {...register(name, {
        required: required && t("This field is required."),
      })}
      {...validSimplePropsForm}
    />
  );
};

export default FsSubTopic;
