/* eslint-disable camelcase */
import React, { useState, useEffect, useCallback } from 'react';
import PropTypes from "prop-types";
import LabelHOC from '@capillarytech/cap-ui-library/assets/HOCs/ComponentWithLabelHOC';
import {
  CapUploader,
  CapHeading,
  CapButton,
} from '@capillarytech/cap-ui-library';
import { injectIntl, FormattedMessage} from 'react-intl';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
import './index.scss';
import messages from './messages';
import { convertPdfToImages } from '../WhatsappDocumentPreview/index';

function CapDocumentUpload(props) {
  const {
    allowedExtensionsRegex,
    documentSize,
    uploadAsset,
    supportedExtensions,
    documentSrc,
    updateDocumentSrc,
    updateOnReUpload,
    index,
    className,
    documentData,
    whatsappDocParams,
    setWhatsappDocParams,
    docPreview,
    supportedFormat,
    supportedMaxSize,
  } = props;

  useEffect(() => {
    const docDataObj = documentData[`uploadedAssetData${index}`];
    if (!isEmpty(docDataObj)) {
      const { secure_file_path = '', karixFileHandle = '', hapticFileHandle = '', name = '', file_size = ''} = get(docDataObj, 'metaInfo', {});
      setWhatsappDocParams({
        ...whatsappDocParams,
        whatsappDocName: `${name.slice(0, -13)}.pdf`,
        //sliced to show the actual name of the pdf to the user and in the preview, this remove suffix appended to the name on creatives node side
        whatsappDocSize: file_size,
      });
      updateDocumentSrc(secure_file_path, hapticFileHandle || karixFileHandle);
    }
  }, [documentData[`uploadedAssetData${index}`]]);

  const [isDocError, updateDocErrorMessage] = useState(false);

  const {CapHeadingSpan} = CapHeading;

  //renders the preview for document
  const DocPreviewComponent = useCallback(
    () => (
      <div className={`upload uploaded-container ${props.ifError ? 'error' : ''}`}>
        {docPreview}
      </div>
    ),
    [documentSrc],
  );

  const WithLabel = LabelHOC(DocPreviewComponent);

  //this function gets executed on the upload of a document
  const uploadDocuments = useCallback((e, {files}) => {
    if (e) {
      e.preventDefault();
    }
    const _URL = window.URL || window.webkitURL;
    let incorrectFile = false;
    const file = files[0];
    if (!allowedExtensionsRegex.test(file.name)) {
      incorrectFile = true;
    }
    const doc = new FileReader();
    doc.src = _URL.createObjectURL(file);
    const fileParams = {
      error: false, // checking error based on file size
    };
    const result = convertPdfToImages(file);
    result.then((data) =>
    setWhatsappDocParams(
      {
        ...whatsappDocParams,
        whatsappDocImg: data?.image,
        whatsappDocPages: data?.numberOfPages,
      })
    );
    submitAction({file, type: 'document', fileParams}, incorrectFile);
    if (e) {
      const event = e;
      event.target.value = null;
    }
  }, []);
  const submitAction = useCallback((data, incorrectFile) => {
    const {
      file,
      fileParams,
      type,
    } = data || {};
    const { size } = file || {};
    const { error } = fileParams || {};
    if (incorrectFile || size > documentSize || error) {
      updateDocErrorMessage(<FormattedMessage {...messages.docErrorDesc} />);
    } else {
      updateDocErrorMessage('');
      uploadAsset(
        file,
        type,
        fileParams,
        index,
      );
    }
  }, [isDocError]);

  const capUploaderCustomRequest = useCallback((uploadData) => {
    uploadDocuments(undefined, {files: [uploadData.file]});
  }, []);

  //this function gets called when reUpload button is clicked
  const onReUpload = useCallback(() => {
    updateDocumentSrc('');
    updateOnReUpload();
  }, []);

  //renders the dragger component to upload the document
  const getDocumentSection = useCallback(() => {
    if (documentSrc === "") {
      return (
        <>
          <CapUploader.CapDragger
            customRequest={capUploaderCustomRequest}
            className="form-builder-dragger whatsapp-background"
            showUploadList={!isDocError}
          >
            <CapHeading className="dragger-title" type="h7">
              <FormattedMessage {...messages.dragAndDrop} />
            </CapHeading>
            <CapHeading className="dragger-or" type="label6">
              <FormattedMessage {...messages.or} />
            </CapHeading>
            <CapButton className="dragger-button upload-doc" type="secondary">
              <FormattedMessage {...messages.uploadComputer} />
            </CapButton>
          </CapUploader.CapDragger>
        </>
      );
    }
    return (
      <CapButton
        className="dragger-button re-upload"
        type="flat"
        onClick={onReUpload}
      >
        <FormattedMessage {...messages.docReUpload} />
      </CapButton>
    );
  }, [isDocError, documentSrc]);

  return (
    <div className="cap-custom-document-upload document-div">
      <WithLabel
        key={`with-label`}
        errorMessage={isDocError} ifError={!!isDocError}
      />
      <form encType="multipart/form-data" id={`form`} className={className}>
        <input
          key={`docFile`}
          className="input-div"
          id="fileName"
          type="file"
          //passing event and files to the uploadDocuments function as
          //there are other instance where event is undefined and we have files
          onChange={(e) => uploadDocuments(e, { files: e.target.files })}
          accept={supportedExtensions || ".pdf"}
      />
        {getDocumentSection()}
      </form>
      <div className="image-info-wrapper">
        <CapHeadingSpan type="label2">
          <FormattedMessage
            {...messages.whatsappDocSize}
            values={{
              size: supportedMaxSize,
            }}
          />
        </CapHeadingSpan>
        <CapHeadingSpan type="label2" className="image-format">
          <FormattedMessage
            {...messages.format}
            values={{
              format: supportedFormat,
            }}
          />
        </CapHeadingSpan>
      </div>
    </div>
  );
}

CapDocumentUpload.propTypes = {
  allowedExtensionsRegex: PropTypes.any,
  documentSize: PropTypes.number,
  uploadAsset: PropTypes.func,
  supportedExtensions: PropTypes.any,
  documentSrc: PropTypes.string,
  updateDocumentSrc: PropTypes.func,
  className: PropTypes.string,
  updateOnReUpload: PropTypes.func,
  documentData: PropTypes.object,
  index: PropTypes.number,
  supportedFormat: PropTypes.string,
  supportedMaxSize: PropTypes.string,
  whatsappDocParams: PropTypes.string,
  setWhatsappDocParams: PropTypes.func,
  docPreview: PropTypes.any,
};

export default injectIntl(CapDocumentUpload);
