import React, { useContext, useEffect, useState } from "react";
import { useFormik } from "formik";
import * as Yup from "yup";
import {
  TextField,
  Button,
  Grid,
  FormControl,
  FormHelperText,
  Select,
  MenuItem,
  InputLabel,
  InputAdornment,
  FormControlLabel,
  Radio,
  RadioGroup,
  Typography,
} from "@mui/material";
import { CarPelak } from "../../../../components/car-pelak/CarPelak";
import { useDispatch, useSelector } from "react-redux";
import { provinceRegisterCarService } from "../../services/province-register-car";
import { AppContext } from "../../../../contexts/AppContext";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import { provinceGetCars } from "../../services/province-get-cars";
import { provinceGetCitiesService } from "../../services/province-get-cities";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceEditCarService } from "../../services/province-edit-car";

const validationSchema = Yup.object({
  driver_mobile: Yup.string().required("شماره موبایل راننده الزامی است"),
  last_name: Yup.string().required("نام خانوادگی الزامی است"),
  first_name: Yup.string().required("نام الزامی است"),
  city_name: Yup.string().required("نام شهر الزامی است"),
  type_car: Yup.string().required("نوع خودرو الزامی است"),
  pelak: Yup.string().required("پلاک الزامی است"),
  capocity: Yup.string().required("ظرفیت الزامی است"),
  health_code: Yup.string().required("کد سلامت الزامی است"),
});

