import { Col, Row, Upload } from "antd";
import { RcFile } from "antd/lib/upload";
import { UploadFile } from "antd/lib/upload/interface";
import classNames from "classnames";
import { Icon } from "components/Icon";
import Progress from "components/Progress";
import { Text } from "components/Typography";
import React, { useCallback, useEffect, useState } from "react";
import "react-lazy-load-image-component/src/effects/blur.css";
import { useDispatch } from "react-redux";
import { MediaUpload } from "redux/Common/types";
import { useTypedSelector } from "redux/rootReducer";
import { setTalentProfileAction } from "redux/User/actions";
import { selectUserData } from "redux/User/selector";
import { User } from "redux/User/types";
import { onBeforeUpload, pushImageToS3 } from "utils/photo";
import ImageReZoom from "../../../../components/ImageReZoom";
import { loadImage } from "../../../../utils/image";
import notification from "../../../../utils/notification";
import config from "config";

import "./ProfileCustomImage.scss";

const API_URL = config.api.url;
const { Dragger } = Upload;
interface ProfileCustomPictureProps {
  disabled?: boolean;
  isUploader?: boolean;
  title?: string;
}
const CustomImageUploader = ({
  disabled,
  title = "Add your Image",
  ...props
}: ProfileCustomPictureProps) => {
  const dispatch = useDispatch();
  const user: User | null | undefined = useTypedSelector(selectUserData);
  const [photoUpload, setPhotoUpload] = useState<MediaUpload>();

  const [imageWidthScale, setImageWidthScale] = useState<string>("100%");
  useEffect(() => {
    if (!user) return;
    setPhotoUpload({
      id: 0,
      url: user.talentProfile?.displayNameImage,
      fileName: user.talentProfile?.displayNameImage,
    });
    setImageWidthScale(user.talentProfile?.displayNameImageScale || "100%");
  }, [user]);

  const updateProfileDisplayNameImage = useCallback(
    (photo: MediaUpload) => {
      dispatch(
        setTalentProfileAction({
          displayNameImage: photo.url,
        })
      );
    },
    [dispatch]
  );

  const handleChange = async (
    file: UploadFile<any>,
    id: { metaId: number | undefined }
  ) => {
    try {
      let photo: MediaUpload = {};
      if (file.status === "uploading") {
        photo.loading = true;
        photo.fileName = file.name;
        setPhotoUpload({ ...photoUpload, ...photo });
        return;
      }

      // TODO: remove status error when integrate with API
      if (file.status === "done" || file.status === "error") {
        const url = await pushImageToS3(file, (value: number) => {
          setPhotoUpload((values) => ({ ...values, percent: value }));
        });

        if (!url) {
          photo = {
            id: id.metaId,
            fileName: undefined,
            loading: false,
          };
        } else {
          photo = {
            id: id.metaId,
            fileName: file.name,
            url,
            loading: false,
          };
        }
      }

      updateProfileDisplayNameImage({ ...photoUpload, ...photo });
      setPhotoUpload({ ...photoUpload, ...photo });
    } catch (ex) {
      console.error(ex);
    }
  };
  const onSetImageWidthScale = (value: string) => {
    setImageWidthScale(value);
    dispatch(
      setTalentProfileAction({
        displayNameImageScale: value,
      })
    );
  };
  const handleBeforeCrop = async (file: RcFile) => {
    const data: any = await loadImage(file);
    if (data) {
      if (data.width < 564) {
        notification.error({
          message: "Your image must be wider than 564 pixels",
        });
        return false;
      }
    }

    return onBeforeUpload(file, true);
  };
  (window as any).handleBeforeCrop = handleBeforeCrop;
  return (
    <div className="profile-custom-image" {...props}>
      <div
        className={classNames(
          "profile-custom-image__wrapper",
          disabled && "opacity--40"
        )}
      >
        <ImageReZoom
          beforeCrop={handleBeforeCrop}
          onSetImageWidth={onSetImageWidthScale}
        >
          <Dragger
            disabled={disabled}
            accept="image/png,image/jpeg,image/webp"
            action={API_URL}
            showUploadList={false}
            onChange={({ file }) => {
              handleChange(file, {
                metaId: photoUpload?.id,
              });
            }}
            data-testid="profile-custom-image__drag"
          >
            {(photoUpload?.percent as number) < 100 || photoUpload?.loading ? (
              <Progress value={photoUpload?.percent} />
            ) : (
              <Row className="p__x--20" align="middle" justify="center">
                <Col>
                  <Icon name="add-blue" />
                </Col>
                <Col>
                  <Text className="d--block m__b--4" preset="semibold16">
                    {title}
                  </Text>
                  <Text className="text--grey4">
                    Use an size that’s at least 564 pixels wide and 6MB or less.
                    For best results, use an image with transparent background.
                  </Text>
                </Col>
              </Row>
            )}
          </Dragger>
        </ImageReZoom>
      </div>
    </div>
  );
};
export default CustomImageUploader;
