import React, { useState } from "react";
import { PropTypes } from "prop-types";
import { Yup } from "../../../../lib/yup/yup";
import { Grid } from "../../../../components/grid/Grid";
import { Button, TextField } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useFormik } from "formik";
import { SPACING } from "../../../../data/spacing";
import { useDispatch } from "react-redux";
import { inspectorUpdateUserProfile } from "../../services/inspector-update-user-profile";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useContext } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceGetUserByKey } from "../../../province/services/province-get-user-by-key";
import { useEffect } from "react";
import { cityGetProvinces } from "../../../city/services/CityGetProvinces";
import { cityGetCity } from "../../../city/services/city-get-city";

export const InspectorEditUserProfile = ({
  id,
  birthday,
  nationalCode,
  nationalId,
  firstName,
  lastName,
  password,
  phone,
}) => {
  const [openNotif] = useContext(AppContext);

  const [, setProvinceData] = useState([]);
  const [, setCityData] = useState([]);
  const [provinceKey] = useState();
  // const [cityKey, setCityKey] = useState();
  const [, setIsExistProvince] = useState(true);

  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      fname: firstName ? firstName : "",
      lname: lastName ? lastName : "",
      nationalcode: nationalId ? nationalId : "",
      nationalId: nationalCode ? nationalCode : "",
      password: password ? password : "",
      phone: phone ? phone : "",
      birthday: birthday
        ? birthday
        : moment(Date()).format("YYYY-MM-DD hh:mm:ss"),
    },
    validationSchema: Yup.object({
      fname: Yup.string().typeError("لطفا فیلد را پر کنید!"),
      lname: Yup.string().typeError("لطفا فیلد را پر کنید!"),
      nationalcode: Yup.string().typeError(
        "لطفا مقادیر را به درستی وارد کنید!"
      ),
      nationalId: Yup.number().test(
        "len",
        "کد ملی میبایست ده رقم باشد.",
        (val, context) => {
          if (context.originalValue) {
            return context.originalValue.length === 10;
          }
        }
      ),
      password: Yup.string().typeError("لطفا مقادیر را به درستی وارد کنید!"),
    }),
  });

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

  useEffect(() => {
    dispatch(cityGetProvinces())?.then((r) => {
      setProvinceData(r.payload.data);
    });
  }, []);

  useEffect(() => {
    if (provinceKey) {
      dispatch(LOADING_START());
      dispatch(cityGetCity(provinceKey)).then((r) => {
        setCityData(r.payload.data);
        setIsExistProvince(false);
        dispatch(LOADING_END());
      });
    }
  }, [provinceKey]);

  return (
    <>
      <Grid>
        <Grid container gap={SPACING.SMALL} direction="column">
          <Grid>
            <TextField
              id="fname"
              label="نام"
              variant="outlined"
              sx={{ width: "100%" }}
              value={formik.values.fname}
              error={formik.touched.fname ? Boolean(formik.errors.fname) : null}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.fname && Boolean(formik.errors.fname)
                  ? formik.errors.fname
                  : null
              }
            />
          </Grid>
          <Grid>
            <TextField
              id="lname"
              label="نام خانوادگی "
              variant="outlined"
              sx={{ width: "100%" }}
              value={formik.values.lname}
              error={formik.touched.lname ? Boolean(formik.errors.lname) : null}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.lname && Boolean(formik.errors.lname)
                  ? formik.errors.lname
                  : null
              }
            />
          </Grid>

          {/* <Grid>
            <Autocomplete
              disablePortal
              id="province"
              options={provinceData?.map((i) => ({
                id: i.key,
                label: i.name,
              }))}
              onChange={(e, value) => {
                setProvinceKey(value.id);
              }}
              renderInput={(params) => (
                <TextField {...params} label="استان را انتخاب  کنید" />
              )}
            />
          </Grid>

          <Grid>
            <Autocomplete
              disabled={isExistProvince}
              disablePortal
              id="city"
              options={cityData?.map((i) => ({ id: i.key, label: i.name }))}
              onChange={(e, value) => {
                setCityKey(value.id);
              }}
              renderInput={(params) => (
                <TextField {...params} label="شهر را انتخاب  کنید" />
              )}
            />
          </Grid> */}

          <Grid>
            <DatePicker
              fullWidth
              label="تاریخ تولد"
              id="birthday"
              renderInput={(params) => <TextField {...params} />}
              value={formik.values.birthday}
              error={
                formik.touched.birthday ? Boolean(formik.errors.birthday) : null
              }
              onChange={(e) => {
                formik.setFieldValue(
                  "birthday",
                  moment(e).format("YYYY-MM-DD hh:mm:ss")
                );
              }}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.birthday && Boolean(formik.errors.birthday)
                  ? formik.errors.birthday
                  : null
              }
            />
          </Grid>

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

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

          <Grid>
            <TextField
              id="phone"
              label="تلفن"
              variant="outlined"
              sx={{ width: "100%" }}
              value={formik.values.phone}
              error={formik.touched.phone ? Boolean(formik.errors.phone) : null}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.phone && Boolean(formik.errors.phone)
                  ? formik.errors.phone
                  : null
              }
            />
          </Grid>
          <Grid>
            <TextField
              id="password"
              label="کلمه عبور"
              variant="outlined"
              sx={{ width: "100%" }}
              value={formik.values.password}
              error={
                formik.touched.password ? Boolean(formik.errors.password) : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.password && Boolean(formik.errors.password)
                  ? formik.errors.password
                  : null
              }
            />
          </Grid>

          <Button
            fullWidth
            color="primary"
            variant="contained"
            onClick={() => {
              dispatch(LOADING_START());
              dispatch(
                inspectorUpdateUserProfile({
                  type: "self_profile",
                  person_type: "operator",
                  userprofile_key: id,
                  fullname: formik.values.fname + " " + formik.values.lname,
                  first_name: formik.values.fname,
                  last_name: formik.values.lname,
                  national_code: formik.values.nationalcode,
                  national_id: formik.values.nationalId,
                  birthday: formik.values.birthday,
                  password: formik.values.password,
                  image: "",
                  // city: cityKey,
                  second_mobile_number: formik.values.phone,
                })
              ).then((r) => {
                if (r.error) {
                  if (r.error.message.includes("403")) {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "مشکلی پیش آمده است!",
                      severity: "error",
                    });
                  } else {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "مشکلی پیش آمده است!",
                      severity: "error",
                    });
                  }
                } else {
                  openNotif({
                    vertical: "top",
                    horizontal: "center",
                    msg: "عملیات با موفقیت انجام شد.",
                    severity: "success",
                  });
                }
                dispatch(LOADING_END());
                dispatch(provinceGetUserByKey(id));
                dispatch(
                  DRAWER({ right: false, bottom: false, content: null })
                );
              });
            }}
          >
            ارسال اطلاعات
          </Button>
        </Grid>
      </Grid>
    </>
  );
};

InspectorEditUserProfile.propTypes = {
  id: PropTypes.any,
  firstName: PropTypes.any,
  lastName: PropTypes.any,
  birthday: PropTypes.any,
  nationalCode: PropTypes.any,
  nationalId: PropTypes.any,
  password: PropTypes.any,
};
