import { Button, TextField } from "@mui/material";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import React, { useEffect } from "react";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { PropTypes } from "prop-types";

import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { changeProfileInfo } from "../../services/changeProfileInfo";
import { useDispatch } from "react-redux";
import moment from "moment";
import { DatePicker } from "@mui/x-date-pickers";
import { ImageUpload } from "../../../../components/image-upload/ImageUpload";
import { fixBase64 } from "../../../../utils/toBase64";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { getUserProfile } from "../../services/getUserProfile";

export const ChangeProfile = ({ user }) => {
  const [profileImages, setProfileImages] = React.useState([]);
  const [profileImg, setProfileImg] = React.useState();
  const [openNotif] = useContext(AppContext);

  const factorPaymentHandler = (imageList) => {
    if (imageList[0]) {
      setProfileImg(fixBase64(imageList[0]?.data_url));
    }
    setProfileImages(imageList);
  };

  const dispatch = useDispatch();

  const formik = useFormik({
    initialValues: {
      firstname: user.firstName ? user.firstName : "",
      lastname: user.lastName ? user.lastName : "",
      natioanlId: user.nationalId ? user.nationalId : "",
      natioanlCode: user.nationalCode ? user.nationalCode : "",
      birthday: user.birthday ? new Date(user.birthday) : Date(),
    },
    validationSchema: Yup.object({
      firstname: Yup.string().typeError("لطفا فیلد را به درستی وارد کنید.!"),
      lastname: Yup.string().typeError("لطفا فیلد را به درستی وارد کنید.!"),
      natioanlId: Yup.number().typeError(
        "لطفا فیلد را به صورت عددی وارد کنید!"
      ),
      natioanlCode: Yup.number().typeError(
        "لطفا فیلد را به صورت عددی وارد کنید!"
      ),
    }),
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  return (
    <Grid
      container
      gap={SPACING.SMALL}
      direction="column"
      justifyContent="space-between"
    >
      <Grid container direction="column" gap={SPACING.SMALL}>
        <Grid>
          <TextField
            id="firstname"
            label="نام"
            variant="outlined"
            sx={{ width: "100%", height: "100%" }}
            value={formik.values.firstname}
            error={
              formik.touched.firstname ? Boolean(formik.errors.firstname) : null
            }
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.firstname && Boolean(formik.errors.firstname)
                ? formik.errors.firstname
                : null
            }
          />
        </Grid>

        <Grid>
          <TextField
            id="lastname"
            label="نام خانوادگی"
            variant="outlined"
            sx={{ width: "100%", height: "100%" }}
            value={formik.values.lastname}
            error={
              formik.touched.lastname ? Boolean(formik.errors.lastname) : null
            }
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.lastname && Boolean(formik.errors.lastname)
                ? formik.errors.lastname
                : null
            }
          />
        </Grid>

        <Grid>
          <TextField
            id="natioanlId"
            label="کد ملی"
            variant="outlined"
            sx={{ width: "100%", height: "100%" }}
            value={formik.values.natioanlId}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.natioanlId
                ? Boolean(formik.errors.natioanlId)
                : null
            }
            helperText={
              formik.touched.natioanlId && Boolean(formik.errors.natioanlId)
                ? formik.errors.natioanlId
                : null
            }
          />
        </Grid>

        <Grid>
          <TextField
            id="natioanlCode"
            label="شماره شناسنامه"
            variant="outlined"
            sx={{ width: "100%", height: "100%" }}
            value={formik.values.natioanlCode}
            error={
              formik.touched.natioanlCode
                ? Boolean(formik.errors.natioanlCode)
                : null
            }
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.natioanlCode && Boolean(formik.errors.natioanlCode)
                ? formik.errors.natioanlCode
                : null
            }
          />
        </Grid>

        <Grid display="contents">
          <DatePicker
            fullWidth
            label="تاریخ تولد"
            id="birthday"
            renderInput={(params) => <TextField {...params} />}
            value={formik.values.birthday}
            error={
              formik.touched.birthday ? Boolean(formik.errors.birthday) : null
            }
            onChange={(e) => {
              const selectedDate = new Date(e);
              //  moment(e).format("YYYY-MM-DD hh:mm:ss")
              formik.setFieldValue("birthday", selectedDate);
            }}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.birthday && Boolean(formik.errors.birthday)
                ? formik.errors.birthday
                : null
            }
          />
        </Grid>
        <Grid>
          <ImageUpload
            onChange={factorPaymentHandler}
            images={profileImages}
            maxNumber={1}
            title={"عکس پروفایل"}
          />
        </Grid>
      </Grid>
      <Grid>
        <Button
          fullWidth
          variant="contained"
          disabled={!formik.isValid}
          onClick={() => {
            const birthday = moment(new Date(formik.values.birthday)).format(
              "YYYY-MM-DD hh:mm:ss"
            );
            if (
              formik.values.firstname ||
              formik.values.lastname ||
              formik.values.natioanlCode ||
              formik.values.natioanlId ||
              profileImg
            ) {
              dispatch(LOADING_START());
              dispatch(
                changeProfileInfo({
                  type: "self_profile",
                  fullname:
                    formik.values.firstname + " " + formik.values.lastname,
                  first_name: formik.values.firstname
                    ? formik.values.firstname
                    : null,
                  last_name: formik.values.lastname
                    ? formik.values.lastname
                    : null,
                  national_code: formik.values.natioanlCode
                    ? formik.values.natioanlCode
                    : null,
                  national_id: formik.values.natioanlId
                    ? formik.values.natioanlId
                    : null,
                  birthday: birthday,
                  image: profileImg ? profileImg : "",
                  person_type: "self",
                })
              ).then((r) => {
                if (r.error) {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "مشکلی پیش آمده است!",
                    severity: "error",
                  });
                } else {
                  dispatch(getUserProfile());
                  dispatch(LOADING_END());
                  dispatch(
                    DRAWER({ right: false, bottom: false, content: null })
                  );
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
                dispatch(LOADING_END());
              });
            } else {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "لطفا حداقل یکی از موارد را تغییر دهید.",
                severity: "error",
              });
            }
          }}
        >
          ثبت اطلاعات
        </Button>
      </Grid>
    </Grid>
  );
};

ChangeProfile.propTypes = {
  user: PropTypes.any,
};
