import React, { useContext, useEffect, useState } from "react";
import { Button, Checkbox, IconButton, TextField } from "@mui/material";
import axios from "axios";
import { RiSearchLine } from "react-icons/ri";
import { useDispatch } from "react-redux";
import EditIcon from "@mui/icons-material/Edit";
import { AppContext } from "../../../../contexts/AppContext";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { ProvinceManageDistributionsSubmitCommitmentPercent } from "../province-manage-distributions-submit-commitment-percentet/ProvinceManageDistributionsSubmitCommitmentPercent";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { ProvinceManageGuildDistributionsSubmitPercents } from "../province-manage-guild-distributions-submit-percents/ProvinceManageGuildDistributionsSubmitPercents";
import {
  provinceManageGuildTradesEditAllPercents,
  provinceManageGuildTradesEditPercents,
  provinceManageGuildTradesGetPercents,
} from "../../services/province-manage-guilds-trades-edit-percents";

export const ManageGuildDistributions = () => {
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const [openNotif] = useContext(AppContext);
  const dispatch = useDispatch();

  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);
  const [dashboardData, setDashboardData] = useState([]);

  const getDashboardData = () => {
    dispatch(provinceManageGuildTradesGetPercents()).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `guilds-for-configs/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}`
    );
    getDashboardData();
    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const updateTable = () => {
    fetchApiData(page !== 0 ? page : 1);
  };

  const openGovModal = (item, isAll) => {
    dispatch(
      OPEN_MODAL({
        title: "فروش دولتی",
        content: (
          <ProvinceManageGuildDistributionsSubmitPercents
            item={item}
            updateTable={updateTable}
            type="gov"
            isDashboard={isAll}
          />
        ),
      })
    );
  };

  const openFreeModal = (item, isAll) => {
    dispatch(
      OPEN_MODAL({
        title: "فروش آزاد",
        content: (
          <ProvinceManageGuildDistributionsSubmitPercents
            item={item}
            updateTable={updateTable}
            type="free"
            isDashboard={isAll}
          />
        ),
      })
    );
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${item?.user?.fullname} (${item?.user?.mobile})`,
        <ProvinceManageDistributionsSubmitCommitmentPercent
          key={i}
          amount={item?.outProvinceFreeBuyingCommitmentPercent}
          updateTable={updateTable}
          item={item}
          isGuild
        />,
        <Checkbox
          key={i}
          checked={item?.freeSaleFromFreeQuotaInProvince}
          onClick={() => {
            dispatch(
              provinceManageGuildTradesEditPercents({
                key: item?.key,
                free_sale_from_free_quota_in_province:
                  !item?.freeSaleFromFreeQuotaInProvince,
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                updateTable();
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        />,
        <Checkbox
          key={i}
          checked={item?.freeSaleFormGovernmentalQuota}
          onClick={() => {
            dispatch(
              provinceManageGuildTradesEditPercents({
                key: item?.key,
                free_sale_form_governmental_quota:
                  !item?.freeSaleFormGovernmentalQuota,
              })
            ).then((r) => {
              if (r.payload.error) {
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: r.payload.error,
                  severity: "error",
                });
              } else {
                updateTable();
                openNotif({
                  vertical: "top",
                  horizontal: "center",
                  msg: "عملیات با موفقیت انجام شد.",
                  severity: "success",
                });
              }
            });
          }}
        />,

        <Grid
          key={i}
          container
          alignItems="center"
          xs={12}
          justifyContent="start"
          direction="row"
        >
          <Grid xs={6}>
            <Checkbox
              checked={item?.governmentalSellingPermission}
              onChange={() => {
                const newValue = !item?.governmentalSellingPermission;
                dispatch(
                  provinceManageGuildTradesEditPercents({
                    key: item?.key,
                    governmental_selling_permission: newValue,
                    ...(newValue === false
                      ? {
                          in_province_governmental_selling_percent: 0,
                          segmentation_governmental_percent: 0,
                          out_province_governmental_selling_percent: 0,
                        }
                      : {}),
                  })
                ).then(() => {
                  if (newValue === true) {
                    openGovModal(item);
                  } else {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                  updateTable();
                });
              }}
            />
          </Grid>

          {item?.governmentalSellingPermission && (
            <Grid xs={6}>
              <IconButton
                size="small"
                onClick={() => openGovModal(item)}
                color="primary"
              >
                <EditIcon />
              </IconButton>
            </Grid>
          )}
        </Grid>,
        <Grid
          key={i}
          container
          alignItems="center"
          xs={12}
          justifyContent="center"
          direction="row"
        >
          <Grid xs={6}>
            <Checkbox
              checked={item?.freeSellingPermission}
              onChange={() => {
                const newValue = !item?.freeSellingPermission;
                dispatch(
                  provinceManageGuildTradesEditPercents({
                    key: item?.key,
                    free_selling_permission: newValue,
                    ...(newValue === false
                      ? {
                          in_province_free_selling_percent: 0,
                          out_province_free_selling_percent: 0,
                          segmentation_free_selling_percent: 0,
                        }
                      : {}),
                  })
                ).then(() => {
                  if (newValue === true) {
                    openFreeModal(item);
                  } else {
                    openNotif({
                      vertical: "top",
                      horizontal: "center",
                      msg: "عملیات با موفقیت انجام شد.",
                      severity: "success",
                    });
                  }
                  updateTable();
                });
              }}
            />
          </Grid>

          <Grid xs={6}>
            {item?.freeSellingPermission && (
              <IconButton
                size="small"
                onClick={() => openFreeModal(item)}
                color="primary"
              >
                <EditIcon />
              </IconButton>
            )}{" "}
          </Grid>
        </Grid>,
        item?.inProvinceGovernmentalSellingPercent,
        item?.outProvinceGovernmentalSellingPercent,
        item?.segmentationGovernmentalPercent,
        item?.inProvinceFreeSellingPercent,
        item?.outProvinceFreeSellingPercent,
        item?.segmentationFreeSellingPercent,
      ];
    });

    setTableData(d);
  }, [data]);

  useEffect(() => {
    fetchApiData(1);
  }, [dispatch, perPage]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());

    try {
      const response = await axios.get(
        `guilds-for-configs/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&page=${1}&page_size=${perPage}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      <Grid container mt={2} mb={4} isDashboard xs={12}>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "درصد تحویل خرید خارج استان",
            "فروش آزاد به داخل استان",
            "فروش آزاد از سهمیه دولتی",
            "فروش دولتی",
            "فروش آزاد",
            "درصد فروش دولتی داخل استان",
            "درصد فروش دولتی خارج استان",
            "درصد فروش دولتی قطعه بندی",
            "درصد فروش آزاد داخل استان",
            "درصد فروش آزاد خارج استان",
            "درصد فروش آزاد قطعه بندی",
          ]}
          data={[
            [
              <ProvinceManageDistributionsSubmitCommitmentPercent
                key={dashboardData}
                amount={dashboardData?.outProvinceFreeBuyingCommitmentPercent}
                updateTable={updateTable}
                item={dashboardData}
                isGuild
                isDashboard
              />,
              <Checkbox
                key={dashboardData}
                checked={dashboardData?.freeSaleFromFreeQuotaInProvince}
                onClick={() => {
                  dispatch(
                    provinceManageGuildTradesEditAllPercents({
                      free_sale_from_free_quota_in_province:
                        !dashboardData?.freeSaleFromFreeQuotaInProvince,
                    })
                  ).then((r) => {
                    if (r.payload.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.payload.error,
                        severity: "error",
                      });
                    } else {
                      updateTable();
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                    }
                  });
                }}
              />,
              <Checkbox
                key={dashboardData}
                checked={dashboardData?.freeSaleFormGovernmentalQuota}
                onClick={() => {
                  dispatch(
                    provinceManageGuildTradesEditAllPercents({
                      free_sale_form_governmental_quota:
                        !dashboardData?.freeSaleFormGovernmentalQuota,
                    })
                  ).then((r) => {
                    if (r.payload.error) {
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: r.payload.error,
                        severity: "error",
                      });
                    } else {
                      updateTable();
                      openNotif({
                        vertical: "top",
                        horizontal: "center",
                        msg: "عملیات با موفقیت انجام شد.",
                        severity: "success",
                      });
                    }
                  });
                }}
              />,

              <Grid
                key={dashboardData}
                container
                alignItems="center"
                xs={12}
                justifyContent="start"
                direction="row"
              >
                <Grid xs={6}>
                  <Checkbox
                    checked={dashboardData?.governmentalSellingPermission}
                    onChange={() => {
                      const newValue =
                        !dashboardData?.governmentalSellingPermission;
                      dispatch(
                        provinceManageGuildTradesEditAllPercents({
                          governmental_selling_permission: newValue,
                          ...(newValue === false
                            ? {
                                in_province_governmental_selling_percent: 0,
                                segmentation_governmental_percent: 0,
                                out_province_governmental_selling_percent: 0,
                              }
                            : {}),
                        })
                      ).then(() => {
                        if (newValue === true) {
                          openGovModal(dashboardData, true);
                        } else {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "عملیات با موفقیت انجام شد.",
                            severity: "success",
                          });
                        }
                        updateTable();
                      });
                    }}
                  />
                </Grid>

                {dashboardData?.governmentalSellingPermission && (
                  <Grid xs={6}>
                    <IconButton
                      size="small"
                      onClick={() => openGovModal(dashboardData, true)}
                      color="primary"
                    >
                      <EditIcon />
                    </IconButton>
                  </Grid>
                )}
              </Grid>,
              <Grid
                key={dashboardData}
                container
                alignItems="center"
                xs={12}
                justifyContent="center"
                direction="row"
              >
                <Grid xs={6}>
                  <Checkbox
                    checked={dashboardData?.freeSellingPermission}
                    onChange={() => {
                      const newValue = !dashboardData?.freeSellingPermission;
                      dispatch(
                        provinceManageGuildTradesEditAllPercents({
                          free_selling_permission: newValue,
                          ...(newValue === false
                            ? {
                                in_province_free_selling_percent: 0,
                                out_province_free_selling_percent: 0,
                                segmentation_free_selling_percent: 0,
                              }
                            : {}),
                        })
                      ).then(() => {
                        if (newValue === true) {
                          openFreeModal(dashboardData, true);
                        } else {
                          openNotif({
                            vertical: "top",
                            horizontal: "center",
                            msg: "عملیات با موفقیت انجام شد.",
                            severity: "success",
                          });
                        }
                        updateTable();
                      });
                    }}
                  />
                </Grid>

                <Grid xs={6}>
                  {dashboardData?.freeSellingPermission && (
                    <IconButton
                      size="small"
                      onClick={() => openFreeModal(dashboardData, true)}
                      color="primary"
                    >
                      <EditIcon />
                    </IconButton>
                  )}{" "}
                </Grid>
              </Grid>,
              dashboardData?.inProvinceGovernmentalSellingPercent,
              dashboardData?.outProvinceGovernmentalSellingPercent,
              dashboardData?.segmentationGovernmentalPercent,
              dashboardData?.inProvinceFreeSellingPercent,
              dashboardData?.outProvinceFreeSellingPercent,
              dashboardData?.segmentationFreeSellingPercent,
            ],
          ]}
          title={"تنظیمات کلی"}
        />
      </Grid>
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Grid>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "نام مباشر",
          "درصد تحویل خرید خارج استان",
          "فروش آزاد به داخل استان",
          "فروش آزاد از سهمیه دولتی",
          "فروش دولتی",
          "فروش آزاد",
          "درصد فروش دولتی داخل استان",
          "درصد فروش دولتی خارج استان",
          "درصد فروش دولتی قطعه بندی",
          "درصد فروش آزاد داخل استان",
          "درصد فروش آزاد خارج استان",
          "درصد فروش آزاد قطعه بندی",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="مباشرین"
      />
    </Grid>
  );
};
