import { Checkbox, Form } from "antd";
import { useTranslation } from "react-i18next";
import PropTypes from "prop-types";

/**
 * ColumnHeaderCheckbox
 * @param channel
 * @param form
 * @param disabled
 * @param onHeaderChange
 * @param scenarioKeys
 * @returns {JSX.Element}
 * @constructor
 */
const ColumnHeaderCheckbox = ({ channel, form, disabled = false, onHeaderChange, scenarioKeys }) => {
  const { t } = useTranslation();

  // Subscribe to all form values so that this component re-renders on changes.
  const formValues = Form.useWatch([], form) || {};

  // Determine if all scenarios for this channel are checked.
  const allChecked = scenarioKeys.length > 0 && scenarioKeys.every((scenario) => formValues[scenario]?.[channel]);

  const onChange = (e) => {
    const checked = e.target.checked;
    // Get current form values.
    const currentValues = form.getFieldsValue();
    // Update each scenario for this channel.
    const newValues = { ...currentValues };
    scenarioKeys.forEach((scenario) => {
      newValues[scenario] = { ...newValues[scenario], [channel]: checked };
    });
    // Update form values.
    form.setFieldsValue(newValues);
    // Manually mark the form as dirty.
    if (onHeaderChange) {
      onHeaderChange();
    }
  };

  return (
    <Checkbox onChange={onChange} checked={allChecked} disabled={disabled}>
      {t(`notifications.channels.${channel}`)}
    </Checkbox>
  );
};

ColumnHeaderCheckbox.propTypes = {
  channel: PropTypes.oneOf(["app", "email", "fcm"]).isRequired,
  form: PropTypes.object.isRequired,
  disabled: PropTypes.bool,
  onHeaderChange: PropTypes.func,
  scenarioKeys: PropTypes.arrayOf(PropTypes.string).isRequired
};

export default ColumnHeaderCheckbox;
