/* eslint-disable camelcase */
/**
*
* CapImageUpload
*
*/

import React, { useState, useEffect, useCallback } from 'react';
import PropTypes from "prop-types";

import LabelHOC from '@capillarytech/cap-ui-library/assets/HOCs/ComponentWithLabelHOC';
import {
  CapDrawer,
  CapUploader,
  CapHeading,
  CapButton,
  CapImage,
  CapError,
} from '@capillarytech/cap-ui-library';
import { injectIntl, FormattedMessage, intlShape } from 'react-intl';
import { isEmpty, get } from 'lodash';
import './index.scss';
import Gallery from '../../v2Containers/Assets/Gallery';
import { MAX_SUPPORTED_IMAGE_SIZE } from './constants';
import {
  FACEBOOK, INAPP, RCS, WHATSAPP, VIBER, WEBPUSH, WEBPUSH_BRAND_ICON
} from "../../v2Containers/CreativesContainer/constants";

import messages from './messages';
import { MOBILEPUSH } from '../CapVideoUpload/constants';
import { CAP_SPACE_16 } from '@capillarytech/cap-ui-library/styled/variables';
function CapImageUpload(props) {
  const {
    intl,
    allowedExtensionsRegex,
    imgWidth,
    imgHeight,
    imgSize,
    minImgSize,
    uploadAsset,
    supportedExtensions,
    isFullMode,
    style,
    imageSrc,
    updateImageSrc,
    updateOnReUpload,
    index,
    className,
    imageData,
    channel,
    channelSpecificStyle,
    showReUploadButton = true,
    disableAutoRestore = false, // New prop to disable automatic restoration
    recommendedDimensions, // Array of {width, height} objects for recommended dimensions
    disabled = false,
  } = props;
  const {
    formatMessage,
  } = intl || {};


  useEffect(() => {
    // Skip automatic restoration if disableAutoRestore is true
    if (disableAutoRestore) {
      return;
    }

    const imageDataObj = imageData[`uploadedAssetData${index}`];
    if (!isEmpty(imageDataObj)) {
      const { secure_file_path = '', karixFileHandle = '', hapticFileHandle = '' } = get(imageDataObj, 'metaInfo', {});
      updateImageSrc(secure_file_path, hapticFileHandle || karixFileHandle);
    }
  }, [imageData[`uploadedAssetData${index}`], disableAutoRestore]);

  const [isImageError, updateImageErrorMessage] = useState(false);
  const [isDrawerRequired, updateDrawerRequirement] = useState(false);

  const { CapHeadingSpan } = CapHeading;
  const ImageComponent = useCallback(
    () => (
      <>
        {
          !isEmpty(imageSrc) ? (
            <div className={`image-container upload ${props.ifError ? 'error' : ''}`}>
              {!isEmpty(imageSrc) && (
                <CapImage src={imageSrc || ''} alt="upload-image-src" height="400" />
              )}
            </div>
          ) : null}
      </>
    ),
    [imageSrc],
  );

  const WithLabel = LabelHOC(ImageComponent);

  const uploadImages = 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 img = new Image();
    img.src = _URL.createObjectURL(file);
    img.onload = () => {
      const fileParams = {
        width: img.width,
        height: img.height,
        error: file && (file.size / (1e+6) > 5), // Checking if file exists and its size is greater than 5MB (5 * 10^6 bytes)
      };
      submitAction({ file, type: 'image', fileParams }, incorrectFile);
    };
    img.onerror = () => {
      const fileParams = {
        error: true,
      };
      submitAction({ fileParams }, incorrectFile);
    };
    if (e) {
      const event = e;
      event.target.value = null;
    }
  }, []);

  const rcsValidation = useCallback((incorrectFile, data, size, height, width, error) => {
    if (incorrectFile || size < minImgSize || size > imgSize || height !== imgHeight || width !== imgWidth || error) {
      updateImageErrorMessage(formatMessage(messages.imageErrorDesc));
    } else {
      updateImageErrorMessage('');
      uploadAsset(
        data.file,
        data.type,
        data.fileParams,
        index,
      );
    }
  }, []);

  const submitAction = useCallback((data, incorrectFile) => {
    const {
      file,
      fileParams,
    } = data || {};
    const { size } = file || {};
    const { height, width, error } = fileParams || {};
    if (channel === RCS) {
      rcsValidation(incorrectFile, data, size, height, width, error);
    } else if ([WEBPUSH, WEBPUSH_BRAND_ICON].includes(channel)) {
      // For WEBPUSH, only validate file extension, size, and format - no dimension validation
      if (incorrectFile || size > imgSize || error) {
        updateImageErrorMessage(formatMessage(messages.imageErrorDesc));
      } else {
        updateImageErrorMessage('');
        uploadAsset(
          data.file,
          data.type,
          data.fileParams,
          index,
        );
      }
    } else if (incorrectFile || size > imgSize || height > imgHeight || width > imgWidth || error) {
      updateImageErrorMessage(formatMessage(messages.imageErrorDesc));
    } else {
      updateImageErrorMessage('');
      uploadAsset(
        data.file,
        data.type,
        data.fileParams,
        index,
      );
    }
  }, [isImageError]);

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

  const setDrawerVisibility = useCallback((drawervisibleFlag) => updateDrawerRequirement(drawervisibleFlag), [isDrawerRequired]);

  const onGalleryClick = useCallback((event) => {
    event.stopPropagation();
    setDrawerVisibility(true);
  }, []);

  const onReUpload = useCallback(() => {
    updateImageSrc('');
    updateOnReUpload();
    // Don't automatically trigger file dialog - let user choose between computer and gallery
  }, []);

  const onGalleryImageSelect = useCallback((imageTemplate) => {
    const {
      secure_file_path: image, width, height, file_size: size,
    } = get(imageTemplate, 'metaInfo', {});
    updateDrawerRequirement(false);
    // For WEBPUSH, skip dimension validation - only check extension, size
    if ([WEBPUSH, WEBPUSH_BRAND_ICON].includes(channel)) {
      if (!allowedExtensionsRegex.test(image) || size > imgSize) {
        updateImageErrorMessage(formatMessage(messages.imageErrorDesc));
      } else {
        updateImageErrorMessage('');
        updateImageSrc(image);
      }
    } else if (!allowedExtensionsRegex.test(image) || height > imgHeight || width > imgWidth || size > imgSize) {
      updateImageErrorMessage(formatMessage(messages.imageErrorDesc));
    } else {
      updateImageErrorMessage('');
      updateImageSrc(image);
    }
  }, [isImageError, isDrawerRequired, channel, allowedExtensionsRegex, imgSize, formatMessage]);

  const getGalleryDrawerContent = useCallback(() => {
    const locationGallery = {
      pathname: `/assets`,
      search: '',
      query: !isFullMode ? { type: 'embedded', module: 'library' } : {},
    };
    return (
      <>
        <CapHeading type="h3">
          {formatMessage(messages.imageGallery)}
        </CapHeading>
        <Gallery
          location={locationGallery}
          isFullMode={isFullMode}
          isLineAsset
          onGalleryImageSelect={onGalleryImageSelect}
        />
      </>
    );
  }, []);

  const getImageSizeLabel = () => (
    <CapHeadingSpan type="label2">
      <FormattedMessage
        {...messages.channelImageSize}
        values={{
          size: MAX_SUPPORTED_IMAGE_SIZE[channel],
        }}

      />
    </CapHeadingSpan>
  );

  const getImageSection = useCallback(() => {
    if (imageSrc === "") {
      return (
        <>
          <CapUploader.CapDragger
            customRequest={capUploaderCustomRequest}
            className="form-builder-dragger grey-background"
            showUploadList={!isImageError}
            disabled={disabled}
          >
            <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-image" type="secondary" disabled={disabled} tabIndex={disabled ? -1 : undefined}>
              <FormattedMessage {...messages.uploadComputer} />
            </CapButton>
            {channel !== WHATSAPP && (
              <CapButton
                className="dragger-button gallery-select"
                type="secondary"
                onClick={onGalleryClick}
                disabled={disabled}
                tabIndex={disabled ? -1 : undefined}
              >
                <FormattedMessage {...messages.uploadGallery} />
              </CapButton>
            )}
          </CapUploader.CapDragger>
          <CapError type="error" className="upload-image-error">
            {isImageError}
          </CapError>
        </>
      );
    }
    if (showReUploadButton) {
      return (
        <CapButton
          className="dragger-button re-upload"
          type="flat"
          onClick={onReUpload}
          style={channelSpecificStyle ? { marginTop: `-${CAP_SPACE_16}` } : {}}
          disabled={disabled}
          tabIndex={disabled ? -1 : undefined}
        >
          <FormattedMessage {...messages.imageReUpload} />
        </CapButton>
      );
    }
  }, [isImageError, imageSrc, disabled, showReUploadButton, channel, channelSpecificStyle, capUploaderCustomRequest, onGalleryClick, onReUpload]);

  return (
    <div style={style} className="cap-custom-image-upload">
      <WithLabel
        key="with-label"
        ifError={!!isImageError}

      />
      <form encType="multipart/form-data" id="form" className={className}>
        <input
          key="imgFile"
          style={{ display: 'none' }}
          id="imageFileName"
          type="file"
          onChange={(e) => uploadImages(e, { files: e.target.files })}
          accept={supportedExtensions || "image/*"}
          disabled={disabled}
          tabIndex={disabled ? -1 : undefined}
        />
        {getImageSection()}
        <CapDrawer
          content={getGalleryDrawerContent()}
          visible={isDrawerRequired}
          width={430}
          onClose={() => updateDrawerRequirement(false)}
        />
      </form>
      <div className="image-info-wrapper">
        {channel === WHATSAPP && (
          <>
            {getImageSizeLabel()}
            <CapHeadingSpan type="label2">
              <FormattedMessage {...messages.whatsappAspectRatio} />
            </CapHeadingSpan>
          </>
        )}
        {![WHATSAPP, INAPP].includes(channel) && (
          <CapHeadingSpan type="label2" className="image-dimension">
            {[WEBPUSH, WEBPUSH_BRAND_ICON].includes(channel) && recommendedDimensions?.length ? (
              <FormattedMessage
                {...messages.recommendedDimensions}
                values={{
                  dimensions: recommendedDimensions
                    .map((dim) => `${dim.width} x ${dim.height}px`)
                    .join(', '),
                }}
              />
            ) : (
              <FormattedMessage {...messages.imageDimenstionDescription} values={{ width: imgWidth, height: imgHeight }} />
            )}
          </CapHeadingSpan>
        )}
        {channel === FACEBOOK && (
          <CapHeadingSpan type="label2" className="image-aspect-ratio">
            <FormattedMessage {...messages.aspectRatio} />
          </CapHeadingSpan>
        )}
        {channel === RCS && (
          minImgSize ? (
            <CapHeadingSpan type="label2">
              <FormattedMessage
                {...messages.RcschannelImageSize}
                values={{
                  size: imgSize / 1024,
                  minSize: minImgSize / 1024,
                }}
              />
            </CapHeadingSpan>
          ) : (
            getImageSizeLabel()
          )
        )}
        {[VIBER, INAPP, MOBILEPUSH, WEBPUSH, WEBPUSH_BRAND_ICON].includes(channel) && getImageSizeLabel()}
        <CapHeadingSpan type="label2" className="image-format">
          {channel === INAPP ? <FormattedMessage {...messages.format2} /> : <FormattedMessage {...messages.format} />}
        </CapHeadingSpan>
      </div>
    </div>
  );
}

CapImageUpload.propTypes = {
  allowedExtensionsRegex: PropTypes.any,
  imgWidth: PropTypes.number,
  imgHeight: PropTypes.number,
  imgSize: PropTypes.number,
  minImgSize: PropTypes.number,
  uploadAsset: PropTypes.func,
  supportedExtensions: PropTypes.any,
  style: PropTypes.any,
  imageSrc: PropTypes.string,
  updateImageSrc: PropTypes.func,
  intl: intlShape,
  isFullMode: PropTypes.bool,
  className: PropTypes.string,
  updateOnReUpload: PropTypes.func,
  imageData: PropTypes.object,
  index: PropTypes.number,
  channel: PropTypes.string,
  channelSpecificStyle: PropTypes.bool,
  disableAutoRestore: PropTypes.bool,
  recommendedDimensions: PropTypes.arrayOf(
    PropTypes.shape({
      width: PropTypes.number.isRequired,
      height: PropTypes.number.isRequired,
    })
  ),
  disabled: PropTypes.bool,
};

export default injectIntl(CapImageUpload);