export const ProvinceRegisterCarForm = ({
  first_name,
  last_name,
  driver_mobile,
  city_name,
  type_car,
  pelak,
  capocity,
  health_code,
  driverKey,
  type,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const { provinceGetCities } = useSelector((state) => state.provinceSlice);

  const formik = useFormik({
    initialValues: {
      driver_mobile: driver_mobile,
      last_name: last_name,
      first_name: first_name,
      city_name: city_name,
      type_car: type_car,
      pelak: "",
      capocity: capocity,
      health_code: health_code,
      type: type ? type : "exclusive",
    },
    validationSchema: validationSchema,
    onSubmit: () => {
      // Handle form submission

      handleSubmitForm();
    },
  });

  const [driverPelak, setDriverPelak] = useState([]);

  useEffect(() => {
    if (pelak) {
      const pelakParts = pelak.split(" ");
      setDriverPelak(pelakParts);
    }
  }, [pelak]);

  useEffect(() => {
    formik.setFieldValue(
      "pelak",
      driverPelak.length ? driverPelak.join(" ").trim() : ""
    );
  }, [driverPelak]);

  const handleSubmitForm = () => {
    const { values, errors } = formik;

    if (errors?.length) {
      return;
    }
    if (driverKey) {
      dispatch(
        provinceEditCarService({
          driver_mobile: values.driver_mobile,
          last_name: values.last_name,
          first_name: values.first_name,
          city_name: values.city_name,
          type_car: values.type_car,
          pelak: driverPelak.join(" "),
          capocity: values.capocity,
          health_code: values.health_code,
          role: getRoleFromUrl(),
          driver_key: driverKey,
          type: values.type,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          dispatch(provinceGetCars());
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    } else {
      dispatch(
        provinceRegisterCarService({
          driver_mobile: values.driver_mobile,
          last_name: values.last_name,
          first_name: values.first_name,
          city_name: values.city_name,
          type_car: values.type_car,
          pelak: driverPelak.join(" "),
          capocity: values.capocity,
          health_code: values.health_code,
          role: getRoleFromUrl(),
          type: values.type,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          dispatch(provinceGetCars());
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    }
  };

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

  useEffect(() => {
    dispatch(provinceGetCitiesService()).then(() =>
      formik.setFieldValue("city_name", city_name)
    );
  }, []);

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container spacing={2}>
        <Grid item xs={12}>
          <FormControl fullWidth>
            <TextField
              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}
            />
          </FormControl>
        </Grid>
        <Grid item xs={12}>
          <FormControl fullWidth>
            <TextField
              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}
            />
          </FormControl>
        </Grid>
        <Grid item xs={12}>
          <FormControl fullWidth>
            <TextField
              id="driver_mobile"
              name="driver_mobile"
              label="شماره موبایل راننده"
              value={formik.values.driver_mobile}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={
                formik.touched.driver_mobile &&
                Boolean(formik.errors.driver_mobile)
              }
              helperText={
                formik.touched.driver_mobile && formik.errors.driver_mobile
              }
            />
          </FormControl>
        </Grid>
        {provinceGetCities?.length && (
          <Grid item xs={12}>
            <FormControl fullWidth>
              <InputLabel id="demo-simple-select-label">شهر</InputLabel>
              <Select
                id="city_name"
                name="city_name"
                onChange={formik.handleChange}
                label="شهر"
                onBlur={formik.handleBlur}
                value={formik.values.city_name}
                error={
                  formik.touched.city_name && Boolean(formik.errors.city_name)
                }
                // displayEmpty
                renderValue={(selected) => (selected ? selected : "نام شهر")}
              >
                <MenuItem value="" disabled>
                  نام شهر
                </MenuItem>
                {provinceGetCities.map((city) => (
                  <MenuItem key={city.id} value={city.name}>
                    {city.name}
                  </MenuItem>
                ))}
              </Select>
              {formik.touched.city_name && formik.errors.city_name && (
                <FormHelperText error>{formik.errors.city_name}</FormHelperText>
              )}
            </FormControl>
          </Grid>
        )}

        <Grid item xs={12}>
          <FormControl fullWidth>
            <InputLabel id="demo-simple-select-label">نوع خودرو</InputLabel>
            <Select
              id="type_car"
              name="type_car"
              label="نوع خودرو"
              value={formik.values.type_car}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={formik.touched.type_car && Boolean(formik.errors.type_car)}
              renderValue={(selected) => selected || "انتخاب نوع خودرو"}
            >
              <MenuItem value="" disabled>
                انتخاب نوع خودرو
              </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>
            {formik.touched.type_car && formik.errors.type_car && (
              <FormHelperText error>{formik.errors.type_car}</FormHelperText>
            )}
          </FormControl>
        </Grid>
        <Grid item xs={12} alignItems="center" justifyContent={"center"}>
          <CarPelak
            width="100%"
            pelakState={driverPelak}
            handleChange={carPelakHandleChange}
          />
        </Grid>
        <Grid item xs={12}>
          <FormControl fullWidth>
            <TextField
              id="capocity"
              name="capocity"
              label="ظرفیت"
              type="number"
              InputProps={{
                endAdornment: (
                  <InputAdornment position="start">کیلوگرم</InputAdornment>
                ),
              }}
              value={formik.values.capocity}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={formik.touched.capocity && Boolean(formik.errors.capocity)}
              helperText={formik.touched.capocity && formik.errors.capocity}
            />
          </FormControl>
        </Grid>
        <Grid item xs={12}>
          <FormControl fullWidth>
            <TextField
              id="health_code"
              name="health_code"
              label="کد بهداشتی"
              value={formik.values.health_code}
              onChange={formik.handleChange}
              onBlur={formik.handleBlur}
              error={
                formik.touched.health_code && Boolean(formik.errors.health_code)
              }
              helperText={
                formik.touched.health_code && formik.errors.health_code
              }
            />
          </FormControl>
        </Grid>
        <Grid item xs={12}>
          <Typography>ماهیت خودرو</Typography>
          <FormControl
            component="fieldset"
            disabled={
              getRoleFromUrl() === "ProvinceOperator" ||
              getRoleFromUrl() === "SuperAdmin" ||
              getRoleFromUrl() === "AdminX"
                ? false
                : type
                ? type === "rental"
                : false
            }
          >
            <RadioGroup
              name="type"
              value={formik.values.type}
              onChange={formik.handleChange}
            >
              {(getRoleFromUrl() === "ProvinceOperator" ||
                getRoleFromUrl() === "SuperAdmin" ||
                getRoleFromUrl() === "AdminX") && (
                <FormControlLabel
                  value="rental"
                  control={<Radio />}
                  label={
                    <Grid container>
                      <Typography>
                        اجاره ای{" "}
                        <Typography variant="caption">
                          (نمایش برای تمام کشتارگاه ها)
                        </Typography>
                      </Typography>
                    </Grid>
                  }
                />
              )}

              <FormControlLabel
                value="exclusive"
                control={<Radio />}
                label="اختصاصی"
              />
            </RadioGroup>
          </FormControl>
        </Grid>
        <Grid item xs={12}>
          <Button
            // onClick={handleSubmitForm}
            fullWidth
            variant="contained"
            color="primary"
            type="submit"
          >
            ارسال
          </Button>
        </Grid>
      </Grid>
    </form>
  );
};
