import React, { useContext, useEffect, useState } from "react";
import { useFormik } from "formik";
import * as Yup from "yup";
import {
  Grid,
  TextField,
  Button,
  Autocomplete,
  Typography,
} from "@mui/material";

import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { cityGetProvinces } from "../../../city/services/CityGetProvinces";
import { cityGetCity } from "../../../city/services/city-get-city";
import {
  provinceJahadSubmitUnionService,
  provinceJahadUpdateUnionService,
} from "../../services/province-jahad-edit-union";
import { SPACING } from "../../../../data/spacing";

export const ProvinceJahadUnionsSubmit = ({ updateTable, item }) => {
  const [provinceData, setProvinceData] = useState([]);
  const [cityData, setCityData] = useState([]);
  const [provinceKey, setProvinceKey] = useState();
  const [cityKey, setCityKey] = useState();
  const [isExistProvince, setIsExistProvince] = useState(true);
  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();

  const validationSchema = Yup.object().shape({
    name: Yup.string().required("این فیلد الزامی است"),
    first_name: Yup.string().required("این فیلد الزامی است"),
    last_name: Yup.string().required("این فیلد الزامی است"),
    address: Yup.string().required("این فیلد الزامی است"),
    nationalId: Yup.string()
      .matches(/^\d+$/, "لطفا فقط عدد وارد کنید")
      .length(10, "کد ملی باید ۱۰ رقم باشد")
      .required("این فیلد الزامی است"),
    postalCode: Yup.string()
      .matches(/^\d+$/, "لطفا فقط عدد وارد کنید")
      .length(10, "کد پستی باید ۱۰ رقم باشد")
      .required("این فیلد الزامی است"),
    mobile: Yup.string()
      .matches(/^\d+$/, "لطفا فقط عدد وارد کنید")
      .length(11, "شماره موبایل باید ۱۱ رقم باشد")
      .required("این فیلد الزامی است"),
  });

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

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

  const formik = useFormik({
    initialValues: {
      name: item?.name || "",
      first_name: item?.user?.firstName || "",
      last_name: item?.user?.lastName || "",
      mobile: item?.user?.mobile || "",
      address: item?.address?.address || "",
      nationalId: item?.nationalId || "",
      postalCode: item?.address?.postalCode || "",
    },
    validationSchema,
    enableReinitialize: true,
    onSubmit: (values) => {
      if (item) {
        dispatch(
          provinceJahadUpdateUnionService({
            union_key: item?.key,
            first_name: values.first_name,
            last_name: values.last_name,
            name: values.name,
            address: values.address,
            mobile: values.mobile,
            national_id: values.nationalId,
            postal_code: values.postalCode,
            city: cityKey || item?.address?.city?.name,
          })
        ).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
            dispatch(DRAWER({ right: false, bottom: false, content: null }));

            updateTable();
          }
        });
      } else {
        dispatch(
          provinceJahadSubmitUnionService({
            first_name: values.first_name,
            last_name: values.last_name,
            name: values.name,
            address: values.address,
            mobile: values.mobile,
            national_id: values.nationalId,
            postal_code: values.postalCode,
            city: cityKey || item?.address?.city?.name,
          })
        ).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
            dispatch(DRAWER({ right: false, bottom: false, content: null }));

            updateTable();
          }
        });
      }
    },
  });

  const isFormValid = () => {
    if (item) {
      return formik.isValid;
    } else {
      return formik.isValid && cityKey;
    }
  };

  return (
    <Grid container direction="column" gap={SPACING.SMALL}>
      <form onSubmit={formik.handleSubmit}>
        <Grid container direction="column" gap={SPACING.TINY}>
          <TextField
            name="name"
            label=" نام اتحادیه"
            fullWidth
            value={formik.values.name}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.name && Boolean(formik.errors.name)}
            helperText={formik.touched.name && formik.errors.name}
          />

          <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="استان را انتخاب  کنید*" />
            )}
          />

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

          <TextField
            name="first_name"
            label="نام "
            fullWidth
            value={formik.values.first_name}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.first_name && Boolean(formik.errors.first_name)
            }
            helperText={formik.touched.first_name && formik.errors.first_name}
          />

          <TextField
            name="last_name"
            label=" نام خانوادگی"
            fullWidth
            value={formik.values.last_name}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.last_name && Boolean(formik.errors.last_name)}
            helperText={formik.touched.last_name && formik.errors.last_name}
          />

          <TextField
            name="mobile"
            label="تلفن"
            fullWidth
            value={formik.values.mobile}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.mobile && Boolean(formik.errors.mobile)}
            helperText={formik.touched.mobile && formik.errors.mobile}
          />

          <TextField
            name="address"
            label="آدرس "
            fullWidth
            value={formik.values.address}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.address && Boolean(formik.errors.address)}
            helperText={formik.touched.address && formik.errors.address}
          />

          <TextField
            name="nationalId"
            label="کد ملی"
            inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }}
            fullWidth
            value={formik.values.nationalId}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.nationalId && Boolean(formik.errors.nationalId)
            }
            helperText={formik.touched.nationalId && formik.errors.nationalId}
          />

          <TextField
            name="postalCode"
            label="کد پستی"
            fullWidth
            inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }}
            value={formik.values.postalCode}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.postalCode && Boolean(formik.errors.postalCode)
            }
            helperText={formik.touched.postalCode && formik.errors.postalCode}
          />

          <Button
            type="submit"
            variant="contained"
            color="primary"
            disabled={!isFormValid()}
          >
            ثبت اطلاعات
          </Button>
        </Grid>
      </form>
    </Grid>
  );
};
