import React, { useContext, useEffect, useState } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import {
  Button,
  Checkbox,
  FormControl,
  FormControlLabel,
  FormLabel,
  MenuItem,
  Radio,
  RadioGroup,
  TextField,
} from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { provinceGetCitiesService } from "../../services/province-get-cities";
import { provinceGetFieldOfWorks } from "../../services/ProvinceGetFieldOfWorks";
import { provinceGetTypeActivity } from "../../services/provinceGetTypeActivity";
import { SPACING } from "../../../../data/spacing";
import { Grid } from "../../../../components/grid/Grid";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { provinceDispensersCreateSteward } from "../../services/province-dispensers-services";
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("نام خانوادگی الزامی است"),
  national_id: yup.string().required("کدملی الزامی است"),
  postal_code: yup.string().required("کدپستی الزامی است"),
  city: yup.string().required("شهر الزامی است"),
  address: yup.string().required("آدرس الزامی است"),
  guilds_id: yup.string().required("شناسه انجمن الزامی است"),
  license_number: yup.string().required("شماره مجوز الزامی است"),
  guilds_name: yup.string().required("نام انجمن الزامی است"),
  type_activity: yup.string().required("نوع فعالیت الزامی است"),
  area_activity: yup.string().required("حوزه فعالیت الزامی است"),
  allocation_limit: yup.string().required("این فیلد الزامی است"),
});

