/**
 * DeliverySettingsSection Component
 *
 * Self-contained delivery settings section shown below content when configured.
 * Fetches domainProperties, displays sender ID/number, opens slidebox on click.
 * Integrated into ChannelSelectionStep (similar to how steps are integrated in CommunicationFlow).
 */

import React, {
  useState, useMemo, useEffect, useRef, useCallback,
} from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';
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 SenderDetails, { parseSenderDetailsFromEntity } from './SenderDetails';
import {
  buildChannelSettingFromFieldValues,
  parseChannelSettingForDisplay,
  getWhatsappAccountName,
} from './deliverySettingsConfig';
import { getDomainProperties, fetchWeCrmAccounts } from '../../../../services/api';
import { loadItem } from '../../../../services/localStorageApi';
import { CHANNELS_WITHOUT_DELIVERY } from '../../constants';
import messages from '../../messages';
import './DeliverySettingsSection.scss';
import { WHATSAPP } from "../../../CreativesContainer/constants";

const DeliverySettingsSection = ({
  contentItems = [],
  deliverySettingsData,
  deliverySetting = {},
  onDeliverySettingChange,
  intl,
}) => {
  const [showSlidebox, setShowSlidebox] = useState(false);
  const [domainPropertiesData, setDomainPropertiesData] = useState(null);
  const [wecrmViberData, setWecrmViberData] = useState(null);
  const fetchInFlightRef = useRef(false);
  const lastChannelKeyRef = useRef('');
  const { formatMessage } = intl || {};

  // Channels from contentItems
  const contentChannels = useMemo(
    () => [...new Set(contentItems.map((contentItem) => (contentItem.channel || '')?.toUpperCase())?.filter(Boolean))],
    [contentItems],
  );

  // Channels that need delivery settings (exclude MPUSH, INAPP, WEBPUSH)
  const deliveryChannels = useMemo(
    () => contentChannels.filter((channel) => !CHANNELS_WITHOUT_DELIVERY.includes(channel)),
    [contentChannels],
  );

  // Hide section when all configured channels are MPUSH, INAPP, WEBPUSH
  const shouldShow = useMemo(() => {
    if (contentChannels.length === 0) return false;
    return contentChannels.some((channel) => !CHANNELS_WITHOUT_DELIVERY.includes(channel));
  }, [contentChannels]);

  // Extract WhatsApp sourceAccountIdentifier from contentItems (set by Whatsapp/index.js when template is created)
  const whatsappSourceAccountId = useMemo(() => {
    const waContentItem = contentItems.find((contentItem) => (contentItem.channel)?.toUpperCase() === WHATSAPP);
    return waContentItem?.templateData?.sourceAccountIdentifier || '';
  }, [contentItems]);

  // Extract WhatsApp account name from contentItems (set by Whatsapp/index.js)
  const whatsappAccNameFromContent = useMemo(() => {
    const waContentItem = contentItems.find((contentItem) => (contentItem.channel)?.toUpperCase() === WHATSAPP);
    return waContentItem?.templateData?.accountName || '';
  }, [contentItems]);

  // Stable key for deduplication - avoid re-fetch when array reference changes
  const deliveryChannelKey = deliveryChannels.slice().sort().join(',');
  const deliveryEnabled = !!deliverySettingsData;
  // Fetch domainProperties when content is configured (single source, deduplicated)
  useEffect(() => {
    if (!deliveryEnabled || deliveryChannels.length === 0) {
      setDomainPropertiesData(null);
      lastChannelKeyRef.current = '';
      return undefined;
    }
    if (lastChannelKeyRef.current === deliveryChannelKey && domainPropertiesData) {
      return undefined;
    }
    if (fetchInFlightRef.current) return undefined;
    fetchInFlightRef.current = true;
    lastChannelKeyRef.current = deliveryChannelKey;
    let cancelled = false;
    const fetchData = async () => {
      try {
        const orgUnitId = loadItem('ouId') || loadItem('orgID');
        const response = await getDomainProperties(deliveryChannels, orgUnitId);
        if (!cancelled) {
          const raw = response?.entity || response;
          // Normalize channel keys to uppercase (API may return Viber, viber, etc.)
          const entity = raw && typeof raw === 'object'
            ? Object.fromEntries(
              Object.entries(raw).map(([channelKey, channelData]) => [String(channelKey)?.toUpperCase(), channelData]),
            )
            : raw;
          setDomainPropertiesData(entity);
        }
      } catch (err) {
        if (!cancelled) setDomainPropertiesData(null);
      } finally {
        if (!cancelled) fetchInFlightRef.current = false;
      }
    };
    fetchData();
    return function cleanup() {
      cancelled = true;
      // Do NOT reset fetchInFlightRef here - it would allow duplicate fetches when effect re-runs.
      // fetchInFlightRef is reset in finally when the fetch completes.
    };
  }, [deliveryEnabled, deliveryChannelKey]); // eslint-disable-line react-hooks/exhaustive-deps

  // Fetch WeCRM accounts for VIBER when domainProperties has empty contactInfo
  const needsWecrmViber = deliveryChannels.includes('VIBER');
  useEffect(() => {
    if (!needsWecrmViber) {
      setWecrmViberData(null);
      return undefined;
    }
    let cancelled = false;
    const fetchWecrm = async () => {
      try {
        const res = await fetchWeCrmAccounts('VIBER');
        if (!cancelled && res?.response) {
          setWecrmViberData(Array.isArray(res.response) ? res.response : [res.response]);
        } else if (!cancelled) {
          setWecrmViberData(null);
        }
      } catch {
        if (!cancelled) setWecrmViberData(null);
      }
    };
    fetchWecrm();
    return () => { cancelled = true; };
  }, [needsWecrmViber]);

  // Merge WeCRM sender options into entity when VIBER domains have empty contactInfo
  const entityWithWecrmViber = useMemo(() => {
    if (!domainPropertiesData || !wecrmViberData?.length) return domainPropertiesData;
    const viberArr = domainPropertiesData.VIBER;
    if (!Array.isArray(viberArr) || viberArr.length === 0) return domainPropertiesData;
    const hasContactInfo = viberArr.some((domain) => (domain?.domainProperties?.contactInfo?.length ?? 0) > 0);
    if (hasContactInfo) return domainPropertiesData;
    const syntheticContactInfo = wecrmViberData
      ?.filter((account) => account?.isActive !== false)
      ?.map((account, index) => ({
        type: 'viber_sender_id',
        value: account?.sourceAccountIdentifier,
        label: account?.name || account?.configs?.viber_account_name || account?.sourceAccountIdentifier,
        valid: true,
        default: index === 0,
      }));
    if (syntheticContactInfo?.length === 0) return domainPropertiesData;
    const merged = { ...domainPropertiesData };
    merged.VIBER = viberArr?.map((domain, index) => {
      if (index === 0) {
        return {
          ...domain,
          domainProperties: {
            ...(domain?.domainProperties || {}),
            contactInfo: [...(domain?.domainProperties?.contactInfo || []), ...syntheticContactInfo],
          },
        };
      }
      return domain;
    });
    return merged;
  }, [domainPropertiesData, wecrmViberData]);

  const parsedSenderDetails = useMemo(() => {
    if (!entityWithWecrmViber) return null;
    const fromEntity = parseSenderDetailsFromEntity(entityWithWecrmViber, { whatsappSourceAccountId });
    const fromSaved = parseChannelSettingForDisplay(deliverySetting?.channelSetting);
    // Derive WhatsApp account name: from entity domain or from content templateData
    const waAccountName = whatsappAccNameFromContent
      || getWhatsappAccountName(entityWithWecrmViber, whatsappSourceAccountId);
    return { ...fromEntity, ...fromSaved, whatsappAccountName: waAccountName || fromEntity.whatsappAccountName };
  }, [entityWithWecrmViber, deliverySetting, whatsappSourceAccountId, whatsappAccNameFromContent]);

  // Map channel -> { labelKey, valueKey } or array of { labelKey, valueKey } for summary display
  // SMS, RCS, EMAIL, VIBER: Sender ID | WHATSAPP: Sender number | LINE: Account
  const channelDisplayMap = {
    SMS: { labelKey: 'senderIdLabel', valueKey: 'smsSenderId' },
    EMAIL: { labelKey: 'senderIdLabel', valueKey: 'emailSenderId' },
    VIBER: { labelKey: 'senderIdLabel', valueKey: 'viberSenderId' },
    ZALO: { labelKey: 'senderIdLabel', valueKey: 'zaloSenderId' },
    LINE: { labelKey: 'accountLabel', valueKey: 'lineSenderId' },
    WHATSAPP: [
      { labelKey: 'senderNumberLabel', valueKey: 'whatsappSenderNumber' },
    ],
    RCS: { labelKey: 'senderNumberLabel', valueKey: 'rcsSenderNumber' },
  };

  const handleDeliverySettingSave = useCallback((fieldValues) => {
    if (!onDeliverySettingChange) return;
    onDeliverySettingChange({
      ...deliverySetting,
      channelSetting: {
        ...(deliverySetting?.channelSetting || {}),
        ...buildChannelSettingFromFieldValues(fieldValues),
      },
    });
  }, [onDeliverySettingChange, deliverySetting]);

  if (!deliverySettingsData || !shouldShow) {
    return null;
  }

  return (
    <>
      <CapRow
        type="flex"
        align="middle"
        justify="space-between"
        className="delivery-settings-section delivery-settings-section--clickable"
        onClick={() => setShowSlidebox(true)}
      >
        <CapRow type="flex" className="delivery-settings-section__content">
          <CapHeading type="h5">
            {formatMessage(messages.senderDetails)}
          </CapHeading>
          {deliveryChannels?.flatMap((channel) => {
            const config = channelDisplayMap[channel];
            if (!config || !parsedSenderDetails) return [];
            const configs = Array.isArray(config) ? config : [config];
            return configs
              .filter((channelConfig) => {
                const value = parsedSenderDetails[channelConfig.valueKey];
                return value != null && value !== '';
              })
              .map((channelConfig) => (
                <CapRow key={`${channel}-${channelConfig.valueKey}`} type="flex" align="middle" justify="space-between" className="delivery-settings-section__field-row">
                  <CapHeading type="label4" className="delivery-settings-section__label">
                    {formatMessage(messages[channelConfig.labelKey])}
                  </CapHeading>
                  <CapLabel type="label9" className="delivery-settings-section__value" title={parsedSenderDetails[channelConfig.valueKey]}>
                    {parsedSenderDetails[channelConfig.valueKey]}
                  </CapLabel>
                </CapRow>
              ));
          })}
        </CapRow>
        <CapIcon
          type="chevron-right"
          size="s"
          className="delivery-settings-section__chevron"
          aria-label="Open delivery settings details"
        />
      </CapRow>

      {showSlidebox && (
        <SenderDetails
          show={showSlidebox}
          onClose={() => setShowSlidebox(false)}
          channels={deliveryChannels}
          preloadedDomainProperties={entityWithWecrmViber}
          savedFieldValues={parseChannelSettingForDisplay(deliverySetting?.channelSetting)}
          whatsappSourceAccountId={whatsappSourceAccountId}
          whatsappAccountName={whatsappAccNameFromContent || getWhatsappAccountName(entityWithWecrmViber, whatsappSourceAccountId)}
          onSave={handleDeliverySettingSave}
        />
      )}
    </>
  );
};

DeliverySettingsSection.propTypes = {
  contentItems: PropTypes.arrayOf(PropTypes.object),
  deliverySettingsData: PropTypes.object,
  deliverySetting: PropTypes.object,
  onDeliverySettingChange: PropTypes.func,
  intl: PropTypes.object.isRequired,
};

DeliverySettingsSection.defaultProps = {
  contentItems: [],
  deliverySettingsData: null,
  deliverySetting: null,
  onDeliverySettingChange: null,
};

export default injectIntl(DeliverySettingsSection);
