/* eslint-disable no-trailing-spaces */
/* eslint-disable guard-for-in */
/* eslint-disable no-loop-func */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-undef */
import PropTypes from 'prop-types';
import React, { useState, useEffect } from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import styled from 'styled-components';
import Dropzone from 'react-dropzone';
import { bindActionCreators } from 'redux';
import CapDivider from '@capillarytech/cap-ui-library/CapDivider';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapColumn from '@capillarytech/cap-ui-library/CapColumn';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import CapError from '@capillarytech/cap-ui-library/CapError';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import CapNotification from '@capillarytech/cap-ui-library/CapNotification';
import Papa from 'papaparse';
import { cloneDeep, isEmpty } from 'lodash';
import {
  CAP_SPACE_16,
  CAP_SPACE_24,
  CAP_SPACE_32,
  CAP_WHITE,
  CAP_RED01,
  CAP_PRIMARY,
} from '@capillarytech/cap-ui-library/styled/variables';
import './index.scss';
import makeSelectSmsTrai from './selectors';
import dragdropImage from '../../../assets/group.png';
import * as smsTraiActions from './actions';
import {
  MANDATORY_COLUMNS,
  HEADER_ALIASES,
  SAMPLE_CSV_DATA,
  DOWNLOAD_ISSUES_CSV,
  SAMPLE_CSV,
  CAPILLARY_REJECTION_REASON,
  APPROVED,
  ACTIVE,
  REGISTERED,
  TEMPLATE_NAME,
  TEMPLATE_ID_ALIASES,
  TEMPLATE_MESSAGE_ALIASES,
  STATUS_ALIASES,
  TYPE_ALIASES,
  SAVED_COLUMNS,
  MAPPED_SAVED_COLUMN,
  SMS,
  FAILURE,
  SUCCESS,
  DUPLICATE,
} from './constants';
import messages from './messages';
import withCreatives from '../../../hoc/withCreatives';
import injectSaga from '../../../utils/injectSaga';
import injectReducer from '../../../utils/injectReducer';
import { v2SmsTraiCreateSagas } from './sagas';
import v2SmsTraiCreateReducer from './reducer';

