import React from "react";
import { PropTypes } from "prop-types";
import { Yup } from "../../../../lib/yup/yup";
import { Grid } from "../../../../components/grid/Grid";
import {
  Autocomplete,
  Button,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  TextField,
} from "@mui/material";

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 { useState } from "react";
import { cityGetCity } from "../../../city/services/city-get-city";
import { useEffect } from "react";
import { cityGetProvinces } from "../../../city/services/CityGetProvinces";

export const InspectorEditOperator = ({
  id,
  address,
  postal,
  name_of_bank_user,
  card,
  shaba,
  account,
  accountHolder,
  type,
}) => {
  const [openNotif] = useContext(AppContext);

  const [provinceData, setProvinceData] = useState();
  const [cityData, setCityData] = useState();
  const [provinceKey, setProvinceKey] = useState();
  const [cityKey, setCityKey] = useState();
  const [isExistProvince, setIsExistProvince] = useState(true);

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(cityGetProvinces())?.then((r) => {
      dispatch(LOADING_END());
      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]);

  const dispatch = useDispatch();
  const formik = useFormik({
    initialValues: {
      address: address ? address : "",
      postal: postal ? postal : "",
      bankName: name_of_bank_user ? name_of_bank_user : "",
      cardNumber: card ? card : "",
      accountNumber: account ? account : "",
      shabaNumber: shaba ? shaba : "",
      accountHolder: accountHolder ? accountHolder : "",
    },
    validationSchema: Yup.object({
      cardNumber: Yup.number().typeError("لطفا شماره کارتتان را وارد کنید!"),
      accountNumber: Yup.number().typeError("لطفا شماره حسابتان را وارد کنید!"),
      shabaNumber: Yup.number().typeError("لطفا شماره شبا را وارد کنید!"),
      accountHolder: Yup.string().typeError("لطفا نام صاحب حساب را وارد کنید!"),
      address: Yup.string().typeError("لطفا نام صاحب حساب را وارد کنید!"),
      postal: Yup.number().typeError("لطفا نام صاحب حساب را وارد کنید!"),
    }),
  });

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

  return (
    <>
      <Grid>
        <Grid container gap={SPACING.SMALL} direction="column">
          <Grid>
            <TextField
              fullWidth
              id="address"
              label="آدرس"
              value={formik.values.address}
              error={
                formik.touched.address ? Boolean(formik.errors.address) : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.address && Boolean(formik.errors.address)
                  ? formik.errors.address
                  : null
              }
              autoComplete="current-password"
              variant="outlined"
            />
          </Grid>

          <Grid>
            <TextField
              fullWidth
              id="postal"
              label="کد پستی"
              value={formik.values.postal}
              error={
                formik.touched.postal ? Boolean(formik.errors.postal) : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.postal && Boolean(formik.errors.postal)
                  ? formik.errors.postal
                  : null
              }
              autoComplete="current-password"
              variant="outlined"
            />
          </Grid>

          <Grid>
            <Autocomplete
              disablePortal
              id="province"
              options={
                provinceData
                  ? 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
                  ? cityData.map((i) => ({ id: i.key, label: i.name }))
                  : []
              }
              onChange={(e, value) => {
                setCityKey(value.id);
              }}
              renderInput={(params) => (
                <TextField {...params} label="شهر را انتخاب  کنید" />
              )}
            />
          </Grid>

          <Grid>
            <FormControl
              fullWidth
              disabled={
                type === "ProvinceOperator" || type === "ProvinceInspector"
              }
            >
              <InputLabel id="demo-simple-select-label">بانک</InputLabel>
              <Select
                fullWidth
                value={formik.values.bankName}
                id="bankName"
                label="بانک"
                onChange={(e) => {
                  formik.setFieldValue("bankName", e.target.value);
                }}
              >
                <MenuItem value={"موسسه افضل توس"}>موسسه افضل توس</MenuItem>
                <MenuItem value={"انصار"}>انصار</MenuItem>
                <MenuItem value={"سپه"}>سپه</MenuItem>
                <MenuItem value={"دی"}>دی</MenuItem>
                <MenuItem value={"کاب"}>اقتصاد نوین</MenuItem>
                <MenuItem value={"گردشگری"}>گردشگری</MenuItem>
                <MenuItem value={"حکمت ایرانیان"}>حکمت ایرانیان</MenuItem>
                <MenuItem value={"ایران زمین"}>ایران زمین</MenuItem>
                <MenuItem value={"کشاورزی"}>کشاورزی</MenuItem>
                <MenuItem value={"مسکن"}>مسکن</MenuItem>
                <MenuItem value={"مهر ایران"}>مهر ایران</MenuItem>
                <MenuItem value={"مهر اقتصاد"}>مهر اقتصاد</MenuItem>
                <MenuItem value={"ملت"}>ملت</MenuItem>
                <MenuItem value={"ملی"}>ملی</MenuItem>
                <MenuItem value={"پارسیان"}>پارسیان</MenuItem>
                <MenuItem value={"پاسارگاد"}>پاسارگاد</MenuItem>
                <MenuItem value={"پست بانک ایران"}>پست بانک ایران</MenuItem>
                <MenuItem value={"صادرات"}>صادرات</MenuItem>
                <MenuItem value={"سامان"}>سامان</MenuItem>
                <MenuItem value={"صنعت و معدن"}>صنعت و معدن</MenuItem>
                <MenuItem value={"سرمایه"}>سرمایه</MenuItem>
                <MenuItem value={"شهر"}>شهر</MenuItem>
                <MenuItem value={"سینا"}>سینا</MenuItem>
                <MenuItem value={"تجارت"}>تجارت</MenuItem>
                <MenuItem value={"موسسه اعتباری توسعه"}>
                  موسسه اعتباری توسعه
                </MenuItem>
                <MenuItem value={"خاورمیانه"}>خاورمیانه</MenuItem>
              </Select>
            </FormControl>
          </Grid>

          <Grid>
            <TextField
              disabled={
                type === "ProvinceOperator" || type === "ProvinceInspector"
              }
              fullWidth
              id="cardNumber"
              label="شماره کارت"
              value={formik.values.cardNumber}
              error={
                formik.touched.cardNumber
                  ? Boolean(formik.errors.cardNumber)
                  : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.cardNumber && Boolean(formik.errors.cardNumber)
                  ? formik.errors.cardNumber
                  : null
              }
              autoComplete="current-password"
              variant="outlined"
            />
          </Grid>

          <Grid>
            <TextField
              disabled={
                type === "ProvinceOperator" || type === "ProvinceInspector"
              }
              fullWidth
              id="accountNumber"
              label="شماره حساب"
              value={formik.values.accountNumber}
              error={
                formik.touched.accountNumber
                  ? Boolean(formik.errors.accountNumber)
                  : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.accountNumber &&
                Boolean(formik.errors.accountNumber)
                  ? formik.errors.accountNumber
                  : null
              }
              autoComplete="current-password"
              variant="outlined"
            />
          </Grid>
          <Grid>
            <TextField
              disabled={
                type === "ProvinceOperator" || type === "ProvinceInspector"
              }
              fullWidth
              id="shabaNumber"
              label="شماره شبا"
              value={formik.values.shabaNumber}
              error={
                formik.touched.shabaNumber
                  ? Boolean(formik.errors.shabaNumber)
                  : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.shabaNumber && Boolean(formik.errors.shabaNumber)
                  ? formik.errors.shabaNumber
                  : null
              }
              autoComplete="current-password"
              variant="outlined"
            />
          </Grid>
          <Grid>
            <TextField
              disabled={
                type === "ProvinceOperator" || type === "ProvinceInspector"
              }
              fullWidth
              id="accountHolder"
              label="نام صاحب حساب"
              value={formik.values.accountHolder}
              error={
                formik.touched.accountHolder
                  ? Boolean(formik.errors.accountHolder)
                  : null
              }
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              helperText={
                formik.touched.accountHolder &&
                Boolean(formik.errors.accountHolder)
                  ? formik.errors.accountHolder
                  : null
              }
              variant="outlined"
            />
          </Grid>
          <Button
            fullWidth
            color="primary"
            variant="contained"
            onClick={() => {
              dispatch(LOADING_START());
              dispatch(
                inspectorUpdateUserProfile({
                  user_bank_info: {
                    name_of_bank_user: formik.values.accountHolder,
                    bank_name: formik.values.bankName,
                    card: formik.values.cardNumber,
                    shaba: formik.values.shabaNumber,
                    account: formik.values.accountNumber,
                  },

                  address: {
                    address: formik.values.address,
                    postal_code: formik.values.postal,
                    city: cityKey,
                    province: provinceKey,
                  },

                  type: type,
                  person_type: "operator",
                  userprofile_key: id,
                })
              ).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>
    </>
  );
};

InspectorEditOperator.propTypes = {
  id: PropTypes.any,
  address: PropTypes.any,
  postal: PropTypes.any,
  name_of_bank_user: PropTypes.any,
  bank_name: PropTypes.any,
  card: PropTypes.any,
  shaba: PropTypes.any,
  account: PropTypes.any,
  accountHolder: PropTypes.any,
  type: PropTypes.any,
};
