import React, { useState, useEffect } from "react";
import PropTypes from "prop-types";
import BackdropComponent from "../../MUI/BackdropComponent";
import {
  EditProfileContainer,
  ProfileImageContainer,
  InputFieldLabel,
  InputField,
  BackButton,
  CloseButton,
  SaveButton,
  ProfileHeader,
  BasicInfo,
  DetailsInfo,
  ButtonsContainer,
  ErrorMessage,
  ProfileImagePicker,
} from "./EditProfile.styled";
import selectedTheme from "../../../themes";
import { useFormik } from "formik";
import { ReactComponent as ArrowBack } from "../../../assets/images/svg/arrow-back.svg";
import { ReactComponent as CloseIcon } from "../../../assets/images/svg/close-modal.svg";
import { useTranslation } from "react-i18next";
import {
  editMineProfile,
  fetchMineProfile,
} from "../../../store/actions/profile/profileActions";
import { useDispatch, useSelector } from "react-redux";
import { selectUserId } from "../../../store/selectors/loginSelectors";
import useScreenDimensions from "../../../hooks/useScreenDimensions";
import editProfileValidation from "../../../validations/editProfileValidation";

const EditProfile = (props) => {
  const [profileImage, setProfileImage] = useState(props.profile.image);
  const [showBasic, setShowBasic] = useState(true);
  const [showDetails, setShowDetails] = useState(true);
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const dimensions = useScreenDimensions();
  const userId = useSelector(selectUserId);

  useEffect(() => {
    if (dimensions.width < 600) {
      setShowDetails(false);
    } else {
      setShowDetails(true);
    }
  }, [dimensions.width]);

  const handleApiResponseSuccess = () => {
    dispatch(fetchMineProfile(userId));
    props.reFetchProfile();
  };

  const handleSubmit = (values) => {
    dispatch(editMineProfile({ ...values, handleApiResponseSuccess }));
    props.closeModalHandler();
  };

  const formik = useFormik({
    initialValues: {
      firmName: `${props.profile.company.name}`,
      firmPIB: `${props.profile.company.PIB}`,
      firmLocation: `${props.profile.company.contacts.location}`,
      firmWebsite: `${props.profile.company.contacts.web}`,
      firmApplink: "",
      firmPhone: `${props.profile.company.contacts.telephone}`,
      firmLogo: profileImage,
    },
    validationSchema: editProfileValidation,
    onSubmit: handleSubmit,
    validateOnBlur: true,
    enableReinitialize: true,
  });

  const closeEditModalHandler = () => {
    props.closeModalHandler();
  };

  const showDetailsHandler = () => {
    setShowDetails(!showDetails);
    setShowBasic(!showBasic);
  };

  const setImage = (image) => {
    setProfileImage(image);
  };

  return (
    <>
      <BackdropComponent
        handleClose={closeEditModalHandler}
        isLoading
        position="fixed"
      />
      <EditProfileContainer component="form" onSubmit={formik.handleSubmit}>
        {!showBasic && (
          <BackButton onClick={showDetailsHandler}>
            <ArrowBack />
          </BackButton>
        )}
        <ProfileImageContainer>
          <ProfileImagePicker
            image={profileImage}
            setImage={setImage}
          ></ProfileImagePicker>
          <ProfileHeader>{props.profile.company.name}</ProfileHeader>
        </ProfileImageContainer>
        <CloseButton onClick={closeEditModalHandler}>
          <CloseIcon />
        </CloseButton>
        {showBasic && (
          <BasicInfo>
            <InputFieldLabel leftText={t("common.labelFirm").toUpperCase()} />
            <InputField
              name="firmName"
              value={formik.values.firmName}
              onChange={formik.handleChange}
              error={formik.touched.firmName && formik.errors.firmName}
              margin="normal"
              fullWidth
            />
            <InputFieldLabel leftText={t("common.labelPIB")} />
            <InputField
              name="firmPIB"
              type="number"
              value={formik.values.firmPIB}
              onChange={formik.handleChange}
              error={formik.touched.firmPIB && formik.errors.firmPIB}
              margin="normal"
              fullWidth
            />
            <InputFieldLabel
              leftText={t("common.labelLocation").toUpperCase()}
            />
            <InputField
              name="firmLocation"
              value={formik.values.firmLocation}
              onChange={formik.handleChange}
              error={formik.touched.firmLocation && formik.errors.firmLocation}
              margin="normal"
              fullWidth
            />
          </BasicInfo>
        )}
        {showDetails && (
          <DetailsInfo>
            <InputFieldLabel
              leftText={t("editProfile.website").toUpperCase()}
            />
            <InputField
              name="firmWebsite"
              value={formik.values.firmWebsite}
              onChange={formik.handleChange}
              margin="normal"
              fullWidth
            />
            <InputFieldLabel
              leftText={t("editProfile.applink").toUpperCase()}
            />
            <InputField
              name="firmApplink"
              values={formik.values.firmApplink}
              margin="normal"
              fullWidth
            />
            <InputFieldLabel
              leftText={t("editProfile.phoneNumber").toUpperCase()}
            />
            <InputField
              type="number"
              name="firmPhone"
              value={formik.values.firmPhone}
              onChange={formik.handleChange}
              error={formik.touched.firmPhone && formik.errors.firmPhone}
              margin="normal"
              fullWidth
            />
          </DetailsInfo>
        )}

        {formik.errors.firmName && formik.touched.firmName ? (
          <ErrorMessage>{formik.errors.firmName}</ErrorMessage>
        ) : formik.errors.firmPIB && formik.touched.firmPIB ? (
          <ErrorMessage>{formik.errors.firmPIB}</ErrorMessage>
        ) : formik.errors.firmLocation && formik.touched.firmLocation ? (
          <ErrorMessage>{formik.errors.firmLocation}</ErrorMessage>
        ) : formik.errors.firmPhone && formik.touched.firmPhone ? (
          <ErrorMessage>{formik.errors.firmPhone}</ErrorMessage>
        ) : (
          <></>
        )}

        {dimensions.width > 600 ? (
          <ButtonsContainer>
            <SaveButton
              type="submit"
              variant="contained"
              height="48px"
              width="335px"
              buttoncolor={selectedTheme.primaryPurple}
              textcolor="white"
            >
              {t("editProfile.saveChanges")}
            </SaveButton>
          </ButtonsContainer>
        ) : (
          <ButtonsContainer>
            <SaveButton
              height="44px"
              width="155px"
              buttoncolor={selectedTheme.primaryPurple}
              textcolor={selectedTheme.primaryPurple}
              onClick={showDetailsHandler}
            >
              {showDetails
                ? t("editProfile.showBasic")
                : t("editProfile.showDetails")}
            </SaveButton>
            <SaveButton
              type="submit"
              variant="contained"
              height="44px"
              width="155px"
              buttoncolor={selectedTheme.primaryPurple}
              textcolor="white"
            >
              {t("common.save")}
            </SaveButton>
          </ButtonsContainer>
        )}
      </EditProfileContainer>
    </>
  );
};

EditProfile.propTypes = {
  children: PropTypes.node,
  profile: PropTypes.any,
  closeModalHandler: PropTypes.func,
  setImage: PropTypes.func,
  reFetchProfile: PropTypes.func,
};

export default EditProfile;
