import React, { useContext, useEffect, useState } from "react";
import { Button, Checkbox, FormControlLabel, TextField } from "@mui/material";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { getKillhouseApprovedPriceState } from "../../services/get-approved-price-state";
import { provinceEditKillhouseApprovedPrice } from "../../services/province-edit-approved-price";
import { AppContext } from "../../../../contexts/AppContext";
import { Grid } from "../../../../components/grid/Grid";

export const ProvincePolicyApprovedKillHousePrice = ({ approvedState }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [checked, setChecked] = useState(false);
  const [data, setData] = useState();

  useEffect(() => {
    dispatch(getKillhouseApprovedPriceState()).then((r) => {
      setData(r.payload.data);
      if (r.payload.data?.active) {
        setChecked(true);
      }
    });
  }, []);

  const formik = useFormik({
    initialValues: {
      kill_house_price: "",
      steward_price: "",
      guild_price: "",
    },
    validationSchema: Yup.object({
      kill_house_price: Yup.number().required("این فیلد اجباری است"),
      steward_price: Yup.number().required("این فیلد اجباری است"),
      guild_price: Yup.number().required("این فیلد اجباری است"),
    }),
  });

  useEffect(() => {
    formik.validateForm();
  }, []);

  useEffect(() => {
    if (data?.killHousePrice && checked) {
      formik.setFieldValue("kill_house_price", data?.killHousePrice);
      formik.setFieldValue("steward_price", data?.stewardPrice);
      formik.setFieldValue("guild_price", data?.guildPrice);
    }
  }, [data]);

  const handleChange = (event) => {
    setChecked(event.target.checked);
    if (event.target.checked === false) {
      dispatch(
        provinceEditKillhouseApprovedPrice({
          active: false,
        })
      ).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",
          });
        }
      });
    }
  };

  useEffect(() => {
    if (checked && approvedState) {
      setChecked(false);
      dispatch(
        provinceEditKillhouseApprovedPrice({
          active: false,
        })
      );
    }
  }, [approvedState]);

  return (
    <Grid
      container
      xs={12}
      alignItems="center"
      justifyContent="space-between"
      direction="column"
    >
      <Grid
        container
        xs={12}
        gap={2}
        alignItems="center"
        justifyContent="start"
      >
        <Grid container direction="column" textAlign="initial">
          <Grid>
            <FormControlLabel
              control={<Checkbox checked={checked} onChange={handleChange} />}
              label="قیمت مصوب کشتارگاه، صنف و مباشر"
            />
          </Grid>
        </Grid>
        {checked && (
          <>
            <Grid container xs={12} md={4} lg={4} spacing={1}>
              <Grid>
                <TextField
                  size="small"
                  label="قیمت کشتارگاه"
                  name="kill_house_price"
                  value={formik.values.kill_house_price}
                  onChange={formik.handleChange}
                  error={
                    formik.touched.kill_house_price &&
                    Boolean(formik.errors.kill_house_price)
                  }
                  helperText={
                    formik.touched.kill_house_price &&
                    formik.errors.kill_house_price
                  }
                  required
                />
              </Grid>

              <Grid>
                <TextField
                  size="small"
                  label="قیمت مباشر"
                  name="steward_price"
                  value={formik.values.steward_price}
                  onChange={formik.handleChange}
                  error={
                    formik.touched.steward_price &&
                    Boolean(formik.errors.steward_price)
                  }
                  helperText={
                    formik.touched.steward_price && formik.errors.steward_price
                  }
                  required
                />
              </Grid>

              <Grid>
                <TextField
                  size="small"
                  label="قیمت صنف"
                  name="guild_price"
                  value={formik.values.guild_price}
                  onChange={formik.handleChange}
                  error={
                    formik.touched.guild_price &&
                    Boolean(formik.errors.guild_price)
                  }
                  helperText={
                    formik.touched.guild_price && formik.errors.guild_price
                  }
                  required
                />
              </Grid>
            </Grid>
            <Grid container xs={12} md={2}>
              <Button
                disabled={!formik.isValid}
                variant="contained"
                onClick={() => {
                  dispatch(
                    provinceEditKillhouseApprovedPrice({
                      active: true,
                      guild_price: formik.values.guild_price,
                      kill_house_price: formik.values.kill_house_price,
                      steward_price: formik.values.steward_price,
                    })
                  ).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",
                      });
                    }
                  });
                }}
              >
                ثبت
              </Button>
            </Grid>
          </>
        )}
      </Grid>
    </Grid>
  );
};
