import { notificationScenarios } from "../../utils/jobNotificationScenarios.js";
import { Checkbox, Form } from "antd";
import { useTranslation } from "react-i18next";
import PropTypes from "prop-types";

/**
 * ColumnHeaderCheckbox
 * @param channel
 * @param form
 * @param disabled
 * @param onHeaderChange
 * @returns {JSX.Element}
 * @constructor
 */
const ColumnHeaderCheckbox = ({ channel, form, disabled = false, onHeaderChange }) => {
  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 =
    notificationScenarios.length > 0 && notificationScenarios.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 };
    notificationScenarios.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
};

export default ColumnHeaderCheckbox;
