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 { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { useDispatch } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { ProvinceManageDistributionsSubmitPercents } from "../province-manage-distributions-submit-percents/ProvinceManageDistributionsSubmitPercents";
import { provinceManageTradesEditPercents } from "../../services/province-manage-trades-edit-percents";
import { AppContext } from "../../../../contexts/AppContext";
import { ProvinceManageDistributionsSubmitCommitmentPercent } from "../province-manage-distributions-submit-commitment-percentet/ProvinceManageDistributionsSubmitCommitmentPercent";
import EditIcon from "@mui/icons-material/Edit";

export const ProvinceManageDistributions = () => {
  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 fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `market-kill-houses/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}`
    );
    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) => {
    dispatch(
      OPEN_MODAL({
        title: "فروش دولتی",
        content: (
          <ProvinceManageDistributionsSubmitPercents
            item={item}
            updateTable={updateTable}
            type="gov"
          />
        ),
      })
    );
  };

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

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.name,
        `${item?.fullname} (${item?.mobile})`,
        item?.killer ? "کشتارکن" : "کشتارگاه",
        <ProvinceManageDistributionsSubmitCommitmentPercent
          key={i}
          amount={item?.outProvinceFreeBuyingCommitmentPercent}
          updateTable={updateTable}
          item={item}
        />,
        <Checkbox
          key={i}
          checked={item?.freeSaleFromFreeQuotaInProvince}
          onClick={() => {
            dispatch(
              provinceManageTradesEditPercents({
                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(
              provinceManageTradesEditPercents({
                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(
                  provinceManageTradesEditPercents({
                    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((r) => {
                  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(
                  provinceManageTradesEditPercents({
                    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((r) => {
                  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?.coldHouseGovernmentalPercent,
        item?.inProvinceFreeSellingPercent,
        item?.outProvinceFreeSellingPercent,
        item?.segmentationFreeSellingPercent,
        item?.coldHouseFreePercent,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `market-kill-houses/?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
        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>
  );
};
