/**
 * Tests for DeliverySettings component (sender ID / delivery settings summary + slidebox)
 * @jest-environment jsdom
 */

import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { IntlProvider } from 'react-intl';
import DeliverySettings from '../../DeliverySettings';
import { CHANNELS } from '../../constants';

jest.mock('../../DeliverySettings/DeliverySettings.scss', () => ({}));

// Mock subpath imports (used by DeliverySettings/index.js and ModifyDeliverySettings.js)
jest.mock('@capillarytech/cap-ui-library/CapRow', () => ({ children, className, ...rest }) => <div className={className} data-testid="cap-row" {...rest}>{children}</div>);
jest.mock('@capillarytech/cap-ui-library/CapHeading', () => ({ children }) => <div data-testid="cap-heading">{children}</div>);
jest.mock('@capillarytech/cap-ui-library/CapIcon', () => ({ onClick, className, 'data-testid': testId }) => <button type="button" onClick={onClick} className={className} data-testid={testId || 'cap-icon'} aria-label="edit" />);
jest.mock('@capillarytech/cap-ui-library/CapLabel', () => ({ children, type }) => <span data-type={type}>{children}</span>);
jest.mock('@capillarytech/cap-ui-library/CapSlideBox', () => ({ show, content, handleClose }) => (show ? (
  <div data-testid="cap-slidebox">
    <button type="button" onClick={handleClose} data-testid="slidebox-close">Close</button>
    {content}
  </div>
) : null));

const mockModifyDeliverySettings = jest.fn();
jest.mock('../../DeliverySettings/ModifyDeliverySettings', () => function MockModifyDeliverySettings(props) {
  mockModifyDeliverySettings(props);
  return (
    <div data-testid="modify-delivery-settings">
      <button type="button" onClick={() => props.onSaveDeliverySettings({ domainId: 1 })} data-testid="modify-done">Done</button>
      <button type="button" onClick={props.onClose} data-testid="modify-close">Cancel</button>
    </div>
  );
});

const defaultFormatMessage = (msg) => msg?.defaultMessage || msg?.id || '';

