/**
 * DeliverySettings — summary row + CapSlideBox trigger for Test and Preview.
 * Rendered only for SMS, Email, WhatsApp. Uses cap-ui-library only.
 *
 * Reference: cap-campaigns-v2 DeliverySettingsV2 (summary + modify panel).
 */

import React, { useState, useCallback } from "react";
import PropTypes from "prop-types";
import CapRow from "@capillarytech/cap-ui-library/CapRow";
import CapHeading from "@capillarytech/cap-ui-library/CapHeading";
import CapIcon from "@capillarytech/cap-ui-library/CapIcon";
import CapLabel from "@capillarytech/cap-ui-library/CapLabel";
import CapSlideBox from "@capillarytech/cap-ui-library/CapSlideBox";
import { FormattedMessage } from "react-intl";
import get from "lodash/get";
import messages from "./messages";
import ModifyDeliverySettings from "./ModifyDeliverySettings";
import {
  CHANNELS,
  CHANNELS_WITH_DELIVERY_SETTINGS,
  SUMMARY_EMPTY_PLACEHOLDER,
  DELIVERY_SETTING_KEY_DOMAIN_ID,
  DELIVERY_SETTING_KEY_GSM_SENDER_ID,
  DELIVERY_SETTING_KEY_SENDER_EMAIL,
  DELIVERY_SETTING_KEY_SENDER_LABEL,
  DELIVERY_SETTING_KEY_SENDER_REPLY_TO,
  DELIVERY_SETTING_KEY_SOURCE_ACCOUNT_IDENTIFIER,
  DELIVERY_SETTING_KEY_SENDER_MOB_NUM,
  TEST_ID_DELIVERY_SETTINGS_EDIT,
} from "./constants";
import "./DeliverySettings.scss";