export const ProvinceCreateAllocateStewardGuild = ({
  killHousekey,
  type,
  updateTable,
  item,
}) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const { provinceGetCities, provinceGetAreActivity, provinceTypeActivity } =
    useSelector((state) => state.provinceSlice);

  const formik = useFormik({
    initialValues: {
      mobile: item ? item.user.mobile : "",
      first_name: item ? item.user.firstName : "",
      last_name: item ? item.user.lastName : "",
      city: item ? item.address.city.name : "",
      address: item ? item.address.address : "",
      guilds_id: item ? item.guildsId : "",
      license_number: item ? item.licenseNumber : "",
      postal_code: item ? item.address.postalCode : "",
      guilds_name: item ? item.guildsName : "",
      type_activity: item ? item.typeActivity : "",
      area_activity: item ? item.areaActivity : "",
      steward: item ? item.steward : false,
      national_id: item ? item.user.nationalId : "",
      allocation_limit: item ? item.allocation_limit : "",
    },
    validationSchema,
    onSubmit: (values) => {
      dispatch(
        provinceDispensersCreateSteward({
          ...values,
          role: getRoleFromUrl(),
          allocation_type: value,
          owner_key: killHousekey,
          role_type: type,
        })
      ).then((r) => {
        if (r.payload.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: r.payload.error,
            severity: "error",
          });
        } else {
          updateTable();
          dispatch(DRAWER({ right: false, bottom: false, content: null }));
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    },
  });

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

  const [value, setValue] = useState("forced");

  const handleChangeRadioButton = (event) => {
    setValue(event.target.value);
  };

  return (
    <form onSubmit={formik.handleSubmit}>
      <Grid container gap={SPACING.SMALL}>
        <TextField
          label="نام"
          variant="outlined"
          fullWidth
          id="first_name"
          name="first_name"
          value={formik.values.first_name}
          onChange={formik.handleChange}
          error={formik.touched.first_name && Boolean(formik.errors.first_name)}
          helperText={formik.touched.first_name && formik.errors.first_name}
        />
        <TextField
          label="نام خانوادگی"
          variant="outlined"
          fullWidth
          id="last_name"
          name="last_name"
          value={formik.values.last_name}
          onChange={formik.handleChange}
          error={formik.touched.last_name && Boolean(formik.errors.last_name)}
          helperText={formik.touched.last_name && formik.errors.last_name}
        />
        <TextField
          label="کدملی"
          variant="outlined"
          fullWidth
          id="national_id"
          name="national_id"
          value={formik.values.national_id}
          onChange={formik.handleChange}
          error={
            formik.touched.national_id && Boolean(formik.errors.national_id)
          }
          helperText={formik.touched.national_id && formik.errors.national_id}
        />
        <TextField
          label="تلفن"
          variant="outlined"
          fullWidth
          id="mobile"
          name="mobile"
          value={formik.values.mobile}
          onChange={formik.handleChange}
          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
          label="کدپستی"
          variant="outlined"
          fullWidth
          id="postal_code"
          name="postal_code"
          value={formik.values.postal_code}
          onChange={formik.handleChange}
          error={
            formik.touched.postal_code && Boolean(formik.errors.postal_code)
          }
          helperText={formik.touched.postal_code && formik.errors.postal_code}
        />

        <TextField
          label="آدرس"
          variant="outlined"
          fullWidth
          id="address"
          name="address"
          value={formik.values.address}
          onChange={formik.handleChange}
          error={formik.touched.address && Boolean(formik.errors.address)}
          helperText={formik.touched.address && formik.errors.address}
        />
        <TextField
          label="نام واحد صنفی"
          variant="outlined"
          fullWidth
          id="guilds_name"
          name="guilds_name"
          value={formik.values.guilds_name}
          onChange={formik.handleChange}
          error={
            formik.touched.guilds_name && Boolean(formik.errors.guilds_name)
          }
          helperText={formik.touched.guilds_name && formik.errors.guilds_name}
        />

        <TextField
          select
          label="نوع فعالیت"
          variant="outlined"
          fullWidth
          id="type_activity"
          name="type_activity"
          value={formik.values.type_activity}
          onChange={formik.handleChange}
          error={
            formik.touched.type_activity && Boolean(formik.errors.type_activity)
          }
          helperText={
            formik.touched.type_activity && formik.errors.type_activity
          }
        >
          {provinceTypeActivity?.map((option) => (
            <MenuItem key={option.title} value={option.title}>
              {option.title}
            </MenuItem>
          ))}
        </TextField>

        <TextField
          select
          label="حوزه فعالیت"
          variant="outlined"
          fullWidth
          id="area_activity"
          name="area_activity"
          value={formik.values.area_activity}
          onChange={formik.handleChange}
          error={
            formik.touched.area_activity && Boolean(formik.errors.area_activity)
          }
          helperText={
            formik.touched.area_activity && formik.errors.area_activity
          }
        >
          {provinceGetAreActivity?.map((option) => (
            <MenuItem key={option.title} value={option.title}>
              {option.title}
            </MenuItem>
          ))}
        </TextField>
        <TextField
          label="شناسه صنف"
          variant="outlined"
          fullWidth
          id="guilds_id"
          name="guilds_id"
          value={formik.values.guilds_id}
          onChange={formik.handleChange}
          error={formik.touched.guilds_id && Boolean(formik.errors.guilds_id)}
          helperText={formik.touched.guilds_id && formik.errors.guilds_id}
        />
        <TextField
          label="شماره مجوز"
          variant="outlined"
          fullWidth
          id="license_number"
          name="license_number"
          value={formik.values.license_number}
          onChange={formik.handleChange}
          error={
            formik.touched.license_number &&
            Boolean(formik.errors.license_number)
          }
          helperText={
            formik.touched.license_number && formik.errors.license_number
          }
        />

        <Grid item xs={12}>
          <TextField
            fullWidth
            id="allocation_limit"
            label="وزن تعهد روزانه"
            variant="outlined"
            sx={{ width: "100%" }}
            value={formik.values.allocation_limit}
            error={
              formik.touched.allocation_limit
                ? Boolean(formik.errors.allocation_limit)
                : null
            }
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
            helperText={
              formik.touched.allocation_limit &&
              Boolean(formik.errors.allocation_limit)
                ? formik.errors.allocation_limit
                : null
            }
          />
        </Grid>

        <Grid xs={12} item>
          <FormControl>
            <FormLabel id="demo-radio-buttons-group-label">نوع تعهد</FormLabel>

            <RadioGroup
              aria-labelledby="demo-controlled-radio-buttons-group"
              name="controlled-radio-buttons-group"
              value={value}
              onChange={handleChangeRadioButton}
            >
              <FormControlLabel
                value="forced"
                control={<Radio />}
                label="اجباری"
              />
              <FormControlLabel
                value="optional"
                control={<Radio />}
                label="اختیاری"
              />
            </RadioGroup>
          </FormControl>
        </Grid>

        {getRoleFromUrl() !== "Guilds" && (
          <FormControlLabel
            control={
              <Checkbox
                name="steward"
                checked={formik.values.steward}
                onChange={formik.handleChange}
                label="مباشر"
              />
            }
            label="مباشر"
          />
        )}

        {formik.errors.steward && <div>{formik.errors.steward}</div>}

        <Button color="primary" fullWidth variant="contained" type="submit">
          ثبت
        </Button>
      </Grid>
    </form>
  );
};
