import {
  call, put, takeLatest, takeEvery, all, select, take,
} from 'redux-saga/effects';
import CapNotification from '@capillarytech/cap-ui-library/CapNotification';
import * as Api from '../../services/api';
import * as types from './constants';
import { transformEmailTemplates, storeS3FileSizeDetails } from '../../utils/cdnTransformation';

export function* createTemplate(template) {
  let errorMsg;
  try {
    const result = yield call(Api.createEmailTemplate, template);
    // Check if the API call failed (non-2xx status codes or explicit failure)
    const statusCode = result.status?.code || result.status;
    const isError = !result.success || statusCode >= 400;

    if (isError) {
      // Extract error message from various possible locations in the response
      errorMsg = result.message
                 || result.errorMessage
                 || result.error?.message
                 || (result.response && result.response.message)
                 || (result.status && result.status.message)
                 || (result.data && result.data.message)
                 || `API Error: ${statusCode || 'Unknown error'}`;
      // Show error notification directly from saga
      CapNotification.error({
        key: 'createTemplateError',
        message: errorMsg,
      });
      yield put({ type: types.CREATE_TEMPLATE_FAILURE, errorMsg });
      // Call callback with error so component can handle it (if needed)
      if (template.onCreateTemplateComplete) {
        try {
          // Call the callback directly (it's a regular function, not a generator)
          template.onCreateTemplateComplete({ error: true, message: errorMsg, statusCode });
        } catch (callbackError) {
          console.error('[Email Saga] Error executing callback:', callbackError);
        }
      }
    } else {
      yield put({
        type: types.CREATE_TEMPLATE_SUCCESS, data: result.response, statusCode: result.status ? result.status.code : '', errorMsg,
      });
      yield template.onCreateTemplateComplete(result.response);
    }
  } catch (error) {
    errorMsg = error.message || error.toString() || 'An unexpected error occurred';
    yield put({ type: types.CREATE_TEMPLATE_FAILURE, error, errorMsg });
    // Call callback with error so component can handle it
    if (template.onCreateTemplateComplete) {
      yield template.onCreateTemplateComplete({ error: true, message: errorMsg });
    }
  }
}

export function* transformEmailTemplate({template, callback}) {
  try {
    const result = yield call(transformEmailTemplates, template);
    yield callback(result);
  } catch (error) {
    yield callback(template);
  }
}

export function* duplicateTemplate(payload) {
  let errorMsg;
  let result;
  const { id, channel, callback } = payload;
  try {
    result = yield call(Api.duplicateTemplate, {id, channel} );
    if (result.status.code === 500) {
      errorMsg = result.message;
    }
    if (callback) {
      callback(result?.response);
    }
    yield put({
      type: types.DUPLICATE_TEMPLATE_SUCCESS, data: result?.response, statusCode: result?.status?.code, errorMsg,
    });
  } catch (error) {
    yield put({ type: types.DUPLICATE_TEMPLATE_FAILURE, error, errorMsg });
  }
}

export function* getTemplateDetails(id) {
  try {
    const result = yield call(Api.getTemplateDetails, id);
    // const sidebar = result.response.sidebar;
    yield put({ type: types.GET_TEMPLATE_DETAILS_SUCCESS, data: result.response });
  } catch (error) {
    yield put({ type: types.GET_TEMPLATE_DETAILS_FAILURE, error });
  }
}

export function* getAllAssets(assetType, queryParams) {
  try {
    const result = yield call(Api.getAllAssets, assetType, queryParams);
    yield put({ type: types.GET_ALL_ASSETS_SUCCESS, data: result?.response, isReset: assetType.queryParams.page === 1 });
  } catch (error) {
    yield put({ type: types.GET_ALL_ASSETS_FAILURE, error });
  }
}