const DeliverySettings = (props) => {
  const {
    channel,
    deliverySettings = {},
    senderDetailsOptions = [],
    wecrmAccounts = [],
    onSaveDeliverySettings,
    isLoadingSenderDetails,
    formatMessage,
    smsTraiDltEnabled,
    registeredSenderIds,
    whatsappAccountFromForm,
  } = props;

  const [isSlideBoxOpen, setSlideBoxOpen] = useState(false);

  const openSlideBox = useCallback(() => setSlideBoxOpen(true), []);
  const closeSlideBox = useCallback(() => setSlideBoxOpen(false), []);

  const handleSave = useCallback(
    (values) => {
      onSaveDeliverySettings(values);
      closeSlideBox();
    },
    [onSaveDeliverySettings, closeSlideBox]
  );

  if (!CHANNELS_WITH_DELIVERY_SETTINGS.includes(channel)) {
    return null;
  }

  const notConfiguredLabel = formatMessage(messages.notConfigured);

  const getSummaryText = () => {
    const empty = SUMMARY_EMPTY_PLACEHOLDER;
    if (channel === CHANNELS.SMS) {
      const domain = (senderDetailsOptions || []).find(
        (d) => d.domainId === get(deliverySettings, DELIVERY_SETTING_KEY_DOMAIN_ID),
      );
      const domainName = domain?.domainName || empty;
      const senderId = get(deliverySettings, DELIVERY_SETTING_KEY_GSM_SENDER_ID) || empty;
      return { senderDomain: domainName, senderId };
    }
    if (channel === CHANNELS.EMAIL) {
      const domain = (senderDetailsOptions || []).find(
        (d) => d.domainId === get(deliverySettings, DELIVERY_SETTING_KEY_DOMAIN_ID),
      );
      const emailDomain = domain?.domainName || empty;
      const senderEmail = get(deliverySettings, DELIVERY_SETTING_KEY_SENDER_EMAIL) || empty;
      const senderLabel = get(deliverySettings, DELIVERY_SETTING_KEY_SENDER_LABEL) || empty;
      const replyToId = get(deliverySettings, DELIVERY_SETTING_KEY_SENDER_REPLY_TO) || empty;
      return {
        emailDomain,
        senderEmail,
        senderLabel,
        replyToId,
      };
    }
    if (channel === CHANNELS.WHATSAPP) {
      const account = (wecrmAccounts || []).find(
        (a) => a.sourceAccountIdentifier
          === get(deliverySettings, DELIVERY_SETTING_KEY_SOURCE_ACCOUNT_IDENTIFIER),
      );
      const accountName = account?.name || empty;
      const senderNumber = get(deliverySettings, DELIVERY_SETTING_KEY_SENDER_MOB_NUM) || empty;
      return { account: accountName, senderNumber };
    }
    return { account: empty, sender: empty };
  };

  const summary = getSummaryText();
  let hasValues = false;
  if (channel === CHANNELS.SMS) {
    hasValues = summary.senderDomain !== SUMMARY_EMPTY_PLACEHOLDER
      || summary.senderId !== SUMMARY_EMPTY_PLACEHOLDER;
  } else if (channel === CHANNELS.EMAIL) {
    hasValues = summary.emailDomain !== SUMMARY_EMPTY_PLACEHOLDER
      || summary.senderEmail !== SUMMARY_EMPTY_PLACEHOLDER
      || summary.senderLabel !== SUMMARY_EMPTY_PLACEHOLDER
      || summary.replyToId !== SUMMARY_EMPTY_PLACEHOLDER;
  } else if (channel === CHANNELS.WHATSAPP) {
    hasValues = summary.account !== SUMMARY_EMPTY_PLACEHOLDER
      || summary.senderNumber !== SUMMARY_EMPTY_PLACEHOLDER;
  } else {
    hasValues = summary.account !== SUMMARY_EMPTY_PLACEHOLDER
      || summary.sender !== SUMMARY_EMPTY_PLACEHOLDER;
  }

  const getSummaryObject = () => {
    if (!hasValues) return null;
    const label = (msg) => formatMessage(msg);
    if (channel === CHANNELS.SMS) {
      return {
        [label(messages.senderDomainSummary)]: summary.senderDomain,
        [label(messages.senderId)]: summary.senderId,
      };
    }
    if (channel === CHANNELS.EMAIL) {
      return {
        [label(messages.emailDomain)]: summary.emailDomain,
        [label(messages.senderId)]: summary.senderEmail,
        [label(messages.senderName)]: summary.senderLabel,
        [label(messages.replyToId)]: summary.replyToId,
      };
    }
    if (channel === CHANNELS.WHATSAPP) {
      return {
        [label(messages.account)]: summary.account,
        [label(messages.senderNumber)]: summary.senderNumber,
      };
    }
    return {
      [label(messages.account)]: summary.account,
      [label(messages.senderNumber)]: summary.sender,
    };
  };

  const summaryObject = getSummaryObject();

  return (
    <CapRow useLegacy className="delivery-settings">
      <CapRow className="delivery-settings__heading-row">
        <CapHeading type="h10">
          <FormattedMessage {...messages.deliverySettings} />
        </CapHeading>
      </CapRow>
      <CapRow type="flex" className="delivery-settings__summary-row">
        <CapRow type="flex" className="delivery-settings__summary-inner">
          {summaryObject == null ? (
            <CapLabel type="label2">{notConfiguredLabel}</CapLabel>
          ) : (
            Object.entries(summaryObject).map(([key, value]) => (
              <CapRow type="flex" key={key} className="delivery-settings__summary-entry">
                <CapLabel type="label1" className="delivery-settings__summary-key">{key}</CapLabel>
                <CapLabel type="label9">
                  :
                  {' '}
                  {value}
                </CapLabel>
              </CapRow>
            ))
          )}
        </CapRow>
        <CapIcon
          type="edit"
          onClick={openSlideBox}
          className="delivery-settings__edit-icon"
          data-testid={TEST_ID_DELIVERY_SETTINGS_EDIT}
          size="s"
        />
      </CapRow>

      {isSlideBoxOpen && (
        <CapSlideBox
          show
          size="size-l"
          header={<FormattedMessage {...messages.deliverySettings} />}
          handleClose={closeSlideBox}
          content={(
            <ModifyDeliverySettings
              channel={channel}
              deliverySettings={deliverySettings}
              senderDetailsOptions={senderDetailsOptions}
              wecrmAccounts={wecrmAccounts}
              onSaveDeliverySettings={handleSave}
              onClose={closeSlideBox}
              isLoading={isLoadingSenderDetails}
              formatMessage={formatMessage}
              smsTraiDltEnabled={smsTraiDltEnabled}
              registeredSenderIds={registeredSenderIds}
              whatsappAccountFromForm={whatsappAccountFromForm}
            />
          )}
        />
      )}
    </CapRow>
  );
};

DeliverySettings.propTypes = {
  channel: PropTypes.string.isRequired,
  deliverySettings: PropTypes.object,
  senderDetailsOptions: PropTypes.array,
  wecrmAccounts: PropTypes.array,
  onSaveDeliverySettings: PropTypes.func.isRequired,
  isLoadingSenderDetails: PropTypes.bool,
  formatMessage: PropTypes.func,
  smsTraiDltEnabled: PropTypes.bool,
  registeredSenderIds: PropTypes.array,
  whatsappAccountFromForm: PropTypes.shape({
    accountName: PropTypes.string,
  }),
};

DeliverySettings.defaultProps = {
  deliverySettings: {},
  senderDetailsOptions: [],
  wecrmAccounts: [],
  isLoadingSenderDetails: false,
  formatMessage: undefined,
  smsTraiDltEnabled: false,
  registeredSenderIds: [],
  whatsappAccountFromForm: undefined,
};

export default DeliverySettings;
