import React, { useContext, useEffect, useState } from "react";
import { useFormik } from "formik";
import * as Yup from "yup";
import {
  TextField,
  Button,
  RadioGroup,
  FormControlLabel,
  Radio,
  FormControl,
  FormLabel,
  Box,
  MenuItem,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import {
  slaughterHouseEditDispenserService,
  slaughterHouseSubmitDispenserService,
} from "../../services/slaughter-house-submit-dispenser-service";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceGetCitiesService } from "../../../province/services/province-get-cities";
import { CarPelak } from "../../../../components/car-pelak/CarPelak";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";

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("این فیلد اجباریست!"),
  city: Yup.string().required("این فیلد اجباریست!"),
  national_id: Yup.string()
    .matches(/^\d{10}$/, "کد ملی ده رقمی است!")
    .required("این فیلد اجباریست!"),
  dispenser_type: Yup.string().required("این فیلد اجباریست!"),
  limitation_amount: Yup.number()
    .min(0, "عدد مثبت وارد کنید!")
    .required("سقف محدودیت اجباری است"),
  driver_car_type: Yup.string().when("dispenser_type", {
    is: "driver",
    then: Yup.string().required("نوع خودرو اجباری است!"),
  }),
});

export const SlaughterHouseSubmitDispenser = ({
  updateTable,
  isEdit,
  item,
}) => {
  const dispatch = useDispatch();
  const { provinceGetCities } = useSelector((state) => state.provinceSlice);
  const [driverPelak, setDriverPelak] = useState([]);

  const carPelakHandleChange = (pelak1, pelak2, pelak3, pelak4) => {
    setDriverPelak([pelak1, pelak2, pelak3, pelak4]);
  };
  const [openNotif] = useContext(AppContext);

  useEffect(() => {
    dispatch(provinceGetCitiesService());
  }, []);

  const formik = useFormik({
    initialValues: {
      mobile: item?.user?.mobile ? item?.user?.mobile : "",
      first_name: item?.user?.firstName ? item?.user?.firstName : "",
      last_name: item?.user?.lastName ? item?.user?.lastName : "",
      city: item?.user?.city?.cityName ? item?.user?.city?.cityName : "",
      national_id: item?.user?.nationalId ? item?.user?.nationalId : "",
      dispenser_type: item?.dispenserType ? item?.dispenserType : "inductor",
      limitation_amount: item?.limitation_amount ? item?.limitation_amount : 0,
      driver_car_type: item?.car ? item?.car : "",
    },
    validationSchema,
    onSubmit: (values) => {
      if (!isEdit) {
        dispatch(
          slaughterHouseSubmitDispenserService({
            mobile: values.mobile,
            first_name: values.first_name,
            last_name: values.last_name,
            city: values.city,
            national_id: values.national_id,
            dispenser_type: values.dispenser_type,
            limitation_amount: values.limitation_amount,
            role: getRoleFromUrl(),
            pelak:
              values.dispenser_type === "driver"
                ? driverPelak[0] +
                  " " +
                  driverPelak[1] +
                  " " +
                  driverPelak[2] +
                  " " +
                  driverPelak[3]
                : null,
            car: values.driver_car_type ? values.driver_car_type : null,
          })
        ).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            dispatch(DRAWER({ right: false, bottom: false, content: null }));
            updateTable();
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
          }
        });
      } else {
        dispatch(
          slaughterHouseEditDispenserService({
            type: "update-profile",
            dispenser_key: item?.key,
            mobile: values.mobile,
            first_name: values.first_name,
            last_name: values.last_name,
            city: values.city,
            national_id: values.national_id,
            dispenser_type: values.dispenser_type,
            limitation_amount: values.limitation_amount,
            role: getRoleFromUrl(),
            pelak:
              values.dispenser_type === "driver"
                ? driverPelak[0] +
                  " " +
                  driverPelak[1] +
                  " " +
                  driverPelak[2] +
                  " " +
                  driverPelak[3]
                : null,
            car: values.driver_car_type ? values.driver_car_type : null,
          })
        ).then((r) => {
          if (r.payload.error) {
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: r.payload.error,
              severity: "error",
            });
          } else {
            dispatch(DRAWER({ right: false, bottom: false, content: null }));
            updateTable();
            openNotif({
              vertical: "top",
              horizontal: "center",
              msg: "عملیات با موفقیت انجام شد.",
              severity: "success",
            });
          }
        });
      }
    },
  });

  return (
    <Box
      component="form"
      onSubmit={formik.handleSubmit}
      sx={{ display: "flex", flexDirection: "column", gap: 2 }}
    >
      <TextField
        fullWidth
        label="نام"
        name="first_name"
        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
        fullWidth
        label="نام خانوادگی"
        name="last_name"
        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
        fullWidth
        label="موبایل"
        name="mobile"
        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
        select
        label="شهر"
        variant="outlined"
        fullWidth
        id="city"
        name="city"
        value={formik.values.city}
        onChange={formik.handleChange}
        error={formik.touched.city && Boolean(formik.errors.city)}
        helperText={formik.touched.city && formik.errors.city}
      >
        {provinceGetCities?.map((city) => (
          <MenuItem key={city.id} value={city.name}>
            {city.name}
          </MenuItem>
        ))}
      </TextField>

      <TextField
        fullWidth
        label="کد ملی"
        name="national_id"
        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}
      />
      <FormControl component="fieldset">
        <FormLabel component="legend">ماهیت</FormLabel>
        <RadioGroup
          name="dispenser_type"
          value={formik.values.dispenser_type}
          onChange={formik.handleChange}
        >
          <FormControlLabel
            value="inductor"
            control={<Radio />}
            label="واسطه"
          />
          <FormControlLabel
            value="salesman"
            control={<Radio />}
            label="فروشنده"
          />
          <FormControlLabel value="driver" control={<Radio />} label="راننده" />
        </RadioGroup>
      </FormControl>
      {formik.values.dispenser_type === "driver" && (
        <>
          <TextField
            fullWidth
            label="نوع خودرو"
            name="driver_car_type"
            value={formik.values.driver_car_type}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            error={
              formik.touched.driver_car_type &&
              Boolean(formik.errors.driver_car_type)
            }
            helperText={
              formik.touched.driver_car_type && formik.errors.driver_car_type
            }
          />
          <Grid item xs={12} alignItems="center" justifyContent={"center"}>
            <CarPelak
              width="100%"
              handleChange={carPelakHandleChange}
              pelakInitial={isEdit ? item?.pelak : ""}
            />
          </Grid>
        </>
      )}
      <TextField
        fullWidth
        label="سقف محدودیت"
        name="limitation_amount"
        type="number"
        value={formik.values.limitation_amount}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
        error={
          formik.touched.limitation_amount &&
          Boolean(formik.errors.limitation_amount)
        }
        helperText={
          formik.touched.limitation_amount && formik.errors.limitation_amount
        }
      />
      <Button
        color="primary"
        variant="contained"
        type="submit"
        disabled={
          formik.values.dispenser_type === "driver" ? !driverPelak[1] : false
        }
      >
        ثبت
      </Button>
    </Box>
  );
};
