import { __ } from '@wordpress/i18n';
import { dispatch } from '@wordpress/data';
import { CART_STORE_KEY } from '@woocommerce/block-data';

import { NovaPostWidget } from '../NovaPostWidget';
import { NoticeMessage } from '../NovaPostWidget/components/NoticeMessage';
import { useShippingContext } from './hooks/useShippingContext';
import { useDivisionData } from './hooks/useDivisionData';
import { useNoticeMessage } from './hooks/useNoticeMessage';

export const NovaPostWidgetBlock = () => {
  const { shippingAddress, divisionData, divisionFilters, errorCalculation, isNovaPostDivisionActive } = useShippingContext();
  const { saveDivisionData, isSaving, saveError } = useDivisionData();
  const noticeMessage = useNoticeMessage(errorCalculation);

  const onChange = async (data) => {
    await saveDivisionData(data);

    if (data?.needRefreshCart) {
      await dispatch(CART_STORE_KEY).invalidateResolutionForStore();
    }
  }

  return (
    <>
      <NoticeMessage message={noticeMessage} />
      {isNovaPostDivisionActive && (
        <NovaPostWidget
          shippingAddress={shippingAddress}
          divisionData={divisionData}
          divisionsFilters={divisionFilters}
          onChange={onChange}
          isSaving={isSaving}
          saveError={saveError}
        />
      )}
    </>
  );
};