export const SmsTraiCreate = (props) => {
  const {
    intl,
    actions,
    onCreateComplete,
    isFullMode,
    onShowTemplates,
    traiSms: {
      duplicateDetails = {},
      duplicateDetailsError = '',
      duplicateDetailsStatus = '',
    } = {},
  } = props;
  const { formatMessage } = intl;
  const [traiFileData, setTraiFileData] = useState({});
  const [traiFileMeta, setTraiFileMeta] = useState(null);
  const [validatedData, setValidatedData] = useState([]);
  const [files, setFiles] = useState([]);
  const [templateRegistrationIndex, setTemplateRegistrationIndex] =
    useState(null);
  const [errorText, setErrorText] = useState('');
  const [dropZone, setDropZone] = useState(true);
  const [previewFileIndex, setPreviewFileIndex] = useState(null);
  const [isFileDropped, setIsFileDropped] = useState(false);
  const [totalFailCount, setTotalFailCount] = useState(0);
  const [saveTemplate, updateSaveTemplate] = useState(false);
  const [uploadValidated, setUploadValidated] = useState(false);

  const SMSTraiFooter = styled.div`
    background-color: ${CAP_WHITE};
    position: fixed;
    bottom: 0;
    width: 100%;
    margin-left: -32px;
    padding: ${CAP_SPACE_32} ${CAP_SPACE_24};
    .ant-btn {
      margin-right: ${CAP_SPACE_16};
    }
    }
`;
  useEffect(() => {
    if (!isEmpty(traiFileData) && traiFileMeta?.name) {
      if (traiFileMeta?.name?.split('.').pop() === 'csv') {
        const mandatoryColNotPresent = [];
        const headerAliasPresent = [];
        const templateIdAliasPresent = [];
        const templateMessageAliasPresent = [];
        const statusAliasPresent = [];
        const typeAliasPresent = [];
        const colCounts = {};
        const traiFileDataCopy = cloneDeep(traiFileData);
        //removing last empty row if each cell is empty
        const removeLastEmptyRow = traiFileDataCopy?.data[
          traiFileDataCopy?.data?.length - 1
        ]?.every((cell) => !cell);
        if (removeLastEmptyRow) {
          traiFileDataCopy.data.pop();
        }
        const fileLen = traiFileDataCopy?.data?.length || 0;
        // at least 1 records should be available
        if (fileLen < 2) {
          setErrorText(formatMessage(messages.fileMinlengthError));
          return;
        }
        // more then 500 records are not available.
        if (fileLen > 501) {
          setErrorText(formatMessage(messages.fileMaxlengthError));
          return;
        }

        const cols = getAllColumnNames(traiFileDataCopy.data[0]);

        for (let i = 0; i < MANDATORY_COLUMNS.length; i += 1) {
          if (!cols.includes(MANDATORY_COLUMNS[i])) {
            mandatoryColNotPresent.push(MANDATORY_COLUMNS[i]);
          }
        }
        if (mandatoryColNotPresent.length > 0) {
          setErrorText(formatMessage(messages.mandatoryColErrorDescription));
          return;
        }

        //one of the mandatory header alias should be available.
        for (let i = 0; i < HEADER_ALIASES.length; i += 1) {
          if (cols.includes(HEADER_ALIASES[i])) {
            headerAliasPresent.push(HEADER_ALIASES[i]);
          }
        }
        if (headerAliasPresent.length === 0) {
          setErrorText(
            formatMessage(messages.headerAliasErrorDescription, {
              headerAliases: HEADER_ALIASES.join(' / '),
            }),
          );
          return;
        }
        //one of the mandatory template id alias should be available.
        for (let i = 0; i < TEMPLATE_ID_ALIASES.length; i += 1) {
          if (cols.includes(TEMPLATE_ID_ALIASES[i])) {
            templateIdAliasPresent.push(TEMPLATE_ID_ALIASES[i]);
          }
        }
        if (templateIdAliasPresent.length === 0) {
          setErrorText(
            formatMessage(messages.templateIdAliasErrorDescription, {
              templateIdAliases: TEMPLATE_ID_ALIASES.join(' / '),
            }),
          );
          return;
        }
        //one of the mandatory template message alias should be available.
        for (let i = 0; i < TEMPLATE_MESSAGE_ALIASES.length; i += 1) {
          if (cols.includes(TEMPLATE_MESSAGE_ALIASES[i])) {
            templateMessageAliasPresent.push(TEMPLATE_MESSAGE_ALIASES[i]);
          }
        }
        if (templateMessageAliasPresent.length === 0) {
          setErrorText(
            formatMessage(messages.templateMessageAliasErrorDescription, {
              templateMessageAliases: TEMPLATE_MESSAGE_ALIASES.join(' / '),
            }),
          );
          return;
        }
        //one of the mandatory status alias should be available.
        for (let i = 0; i < STATUS_ALIASES.length; i += 1) {
          if (cols.includes(STATUS_ALIASES[i])) {
            statusAliasPresent.push(STATUS_ALIASES[i]);
          }
        }
        if (statusAliasPresent.length === 0) {
          setErrorText(
            formatMessage(messages.statusAliasErrorDescription, {
              statusAliases: STATUS_ALIASES.join(' / '),
            }),
          );
          return;
        }
        //one of the mandatory type alias should be available.
        for (let i = 0; i < TYPE_ALIASES.length; i += 1) {
          if (cols.includes(TYPE_ALIASES[i])) {
            typeAliasPresent.push(TYPE_ALIASES[i]);
          }
        }
        if (typeAliasPresent.length === 0) {
          setErrorText(
            formatMessage(messages.typeAliasErrorDescription, {
              typeAliases: TYPE_ALIASES.join(' / '),
            }),
          );
          return;
        }
        // count of each col to validate repetitive cols
        for (const num of cols) {
          colCounts[num] = colCounts[num] ? colCounts[num] + 1 : 1;
        }

        const repetitiveColsArray = Object.keys(
          Object.fromEntries(
            Object.entries(colCounts).filter(
              ([key, value]) => key !== '' && value > 1,
            ),
          ),
        );
        //throw validation if repetitive columns present
        if (repetitiveColsArray.length !== 0) {
          setErrorText(
            formatMessage(messages.repetitiveColsErrorDescription, {
              repetitiveCols: repetitiveColsArray.join(', '),
            }),
          );
          return;
        }
        //perform required data transformation
        dataTransformHandler(
          cols,
          traiFileDataCopy,
          headerAliasPresent,
          templateIdAliasPresent,
          statusAliasPresent,
        );
      } else {
        setErrorText(formatMessage(messages.nonCsvErrorDescription));
      }
    }
  }, [traiFileData, traiFileMeta]);

  useEffect(() => {
    const { count = 0, template_ids = [] } = duplicateDetails || {};

    if (errorText && !uploadValidated) {
      setIsFileDropped(false); // Stop the spinner
      const selectedFiles = cloneDeep(files);
      selectedFiles.push({
        fileMeta: traiFileMeta,
        fileData: traiFileData,
        columnMapping: [],
      });
      setFiles(selectedFiles);
      setPreviewFileIndex(selectedFiles.length - 1);
      setDropZone(false);
    } else if (uploadValidated && duplicateDetailsStatus === FAILURE) {
      deleteOrCancelCSV();
      CapNotification.error({ message: duplicateDetailsError || FAILURE });
    } else if (
      uploadValidated &&
      duplicateDetailsStatus === SUCCESS &&
      !isEmpty(validatedData)
    ) {
      if (
        !isEmpty(duplicateDetails) &&
        count > 0 &&
        templateRegistrationIndex !== null
      ) {
        const clonedValidatedData = cloneDeep(validatedData);
        let duplicateTemplateNameCounts = 0;
        const apiResponseIds = [...new Set(template_ids)];

        for (let i = 1; i < clonedValidatedData.length; i += 1) {
          const duplicatePresent = apiResponseIds?.includes(
            clonedValidatedData[i][templateRegistrationIndex]?.replace(
              /[“”"'‘’`´]/g,
              '',
            ),
          );
          if (duplicatePresent) {
            //if rejection reason for this row is empty, consider as new error
            if (!clonedValidatedData[i][clonedValidatedData[i]?.length - 1]) {
              duplicateTemplateNameCounts += 1;
            }
            //add rejection reason to rejection reason column
            clonedValidatedData[i][
              clonedValidatedData[i]?.length - 1
            ] += ` This template name is already present in the database.Duplicate template names are not allowed.`;
          }
        } //Duplicate should match constant DUPLICATE
        setTotalFailCount((prev) => prev + duplicateTemplateNameCounts);
        setValidatedData(clonedValidatedData);
      }
      updateSaveTemplate(true);
    }
  }, [duplicateDetailsStatus, errorText, templateRegistrationIndex]);

  useEffect(() => {
    if (saveTemplate && !isEmpty(traiFileData) && !isEmpty(validatedData)) {
      setIsFileDropped(false); // Stop the spinner
      const selectedFiles = cloneDeep(files);
      const traiFileDataCopy = cloneDeep(traiFileData);
      //removing last empty row if each cell is empty
      const removeLastEmptyRow = traiFileDataCopy?.data[
        traiFileDataCopy?.data?.length - 1
      ]?.every((cell) => !cell);
      if (removeLastEmptyRow) {
        traiFileDataCopy.data.pop();
      }
      //remove capillary rejection reason column if already present on reupload
      //ex: user reuploads a csv which was earlier validated and rejection reasons were added for failed templates
      const rejectionIndex = getAllColumnNames(
        traiFileDataCopy.data[0],
      ).indexOf(CAPILLARY_REJECTION_REASON.toLowerCase());
      if (rejectionIndex !== -1) {
        traiFileDataCopy.data.forEach((row) => {
          row.splice(rejectionIndex, 1);
        });
      }
      //adding validated rejection reason column to original results
      for (let i = 0; i < validatedData.length; i += 1) {
        traiFileDataCopy.data[i].push(
          validatedData[i][validatedData[i]?.length - 1],
        );
      }

      selectedFiles.push({
        fileMeta: traiFileMeta,
        fileData: traiFileDataCopy,
        columnMapping: [],
      });
      setFiles(selectedFiles);
      setPreviewFileIndex(selectedFiles.length - 1);
      setDropZone(false);
    }
  }, [validatedData, saveTemplate]);

  const getIndexofColumn = (allColumnNames, columnName) =>
    allColumnNames.findIndex(
      (column) => column.toLowerCase().trim() === columnName,
    );

  const getIndexesofColumns = (allColumnNames, columnNames) => {
    const indexes = [];
    allColumnNames.forEach((colName, index) => {
      if (columnNames.includes(colName.toLowerCase().trim())) {
        indexes.push(index);
      }
    });
    return indexes;
  };

  const headerValidationHandler = (senderIdString) => {
    //each row must contain atleast 1 header
    //each header can contain letters or numbers with length in range 3 to 9, no mixing
    //it cannot contain special characters except {}
    //eg: valid: "123456" "abcdef" "{123456}" invalid: "abc123" "abc$ef" "1234567"
    const senderIdLength = senderIdString.length;
    if (senderIdLength < 3) {
      return true;
    }
    const lettersOnly = /^[a-zA-Z]*$/;
    const numbersOnly = /^\d+$/;
    let isError = false;
    senderIdString.split(',').forEach((value) => {
      const _value = value.trim()?.replace(/[{}]/g, '');
      if (_value) {
        if (!(_value.length >= 3 && _value.length <= 9) ) {
          isError = true;
          return;
        }
        if (!(lettersOnly.test(_value) || numbersOnly.test(_value))) {
          isError = true;
        }
      }
    });
    return isError;
  };

  const statusValidationHandler = (columnName, value) => {
    //Approval status should be Approved or Status/Template status should be Active/Registered.
    switch (columnName) {
      case STATUS_ALIASES[0]:
      case STATUS_ALIASES[1]:
        return ![ACTIVE, REGISTERED].includes(value);
      case STATUS_ALIASES[2]:
        return value !== APPROVED;
      default:
        return true;
    }
  };

  const templateIdValidation = (templateId) => {
    let isError = false;
    const _templateId = templateId?.replace(/[“”"'‘’`´]/g, '');
    const numbersOnly = /^\d+$/;
    if (!numbersOnly.test(_templateId)) {
      isError = true;
    }
    return isError;
  };

  const checkDuplicateTemplateNameInDb = (
    transformedResults,
    templateIdIndex,
    templateNameIndex,
  ) => {
    //filtering out rows that have duplicate template name in CSV and rows which have template name/template id missing
    const checkInDb = transformedResults
      ?.map((elem, index) => {
        const rejectionReason = elem[elem?.length - 1]?.trim();
        if (index !== 0 && !rejectionReason?.includes(DUPLICATE)) {
          return {
            template_id: elem[templateIdIndex]?.replace(/[“”"'‘’`´]/g, ''),
            template_name: elem[templateNameIndex],
          };
        }
      })
      ?.filter(
        (obj) => obj && obj.template_name !== '' && obj.template_id !== '',
      );
    setUploadValidated(true);
    setValidatedData(transformedResults);
    setTemplateRegistrationIndex(templateIdIndex);
    if (checkInDb.length > 0) {
      actions.checkDuplicatesInDb(checkInDb);
    } else {
      const data = {
        templateId: [],
        count: 0,
      }
      actions.doneCheckingDuplicates(data);
    }
  };

  const checkDuplicateTemplateNameInCSV = (
    transformedResults,
    templateNameObj,
    templateIdIndex,
    templateNameIndex,
  ) => {
    //filtering and extracting index of template names with more than 1 occurence
    const duplicateTemplateNameRows =
      Object.values(templateNameObj)
        ?.filter((i) => i.count > 1)
        ?.map((i) => i.csvRow)
        ?.flat()
        ?.sort((a, b) => a - b) || [];
    let duplicateTemplateNameCounts = 0;

    //only if there are atleast 2 duplicate template names
    if (duplicateTemplateNameRows.length > 1) {
      duplicateTemplateNameRows.forEach((row) => {
        if (!transformedResults[row][transformedResults[row]?.length - 1]) {
          duplicateTemplateNameCounts += 1;
        }
        transformedResults[row][
          transformedResults[row]?.length - 1
        ] += ` This template name is repeated in this CSV.Duplicate template names are not allowed.`;
      });
      setTotalFailCount((prev) => prev + duplicateTemplateNameCounts);
    }
    checkDuplicateTemplateNameInDb(
      transformedResults,
      templateIdIndex,
      templateNameIndex,
    );
  };

  const checkCSVRowsValidation = (
    transformedResults,
    selectedHeaderAlias,
    selectedTemplateIdAlias,
    selectedStatusAlias,
  ) => {
    const headerIndex = getIndexofColumn(
      transformedResults[0],
      selectedHeaderAlias,
    );
    const templateIdIndex = getIndexofColumn(
      transformedResults[0],
      selectedTemplateIdAlias,
    );
    const statusIndexes = getIndexesofColumns(
      transformedResults[0],
      selectedStatusAlias,
    );
    const templateNameIndex = getIndexofColumn(
      transformedResults[0],
      TEMPLATE_NAME,
    );
    const templateNameObj = {};

    for (let row = 1; row < transformedResults.length; row += 1) {
      const errorArray = [];
      const columnErrorArray = [];
      let rejectionReasons = '';
      let statusErrorIndicator = false;
      //adding rejection reasons
      transformedResults[row].forEach((cell, index) => {
        if (index === headerIndex && headerValidationHandler(cell)) {
          columnErrorArray.push(
            `${selectedHeaderAlias.toUpperCase()} is mandatory and each ${selectedHeaderAlias.toUpperCase()} must contain either letters or digits with length between 3 to 9. It cannot contain special characters. `,
          );
        } else if (statusIndexes.includes(index) && !statusErrorIndicator) {
          statusErrorIndicator = statusValidationHandler(
            transformedResults[0][index].toLowerCase(),
            cell.toLowerCase(),
          );
        } else if (index === templateIdIndex && templateIdValidation(cell)) {
          columnErrorArray.push(
            `${selectedTemplateIdAlias.toUpperCase()} is mandatory and ${selectedTemplateIdAlias.toUpperCase()} must be numeric.`,
          );
        } else if (
          !cell &&
          ![headerIndex, templateIdIndex, ...statusIndexes].includes(index)
        ) {
          errorArray.push(`"${transformedResults[0][index]}"`);
        } else if (index === templateNameIndex && cell) {
          if (templateNameObj[cell]) {
            templateNameObj[cell].count += 1;
            templateNameObj[cell].csvRow?.push(row);
          } else {
            templateNameObj[cell] = { count: 1, csvRow: [row] };
          }
        }
      });

      if (statusErrorIndicator) {
        columnErrorArray.push(
          `Approval status should be Approved or Status/Template status should be Active/Registered.`,
        );
      }
      if (errorArray.length !== 0) {
        rejectionReasons = `${rejectionReasons} Please include these mandatory fields value: ${errorArray.join(
          ' ',
        )}.`;
      }
      if (columnErrorArray.length !== 0) {
        rejectionReasons = `${rejectionReasons} ${columnErrorArray
          .toString()
          .replace(',', ' ')}`;
      }
      transformedResults[row].push(rejectionReasons);
      //if there are rejected reasons present in this row at last column (where we store rejected reasons),  consider it as failure
      if (transformedResults[row][transformedResults[row]?.length - 1]) {
        setTotalFailCount((prev) => prev + 1);
      }
    }
    checkDuplicateTemplateNameInCSV(
      transformedResults,
      templateNameObj,
      templateIdIndex,
      templateNameIndex,
    );
  };

  const dataTransformHandler = (
    cols,
    traiFileDataCopy,
    headerAliasPresent,
    templateIdAliasPresent,
    statusAliasPresent,
  ) => {
    //getting the index of the cols for 6 mandatory cols and also taking care of alias of headers of mandatory columns
    const indexArray = [];
    for (let i = 0; i < cols.length; i += 1) {
      if (
        MANDATORY_COLUMNS.includes(cols[i]) ||
        HEADER_ALIASES.includes(cols[i]) ||
        TEMPLATE_ID_ALIASES.includes(cols[i]) ||
        TEMPLATE_MESSAGE_ALIASES.includes(cols[i]) ||
        STATUS_ALIASES.includes(cols[i]) ||
        TYPE_ALIASES.includes(cols[i])
      ) {
        indexArray.push(i);
      }
    }
    //transforming data to keep only mandatory cols data using their index
    const transformedResults = [];
    for (const key in traiFileDataCopy.data) {
      transformedResults.push(
        indexArray.map((i) => traiFileDataCopy.data[key][i]?.trim()),
      );
    }
    //add rejection header
    transformedResults[0].push(CAPILLARY_REJECTION_REASON);
    checkCSVRowsValidation(
      transformedResults,
      headerAliasPresent[0],
      templateIdAliasPresent[0],
      statusAliasPresent,
    );
  };

  //returns the headers(first row) of the uploaded file in lowercase
  const getAllColumnNames = (data) => data.map((x) => x?.toLowerCase()?.trim());

  const onDrop = (traiFile) => {
    // Sets isFileDropped state to true to load the spinner while the file is being parsed.
    setIsFileDropped(true);

    Papa.parse(traiFile[0], {
      complete: (fileData, fileMeta) => {
        setTraiFileData(fileData);
        setTraiFileMeta(fileMeta);
      },
    });
  };

  //common function to handle csv downloads
  const downloadHandler = (event, data, downloadedFileName) => {
    event.target.setAttribute(
      'href',
      `data:text/csv;charset=utf-8,${encodeURIComponent(data)}`,
    );
    event.target.setAttribute('download', downloadedFileName);
  };

  const downloadSampleCSV = (event) => {
    const csvContent = SAMPLE_CSV_DATA.map((e) => e.join(',')).join('\n');
    downloadHandler(event, csvContent, SAMPLE_CSV);
  };

  const downloadIssuesCSV = (event) => {
    let csvContent = [];
    let tempArray = [];
    const csvData = files[0].fileData.data;
    const rejectionIndex = csvData[0].indexOf(CAPILLARY_REJECTION_REASON);

    if (rejectionIndex !== -1) {
      tempArray.push(csvData[0]);
      for (let row = 1; row < csvData.length; row += 1) {
        if (csvData[row][rejectionIndex]) {
          tempArray.push(csvData[row]);
        }
      }
      tempArray = tempArray.map((row) =>
        row.map((cell) => cell.replace(',', ' ')),
      );
      csvContent = tempArray
        .map((e) => e.join(','))
        .map((e) => e.replace(/(\r\n|\n|\r)/gm, ' '))
        .join('\n');
    }
    downloadHandler(event, csvContent, DOWNLOAD_ISSUES_CSV);
  };

  const createCallback = ({ errorMessage }) => {
    if (!errorMessage) {
      CapNotification.success({
        message: formatMessage(messages.smsCreateNotification),
      });
      actions.clearCreateResponse();
    } else {
      CapNotification.error({
        message: errorMessage,
      });
    }
  };

  const onDoneCallback = () => {
    //start spinner
    setIsFileDropped(true);
    const csvData = files[0].fileData.data;
    const rejectionIndex = csvData[0].indexOf(CAPILLARY_REJECTION_REASON);
    const tempArray = [];
    tempArray.push(csvData[0]);

    // filter out non rejected rows
    for (let row = 1; row < csvData.length; row += 1) {
      if (!csvData[row][rejectionIndex]) {
        tempArray.push(csvData[row]);
      }
    }
    // Filter out the columns index that needs to save
    const cols = getAllColumnNames(tempArray[0]);
    const indexArray = [];
    for (let i = 0; i < cols.length; i += 1) {
      if (
        SAVED_COLUMNS.includes(cols[i]) ||
        HEADER_ALIASES.includes(cols[i]) ||
        TEMPLATE_ID_ALIASES.includes(cols[i]) ||
        TEMPLATE_MESSAGE_ALIASES.includes(cols[i]) ||
        TYPE_ALIASES.includes(cols[i])
      ) {
        indexArray.push(i);
      }
    }

    //transforming data to keep only saved cols data using their index
    const transformedResults = [];
    for (const key in tempArray) {
      transformedResults.push(
        indexArray.map((i) => {
          if (key === '0') {
            return MAPPED_SAVED_COLUMN[tempArray[key][i]?.toUpperCase()];
          }
          return tempArray[key][i]?.trim();
        }),
      );
    }

    // prepare data based on API
    const savedData = [];
    transformedResults.forEach((arr, index) => {
      if (index !== 0) {
        const obj = {};
        arr.forEach((data, i) => {
          obj[transformedResults[0][i]] = arr[i];
        });
        //removing additional single/double quotes from template_id
        obj['template_id'] = obj['template_id']?.replace(/[“”"'‘’`´]/g, '');
        obj['unicode-validity'] = true;
        obj['updated-sms-editor'] = '';
        obj['var-mapped'] = {};
        obj.header = obj.header?.replace(/[\s{}]/g, '')?.split(',');
        const history = obj;
        history.tabKey = 1;
        savedData.push({
          versions: { base: obj },
          history: [history],
          type: SMS,
          traiEnable: true,
          name: obj.template_name,
        });
      }
    });
    actions.createSMSTRAITemplates(
      { templates: savedData },
      (resp, errorMessage) => {
        createCallback({ errorMessage });
        if (isFullMode) {
          onCreateComplete();
        } else {
          onShowTemplates();
        }
      },
    );
  };

  const isDisableDone = () => {
    //only if there is a file which is validated and has passed templates
    //the done is not disabled otherwise it is disabled
    if (
      previewFileIndex !== null &&
      saveTemplate &&
      files[0].fileData.data.length - 1 - totalFailCount >= 1
    ) {
      return false;
    }
    return true;
  };

  const deleteOrCancelCSV = () => {
    setTraiFileData({});
    setTraiFileMeta(null);
    setValidatedData([]);
    setFiles([]);
    setTemplateRegistrationIndex(null);
    setErrorText('');
    setDropZone(true);
    setPreviewFileIndex(null);
    setIsFileDropped(false);
    setTotalFailCount(0);
    updateSaveTemplate(false);
    setUploadValidated(false);
  };

  const InstructionComp = (inst) => (
    <CapRow className="instruction">
      <CapColumn span={1}>
        <span className="instruction-num"></span>
      </CapColumn>
      <CapColumn span={23}>{inst.message}</CapColumn>
    </CapRow>
  );

  const fileZero = files[previewFileIndex] || {};
  const { fileData, fileMeta } = fileZero;
  return (
    <>
      <CapRow span={24} className="dlt-csv-upload-container">
        <CapColumn span={12}>
          <CapHeading type="h4" className="upload-file-title">
            {formatMessage(messages.uploadFile)}
          </CapHeading>
          {previewFileIndex === null && dropZone && (
            <>
              <CapSpin spinning={isFileDropped}>
                <Dropzone
                  onDrop={onDrop}
                  onFileDialogCancel={deleteOrCancelCSV}
                >
                  {({ getRootProps, getInputProps }) => (
                    <div {...getRootProps()} className="file-drop-zone">
                      <input {...getInputProps()} />
                      <div>
                        <img
                          src={dragdropImage}
                          role="presentation"
                          alt="dropzone"
                        />
                        <div className="drop-zone-text">
                          <CapHeading type="h2" className="drop-zone-text-1">
                            {formatMessage(messages.dropCsvFile)}
                          </CapHeading>
                          <CapHeading type="h3" className="drop-zone-text-2">
                            {formatMessage(messages.or)}
                          </CapHeading>
                          <CapButton
                            type="secondary"
                            className="drop-zone-text-3"
                          >
                            {formatMessage(messages.selectFileFromComputer)}
                          </CapButton>
                        </div>
                      </div>
                    </div>
                  )}
                </Dropzone>
              </CapSpin>
            </>
          )}
          {previewFileIndex !== null && (
            <>
              <CapRow span={24} className="dlt-csv-upload-container">
                <>
                  <CapDivider
                    type="horizontal"
                    className="upload-file-preview-divider-1"
                  />
                  <CapRow>
                    <CapColumn span={10}>
                      <CapLabel.CapLabelInline type="label9">
                        {fileMeta.name}
                      </CapLabel.CapLabelInline>
                      {saveTemplate && (
                        <CapLabel.CapLabelInline
                          type="label1"
                          className="number-of-records"
                        >
                          (
                          {formatMessage(messages.numberOfRecords, {
                            value: fileData.data.length - 1,
                          })}
                          )
                        </CapLabel.CapLabelInline>
                      )}
                    </CapColumn>
                    {errorText && (
                      <>
                        <CapColumn
                          span={13}
                          className="upload-failed-container"
                        >
                          <CapLabel
                            type="label9"
                            className="upload-failed-message"
                          >
                            {formatMessage(messages.failedToUpload)}
                          </CapLabel>
                          <CapIcon
                            type="warning"
                            className="upload-failed-icon"
                            svgProps={{ color: CAP_RED01 }}
                          ></CapIcon>
                        </CapColumn>
                      </>
                    )}
                    {!errorText && (
                      <>
                        <CapColumn
                          span={4}
                          className="validation-count-container"
                        >
                          <CapLabel
                            type="label9"
                            className="validation-count-label"
                          >
                            {formatMessage(messages.passedVal, {
                              number: fileData.data.length - 1 - totalFailCount,
                            })}
                          </CapLabel>
                          <CapIcon
                            type="check-circle"
                            className="validation-count-icon"
                            svgProps={{ color: CAP_PRIMARY.base }}
                          ></CapIcon>
                        </CapColumn>
                        <CapColumn
                          span={4}
                          className="validation-count-container"
                        >
                          <CapLabel
                            type="label9"
                            className="validation-count-label"
                          >
                            {formatMessage(messages.failedVal, {
                              number: totalFailCount,
                            })}
                          </CapLabel>
                          <CapIcon
                            type="warning"
                            className="validation-count-icon"
                            svgProps={{ color: CAP_RED01 }}
                          ></CapIcon>
                        </CapColumn>
                        <CapColumn span={5}>
                          {totalFailCount >= 1 && (
                            <a
                              onClick={downloadIssuesCSV}
                              className="download-issues-csv-link"
                            >
                              {formatMessage(messages.downloadIssues)}
                            </a>
                          )}
                        </CapColumn>
                      </>
                    )}
                    <CapColumn span={1} className="delete-csv">
                      <CapIcon
                        type="delete"
                        size="s"
                        onClick={deleteOrCancelCSV}
                      ></CapIcon>
                    </CapColumn>
                  </CapRow>
                  <CapDivider
                    type="horizontal"
                    className="upload-file-preview-divider-2"
                  />
                  {errorText && <CapError>{errorText}</CapError>}
                </>
              </CapRow>
            </>
          )}
        </CapColumn>
        <CapColumn span={12} className="dlt-csv-upload-instructions-container">
          <CapHeading type="h4">
            {formatMessage(messages.uploadInstructions)}
          </CapHeading>
          <div className="upload-instruction-list">
            <InstructionComp message={formatMessage(messages.deferEdit)} />
            <InstructionComp
              message={
                <FormattedMessage
                  {...messages.sampleFileInstruction}
                  values={{
                    link: (
                      <a
                        onClick={downloadSampleCSV}
                        className="download-sample-link"
                      >
                        {formatMessage(messages.sampleCsv)}
                      </a>
                    ),
                  }}
                />
              }
            />
            <InstructionComp
              message={formatMessage(messages.rowLimitInstruction)}
            />
            <InstructionComp
              message={formatMessage(messages.mandatoryColInstruction)}
            />
            <InstructionComp
              message={formatMessage(messages.statusesInstruction)}
            />
            <InstructionComp
              message={formatMessage(messages.duplicateTemplateIdInstruction)}
            />
            <InstructionComp
              message={formatMessage(messages.duplicateTemplateNameInstruction)}
            />
            <InstructionComp
              message={formatMessage(messages.trimInstruction)}
            />
            <InstructionComp
              message={formatMessage(messages.tempInstruction)}
            />
            <div style={{ marginBottom: '200px' }} />
          </div>
        </CapColumn>
        <SMSTraiFooter>
          <CapButton
            className="done-button"
            onClick={onDoneCallback}
            disabled={isDisableDone()}
          >
            <FormattedMessage {...messages.doneButtonLabel} />
          </CapButton>
        </SMSTraiFooter>
      </CapRow>
    </>
  );
};

SmsTraiCreate.propTypes = {
  dispatch: PropTypes.func.isRequired,
};

const mapStateToProps = createStructuredSelector({
  traiSms: makeSelectSmsTrai(),
});

const mapDispatchToProps = (dispatch) => ({
  actions: bindActionCreators(smsTraiActions, dispatch),
});


const withSaga = injectSaga({ key: 'smsTrai', saga: v2SmsTraiCreateSagas });
const withReducer = injectReducer({ key: 'smsTrai', reducer: v2SmsTraiCreateReducer });


export default withCreatives({
  WrappedComponent: SmsTraiCreate,
  mapStateToProps,
  mapDispatchToProps,
  userAuth: true,
  sagas: [withSaga],
  reducers: [withReducer],
});