export function* getCmsSetting({
  cmsType, projectId, cmsMode, langId, isEdmSupport, isBEEAppEnable: isBEEAppEnableFromAction,
}) {
  try {
    const emailState = yield select((state) => state.get('email'));
    if (!emailState.get('cmsAccountsLoaded') && emailState.get('fetchingCmsAccounts')) {
      yield take([types.GET_CMS_ACCOUNTS_SUCCESS, types.GET_CMS_ACCOUNTS_FAILURE]);
    }
    const updatedState = yield select((state) => state.get('email'));
    const isBEEAppEnable = updatedState.get('isBeeEnabled') ?? isBEEAppEnableFromAction;
    const result = yield call(Api.getCmsTemplateSettingsV2, cmsType, projectId, cmsMode, langId, isEdmSupport, isBEEAppEnable);
    const cmsAccountDetail = result.data?.response.cmsDetails || {};
    const isBeeEnabled = cmsAccountDetail?.type === cmsType;
    yield put({ type: types.GET_CMS_EDITOR_DETAILS_SUCCESS, settings: cmsAccountDetail, isBeeEnabled });
  } catch (error) {
    yield put({ type: types.GET_CMS_EDITOR_DETAILS_FAILURE, error });
  }
}

export function* getCmsData({cmsType, projectId, langId}) {
  try {
    const result = yield call(Api.getCmsTemplateDataV2, cmsType, projectId, langId);

    yield put({ type: types.GET_CMS_EDITOR_DATA_SUCCESS, data: result.data.response.data, langId: result.data.response.langId });
  } catch (error) {
    yield put({ type: types.GET_CMS_EDITOR_DATA_FAILURE, error });
  }
}

export function* getCmsAccounts({cmsType}) {
  try {
    const result = yield call(Api.getCmsAccounts, cmsType);
    const { cmsAccounts } = result.data?.response || {};
    const isBeeEnabled = cmsAccounts?.type === cmsType;
    yield put({ type: types.GET_CMS_ACCOUNTS_SUCCESS, isBeeEnabled });
  } catch (error) {
    yield put({ type: types.GET_CMS_ACCOUNTS_FAILURE, error });
  }
}

export function* uploadAsset(file, assetType, fileParams) {
  try {
    const result = yield call(Api.uploadFile, file, assetType, fileParams);
    const metaInfo = result?.response?.asset?.metaInfo;
    storeS3FileSizeDetails(metaInfo?.secure_file_path, metaInfo?.file_size);
    yield put({ type: types.UPLOAD_ASSET_SUCCESS, data: result.response.asset, statusCode: result.status ? result.status.code : '' });
  } catch (error) {
    yield put({ type: types.UPLOAD_ASSET_FAILURE, error });
  }
}

function* watchCreateTemplate() {
  yield takeLatest(types.CREATE_TEMPLATE_REQUEST, createTemplate);
}

export function* watchTransformEmailTemplate() {
  yield takeLatest(types.TRANSFORM_EMAIL_TEMPLATE_REQUEST, transformEmailTemplate);
}


function* watchGetTemplateDetails() {
  yield takeLatest(types.GET_TEMPLATE_DETAILS_REQUEST, getTemplateDetails);
}

function* watchGetAllAssets() {
  yield takeLatest(types.GET_ALL_ASSETS_REQUEST, getAllAssets);
}

function* watchGetCmsSetting() {
  yield takeEvery(types.GET_CMS_EDITOR_DETAILS_REQUEST, getCmsSetting);
}

function* watchGetCmsData() {
  yield takeEvery(types.GET_CMS_EDITOR_DATA_REQUEST, getCmsData);
}

function* watchGetCmsAccounts() {
  yield takeEvery(types.GET_CMS_ACCOUNTS_REQUEST, getCmsAccounts);
}

function* watchUploadAsset() {
  yield takeLatest(types.UPLOAD_ASSET_REQUEST, uploadAsset);
}

function* watchDuplicateTemplate() {
  yield takeLatest(types.DUPLICATE_TEMPLATE_REQUEST, duplicateTemplate);
}

// All sagas to be loaded
export default [
  watchCreateTemplate,
  watchTransformEmailTemplate,
  watchGetTemplateDetails,
  watchGetAllAssets,
  watchGetCmsSetting,
  watchGetCmsData,
  watchGetCmsAccounts,
  watchUploadAsset,
  watchDuplicateTemplate,
];

export function* v2EmailSagas() {
  yield all([
    watchCreateTemplate(),
    watchTransformEmailTemplate(),
    watchGetTemplateDetails(),
    watchGetAllAssets(),
    watchGetCmsSetting(),
    watchGetCmsData(),
    watchGetCmsAccounts(),
    watchUploadAsset(),
  ]);
}

export function* v2EmailDuplicateTemplateSaga() {
  yield all([
    watchDuplicateTemplate(),
  ]);
}