describe('DeliverySettings', () => {
  const defaultProps = {
    channel: CHANNELS.SMS,
    deliverySettings: {},
    senderDetailsOptions: [],
    wecrmAccounts: [],
    onSaveDeliverySettings: jest.fn(),
    isLoadingSenderDetails: false,
    formatMessage: defaultFormatMessage,
    smsTraiDltEnabled: false,
    registeredSenderIds: [],
    whatsappAccountFromForm: undefined,
  };

  beforeEach(() => {
    jest.clearAllMocks();
  });

  describe('channel visibility', () => {
    it('should return null when channel is not in CHANNELS_WITH_DELIVERY_SETTINGS', () => {
      const { container } = render(
        <DeliverySettings {...defaultProps} channel="INAPP" />
      );
      expect(container.firstChild).toBeNull();
    });

    it('should render when channel is SMS', () => {
      render(<DeliverySettings {...defaultProps} channel={CHANNELS.SMS} />);
      expect(screen.getByTestId('cap-heading')).toBeTruthy();
    });

    it('should render when channel is EMAIL', () => {
      render(<DeliverySettings {...defaultProps} channel={CHANNELS.EMAIL} />);
      expect(screen.getByTestId('cap-heading')).toBeTruthy();
    });

    it('should render when channel is WHATSAPP', () => {
      render(<DeliverySettings {...defaultProps} channel={CHANNELS.WHATSAPP} />);
      expect(screen.getByTestId('cap-heading')).toBeTruthy();
    });
  });

  describe('summary display', () => {
    it('should show not configured when no delivery values for SMS', () => {
      render(<DeliverySettings {...defaultProps} channel={CHANNELS.SMS} />);
      expect(screen.getByText('Not configured')).toBeTruthy();
    });

    it('should show summary values for SMS when deliverySettings and senderDetailsOptions match', () => {
      const senderDetailsOptions = [{ domainId: 1, domainName: 'SMS Domain' }];
      const deliverySettings = { domainId: 1, gsmSenderId: 'SENDER1' };
      render(
        <DeliverySettings
          {...defaultProps}
          channel={CHANNELS.SMS}
          deliverySettings={deliverySettings}
          senderDetailsOptions={senderDetailsOptions}
        />
      );
      expect(screen.getAllByText(/SMS Domain/).length).toBeGreaterThan(0);
      expect(screen.getAllByText(/SENDER1/).length).toBeGreaterThan(0);
    });

    it('should show not configured for EMAIL when empty', () => {
      render(<DeliverySettings {...defaultProps} channel={CHANNELS.EMAIL} />);
      expect(screen.getByText('Not configured')).toBeTruthy();
    });

    it('should show summary for EMAIL when has domain and sender', () => {
      const senderDetailsOptions = [{ domainId: 2, domainName: 'Email Domain' }];
      const deliverySettings = {
        domainId: 2,
        senderEmail: 'noreply@test.com',
        senderLabel: 'Test',
        senderReplyTo: 'reply@test.com',
      };
      render(
        <DeliverySettings
          {...defaultProps}
          channel={CHANNELS.EMAIL}
          deliverySettings={deliverySettings}
          senderDetailsOptions={senderDetailsOptions}
        />
      );
      expect(screen.getAllByText(/Email Domain/).length).toBeGreaterThan(0);
      expect(screen.getAllByText(/noreply@test\.com/).length).toBeGreaterThan(0);
    });

    it('should show summary for WHATSAPP when has account and sender', () => {
      const wecrmAccounts = [{ name: 'WABA One', sourceAccountIdentifier: 'waba-1' }];
      const deliverySettings = {
        sourceAccountIdentifier: 'waba-1',
        senderMobNum: '+1234567890',
      };
      render(
        <DeliverySettings
          {...defaultProps}
          channel={CHANNELS.WHATSAPP}
          deliverySettings={deliverySettings}
          wecrmAccounts={wecrmAccounts}
        />
      );
      expect(screen.getAllByText(/WABA One/).length).toBeGreaterThan(0);
      expect(screen.getAllByText(/\+1234567890/).length).toBeGreaterThan(0);
    });
  });

  describe('edit and slidebox', () => {
    it('should open slidebox when edit icon is clicked', () => {
      render(<DeliverySettings {...defaultProps} channel={CHANNELS.SMS} />);
      expect(screen.queryByTestId('cap-slidebox')).toBeNull();
      fireEvent.click(screen.getByTestId('delivery-settings-edit'));
      expect(screen.getByTestId('cap-slidebox')).toBeTruthy();
      expect(screen.getByTestId('modify-delivery-settings')).toBeTruthy();
    });

    it('should pass correct props to ModifyDeliverySettings', () => {
      render(<DeliverySettings {...defaultProps} channel={CHANNELS.SMS} />);
      fireEvent.click(screen.getByTestId('delivery-settings-edit'));
      expect(mockModifyDeliverySettings).toHaveBeenCalledWith(
        expect.objectContaining({
          channel: CHANNELS.SMS,
          deliverySettings: {},
          senderDetailsOptions: [],
          wecrmAccounts: [],
          isLoading: false,
          smsTraiDltEnabled: false,
          registeredSenderIds: [],
          whatsappAccountFromForm: undefined,
        })
      );
    });

    it('should call onSaveDeliverySettings and close slidebox when Done is clicked', () => {
      const onSave = jest.fn();
      render(
        <DeliverySettings
          {...defaultProps}
          channel={CHANNELS.SMS}
          onSaveDeliverySettings={onSave}
        />
      );
      fireEvent.click(screen.getByTestId('delivery-settings-edit'));
      fireEvent.click(screen.getByTestId('modify-done'));
      expect(onSave).toHaveBeenCalledWith({ domainId: 1 });
      expect(screen.queryByTestId('cap-slidebox')).toBeNull();
    });

    it('should pass whatsappAccountFromForm to ModifyDeliverySettings', () => {
      render(
        <DeliverySettings
          {...defaultProps}
          channel={CHANNELS.WHATSAPP}
          whatsappAccountFromForm={{ accountName: 'My WABA' }}
        />
      );
      fireEvent.click(screen.getByTestId('delivery-settings-edit'));
      expect(mockModifyDeliverySettings).toHaveBeenCalledWith(
        expect.objectContaining({
          whatsappAccountFromForm: { accountName: 'My WABA' },
        })
      );
    });

    it('should pass SMS TRAI props to ModifyDeliverySettings', () => {
      render(
        <DeliverySettings
          {...defaultProps}
          channel={CHANNELS.SMS}
          smsTraiDltEnabled
          registeredSenderIds={['HPCLTD']}
        />
      );
      fireEvent.click(screen.getByTestId('delivery-settings-edit'));
      expect(mockModifyDeliverySettings).toHaveBeenCalledWith(
        expect.objectContaining({
          smsTraiDltEnabled: true,
          registeredSenderIds: ['HPCLTD'],
        })
      );
    });
  });
});
