import React, { useContext, useEffect, useState } from "react";
import {
  Grid,
  TextField,
  Button,
  Autocomplete,
  Typography,
} from "@mui/material";
import { useFormik } from "formik";
import * as Yup from "yup";
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 { useDispatch } from "react-redux";
import {
  provinceJahadEditRancher,
  provinceJahadSubmitRancher,
} from "../../services/province-jahad-rancher-activation";
import { SPACING } from "../../../../data/spacing";

const validationSchema = Yup.object({
  mobile: Yup.string()
    .required("این فیلد اجباری است!")
    .min(11, "شماره موبایل باید 11 رقم باشد")
    .max(11, "شماره موبایل باید 11 رقم باشد")
    .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شود و 11 رقم باشد"),
  first_name: Yup.string().required("این فیلد اجباریست!"),
  last_name: Yup.string().required("این فیلد اجباریست!"),
  national_id: Yup.string()
    .required("این فیلد اجباریست!")
    .matches(/^\d{10}$/, "کد ملی باید 10 رقم باشد!"),
  postal_code: Yup.string().required("این فیلد اجباریست!"),
  name: Yup.string().required("این فیلد اجباریست!"),
  epidemiological_code: Yup.string().required("این فیلد اجباریست!"),
  herd_code: Yup.string().required("این فیلد اجباریست!"),
  herd_name: Yup.string().required("این فیلد اجباریست!"),
});

export const ProvinceJahadEditRancher = ({ item, updateTable }) => {
  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 formik = useFormik({
    initialValues: {
      mobile: item?.mobile || "",
      first_name: item?.user?.firstName || "",
      last_name: item?.user?.lastName || "",
      national_id: item?.nationalId || "",
      postal_code: item?.postalCode || "",
      name: item?.name || "",
      epidemiological_code: item?.epidemiologicalCode || "",
      herd_code: item?.herdCode || "",
      herd_name: item?.herdName || "",
    },
    validationSchema: validationSchema,
    onSubmit: (values) => {
      if (item) {
        dispatch(
          provinceJahadEditRancher({
            key: item?.key,
            city: cityKey || item?.city,
            mobile: values.mobile,
            first_name: values.first_name,
            last_name: values.last_name,
            national_id: values.national_id,
            postal_code: values.postal_code,
            name: values.name,
            epidemiological_code: values.epidemiological_code,
            herd_code: values.herd_code,
            herd_name: values.herd_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(
          provinceJahadSubmitRancher({
            city: cityKey,
            mobile: values.mobile,
            first_name: values.first_name,
            last_name: values.last_name,
            national_id: values.national_id,
            postal_code: values.postal_code,
            name: values.name,
            epidemiological_code: values.epidemiological_code,
            herd_code: values.herd_code,
            herd_name: values.herd_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;
    }
  };

  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]);

  return (
    <Grid container direction="column" gap={SPACING.SMALL}>
      <Grid container direction="column" gap={SPACING.TINY}>
        <Grid item xs={12}>
          <TextField
            fullWidth
            id="name"
            name="name"
            label="نام دامداری"
            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}
          />
        </Grid>
        <Grid item xs={12}>
          <TextField
            fullWidth
            id="herd_name"
            name="herd_name"
            label="نام گله"
            value={formik.values.herd_name}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.herd_name && Boolean(formik.errors.herd_name)}
            helperText={formik.touched.herd_name && formik.errors.herd_name}
          />
        </Grid>

        <Grid item xs={12}>
          <TextField
            fullWidth
            id="first_name"
            name="first_name"
            label="نام"
            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}
          />
        </Grid>

        <Grid item xs={12}>
          <TextField
            fullWidth
            id="last_name"
            name="last_name"
            label="نام خانوادگی"
            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}
          />
        </Grid>

        <Grid item xs={12}>
          <TextField
            fullWidth
            id="mobile"
            name="mobile"
            label="موبایل"
            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}
          />
        </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="استان را انتخاب  کنید*" />
          )}
        />

        <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?.city}
          </Typography>
        )}

        <Grid item xs={12}>
          <TextField
            fullWidth
            id="national_id"
            name="national_id"
            label="کد ملی"
            value={formik.values.national_id}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.national_id && Boolean(formik.errors.national_id)
            }
            helperText={formik.touched.national_id && formik.errors.national_id}
          />
        </Grid>

        <Grid item xs={12}>
          <TextField
            fullWidth
            id="postal_code"
            name="postal_code"
            label="کد پستی"
            value={formik.values.postal_code}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.postal_code && Boolean(formik.errors.postal_code)
            }
            helperText={formik.touched.postal_code && formik.errors.postal_code}
          />
        </Grid>

        <Grid item xs={12}>
          <TextField
            fullWidth
            id="epidemiological_code"
            name="epidemiological_code"
            label="کد اپیدمیولوژیک"
            value={formik.values.epidemiological_code}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.epidemiological_code &&
              Boolean(formik.errors.epidemiological_code)
            }
            helperText={
              formik.touched.epidemiological_code &&
              formik.errors.epidemiological_code
            }
          />
        </Grid>

        <Grid item xs={12}>
          <TextField
            fullWidth
            id="herd_code"
            name="herd_code"
            label="کد گله"
            value={formik.values.herd_code}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={formik.touched.herd_code && Boolean(formik.errors.herd_code)}
            helperText={formik.touched.herd_code && formik.errors.herd_code}
          />
        </Grid>
        <Grid item xs={12}>
          <Button
            disabled={!isFormValid()}
            type="submit"
            variant="contained"
            color="primary"
            fullWidth
            onClick={formik.handleSubmit}
          >
            ثبت
          </Button>
        </Grid>
      </Grid>
    </Grid>
  );
};
