import React, { useContext, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  TextField,
  Radio,
  RadioGroup,
  FormControlLabel,
} from "@mui/material";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { provincePolicyEditFinePermission } from "../../services/province-policy-edit-fine-permission";
import TimePicker from "../../../../components/date-picker/CustomDatePicker";

export const ProvincePolicyEditFine = ({ item, fetchData }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  const [range, setRange] = useState({
    start_time: item?.startTime || "01:00:00",
    end_time: item?.endTime || "24:00:00",
    fine: item?.fine || false,
  });

  const formik = useFormik({
    initialValues: {
      fine_coefficient: item?.fineCoefficient || 0,
    },
    validationSchema: Yup.object({
      fine_coefficient: Yup.number()
        .typeError("لطفا فیلد را به صورت عددی وارد کنید!")
        .required("این فیلد اجباری است!"),
    }),
    onSubmit: async (values) => {
      const payload = {
        key: item?.key,
        fine: range.fine,
        start_time: range.fine ? range.start_time : "00:00:00",
        end_time: range.fine ? range.end_time : "00:00:00",
        fine_coefficient: range.fine ? values.fine_coefficient : 0,
      };

      dispatch(provincePolicyEditFinePermission(payload)).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",
          });
          fetchData();
          dispatch(CLOSE_MODAL());
        }
      });
    },
  });

  return (
    <Grid container xs={12} direction="column" justifyContent="center">
      <form onSubmit={formik.handleSubmit}>
        <Grid container xs={12} gap={2} direction="column">
          <Grid item display="flex" justifyContent="start">
            <RadioGroup
              row
              value={range.fine ? "active" : "inactive"}
              onChange={(e) =>
                setRange((prev) => ({
                  ...prev,
                  fine: e.target.value === "active",
                }))
              }
            >
              <FormControlLabel
                value="active"
                control={<Radio />}
                label="فعال"
              />
              <FormControlLabel
                value="inactive"
                control={<Radio />}
                label="غیرفعال"
              />
            </RadioGroup>
          </Grid>

          {range.fine && (
            <Grid
              item
              display="flex"
              alignItems="center"
              sx={{
                flexDirection: {
                  xs: "column",
                  md: "row",
                },
              }}
              gap={2}
            >
              <TextField
                id="fine_coefficient"
                size="small"
                label="ضریب جریمه"
                variant="outlined"
                value={formik.values.fine_coefficient}
                error={
                  formik.touched.fine_coefficient
                    ? Boolean(formik.errors.fine_coefficient)
                    : null
                }
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
                helperText={
                  formik.touched.fine_coefficient &&
                  formik.errors.fine_coefficient
                    ? formik.errors.fine_coefficient
                    : null
                }
                sx={{ width: 363, marginTop: "26px" }}
              />
              <Grid item display="flex" alignItems="center" gap={2}>
                <TimePicker
                  value={range.start_time}
                  onChange={(newTime) =>
                    setRange((prev) => ({ ...prev, start_time: newTime }))
                  }
                  label="از"
                />
                <TimePicker
                  value={range.end_time}
                  onChange={(newTime) =>
                    setRange((prev) => ({ ...prev, end_time: newTime }))
                  }
                  label="تا"
                />
              </Grid>
            </Grid>
          )}

          <Button variant="contained" fullWidth type="submit">
            ویرایش
          </Button>
        </Grid>
      </form>
    </Grid>
  );
};
