import React, { useContext, useEffect, useState } from "react";
import { Grid } from "../../../../components/grid/Grid";
import {
  Button,
  Checkbox,
  Divider,
  FormControlLabel,
  TextField,
} from "@mui/material";
import { Yup } from "../../../../lib/yup/yup";
import { useFormik } from "formik";
import { useDispatch } from "react-redux";
import { getApprovedPriceState } from "../../services/get-approved-price-state";
import { provinceEditApprovedPrice } from "../../services/province-edit-approved-price";
import { AppContext } from "../../../../contexts/AppContext";
import { ProvincePolicyAvicultureCommit } from "../province-policy-aviculture-commit/ProvincePolicyAvicultureCommit";
import { ProvincePolicyApprovedKillHousePrice } from "../province-policy-approved-killhouse-price/ProvincePolicyApprovedKillHousePrice";

export const ProvincePolicyApprovedPrice = () => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [checked, setChecked] = useState(false);
  const [killHousePriceCheck, setKillHousePriceCheck] = useState(false);
  const [data, setData] = useState();

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

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

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

  useEffect(() => {
    if (data?.highestPrice && checked) {
      formik.setFieldValue("minWeight", data?.lowestWeight);
      formik.setFieldValue("maxWeight", data?.highestWeight);
      formik.setFieldValue("minPrice", data?.lowestPrice);
      formik.setFieldValue("maxPrice", data?.highestPrice);
    }
  }, [data]);

  const handleChange = (event) => {
    setChecked(event.target.checked);
    if (event.target.checked === false) {
      setKillHousePriceCheck(true);
      dispatch(
        provinceEditApprovedPrice({
          approved: false,
        })
      ).then((r) => {
        if (r.error) {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "مشکلی پیش آمده است!",
            severity: "error",
          });
        } else {
          openNotif({
            vertical: "top",
            horizontal: "center",
            msg: "عملیات با موفقیت انجام شد.",
            severity: "success",
          });
        }
      });
    }
  };

  return (
    <Grid
      container
      xs={12}
      alignItems="center"
      justifyContent="space-between"
      direction="column"
      mt={4}
    >
      <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 xs={6}>
                <TextField
                  size="small"
                  label="وزن کف (گرم)"
                  name="minWeight"
                  value={formik.values.minWeight}
                  onChange={formik.handleChange}
                  error={
                    formik.touched.minWeight && Boolean(formik.errors.minWeight)
                  }
                  helperText={
                    formik.touched.minWeight && formik.errors.minWeight
                  }
                  required
                />
              </Grid>

              <Grid xs={6}>
                <TextField
                  size="small"
                  label="وزن سقف (گرم)"
                  name="maxWeight"
                  value={formik.values.maxWeight}
                  onChange={formik.handleChange}
                  error={
                    formik.touched.maxWeight && Boolean(formik.errors.maxWeight)
                  }
                  helperText={
                    formik.touched.maxWeight && formik.errors.maxWeight
                  }
                  required
                />
              </Grid>

              <Grid xs={6}>
                <TextField
                  size="small"
                  label="قیمت وزن کف (ریال)"
                  name="minPrice"
                  value={formik.values.minPrice}
                  onChange={formik.handleChange}
                  error={
                    formik.touched.minPrice && Boolean(formik.errors.minPrice)
                  }
                  helperText={formik.touched.minPrice && formik.errors.minPrice}
                  required
                />
              </Grid>

              <Grid xs={6}>
                <TextField
                  size="small"
                  label="قیمت وزن سقف (ریال)"
                  name="maxPrice"
                  value={formik.values.maxPrice}
                  onChange={formik.handleChange}
                  error={
                    formik.touched.maxPrice && Boolean(formik.errors.maxPrice)
                  }
                  helperText={formik.touched.maxPrice && formik.errors.maxPrice}
                  required
                />
              </Grid>
            </Grid>
            <Grid container xs={12} md={2}>
              <Button
                disabled={
                  !formik.isValid ||
                  formik.values.maxPrice < formik.values.minPrice ||
                  formik.values.maxWeight < formik.values.minWeight
                }
                variant="contained"
                onClick={() => {
                  dispatch(
                    provinceEditApprovedPrice({
                      approved: true,
                      lowest_price: formik.values.minPrice,
                      highest_price: formik.values.maxPrice,
                      lowest_weight: formik.values.minWeight,
                      highest_weight: formik.values.maxWeight,
                    })
                  ).then((r) => {
                    if (r.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "مشکلی پیش آمده است!",
                        severity: "error",
                      });
                    } else {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                    }
                  });
                }}
              >
                ارسال
              </Button>
            </Grid>
          </>
        )}
      </Grid>

      <Grid
        container
        xs={12}
        alignItems="center"
        justifyContent="space-between"
        mt={2}
      >
        <Divider
          style={{
            width: "100%",
            backgroundColor: "black",
            marginBottom: "20px",
          }}
        />
        <ProvincePolicyAvicultureCommit approvedState={checked} />

        <Divider
          style={{
            width: "100%",
            backgroundColor: "black",
            marginBottom: "20px",
          }}
        />
        <ProvincePolicyApprovedKillHousePrice
          approvedState={killHousePriceCheck}
        />
      </Grid>
    </Grid>
  );
};
