import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  FormControlLabel,
  IconButton,
  Switch,
  TextField,
  Tooltip,
} from "@mui/material";
import axios from "axios";
import { RiSearchLine } from "react-icons/ri";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { Grid } from "../../../../components/grid/Grid";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { useDispatch } from "react-redux";
import { provinceJahadEditRancher } from "../../services/province-jahad-rancher-activation";
import { AppContext } from "../../../../contexts/AppContext";
import { provinceJahadGetProductInfoService } from "../../services/province-jahad-get-product-info";
import { ProvinceJahadEditProduct } from "../province-jahad-edit-product/ProvinceJahadEditProduct";
import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye";
export const ProvinceJahadBranDistributionsPolicy = ({ product }) => {
  const dispatch = useDispatch();
  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const [dashboardData, setDashboardData] = useState([]);

  const getDashboardData = () => {
    dispatch(
      provinceJahadGetProductInfoService({ product: product?.key })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  useEffect(() => {
    if (getRoleFromUrl() === "LiveStockProvinceJahad") {
      getDashboardData();
    }
  }, []);

  const [openNotif] = useContext(AppContext);

  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(
      `/LiveStock/rancher/rancher-view/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&name=${
        product?.key
      }`
    );

    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);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.herdCode,
        item?.epidemiologicalCode,
        item?.postalCode,
        item?.unitId,
        item?.herdName,
        item?.nationalId,
        item?.user?.fullname.replace(":", " "),
        item?.mobile,
        item?.contractorCode || "-",
        item?.city,
        // item?.lightLivestock?.toLocaleString(),
        // item?.heavyLivestock?.toLocaleString(),
        // Math.round(
        //   item?.lightLivestock + item?.heavyLivestock
        // )?.toLocaleString(),
        // item?.weightQuotaLight?.toLocaleString(),
        // item?.weightQuotaHeavy?.toLocaleString(),
        // Math.round(
        //   item?.weightQuotaLight + item?.weightQuotaHeavy
        // )?.toLocaleString(),
        <FormControlLabel
          key={i}
          control={
            <Switch
              checked={item?.allowBuy}
              onChange={() => {
                dispatch(
                  provinceJahadEditRancher({
                    key: item?.key,
                    allow_buy: !item?.allowBuy,
                  })
                ).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",
                    });
                  }
                });
              }}
              color="primary"
            />
          }
          label={item?.allowBuy ? "فعال" : "غیرفعال"}
          style={{
            justifyContent: "center",
            alignItems: "center",
            display: "flex",
          }}
        />,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `/LiveStock/rancher/rancher-view/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&name=${
          product?.key
        }`
      );
      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}>
      {getRoleFromUrl() === "LiveStockProvinceJahad" && (
        <Grid container mt={2} mb={4} isDashboard xs={12}>
          <ResponsiveTable
            noPagination
            isDashboard
            columns={[
              "محصول",
              "سهمیه دام سبک روستایی (کیلوگرم)",
              "سهمیه دام سنگین روستایی (کیلوگرم)",
              "سهمیه دام سبک صنعتی (کیلوگرم)",
              "سهمیه دام سنگین صنعتی (کیلوگرم)",
              "سهمیه دام سبک DHI (کیلوگرم)",
              "سهمیه دام سنگین DHI (کیلوگرم)",
              "قیمت سبوس (ریال)",
              "کارمزد اتحادیه",
              "کارمزد تعاونی",
              "هزینه حمل و نقل",
              "قیمت درب کارخانه (ریال)",
              "قیمت درب تعاونی (ریال)",
              "عملیات",
            ]}
            data={[
              [
                dashboardData?.name,
                dashboardData?.lightWight?.toLocaleString() || "0",
                dashboardData?.heavyWight?.toLocaleString() || "0",
                dashboardData?.lightWightIndustrial?.toLocaleString() || "0",
                dashboardData?.heavyWightIndustrial?.toLocaleString() || "0",
                dashboardData?.lightWightDha?.toLocaleString() || "0",
                dashboardData?.heavyWightDha?.toLocaleString() || "0",
                dashboardData?.price?.toLocaleString() || "0",
                dashboardData?.unionPrice?.toLocaleString() || "0",
                dashboardData?.cooperativePrice?.toLocaleString() || "0",
                dashboardData?.shippingPrice?.toLocaleString() || "0",
                (
                  (dashboardData?.price || 0) +
                  (dashboardData?.unionPrice || 0) +
                  (dashboardData?.cooperativePrice || 0)
                )?.toLocaleString() || "0",
                (
                  (dashboardData?.price || 0) +
                  (dashboardData?.unionPrice || 0) +
                  (dashboardData?.cooperativePrice || 0) +
                  (dashboardData?.shippingPrice || 0)
                )?.toLocaleString() || "0",
                <Tooltip
                  key={`edit-${dashboardData?.name || "product"}`}
                  title="ویرایش محصول"
                  placement="left"
                >
                  <IconButton
                    color="primary"
                    size="small"
                    onClick={() => {
                      dispatch(
                        DRAWER({
                          title: "ویرایش محصول",
                          right: !(window.innerWidth <= 600),
                          bottom: window.innerWidth <= 600,
                          content: (
                            <ProvinceJahadEditProduct
                              item={dashboardData}
                              updateTable={getDashboardData}
                            />
                          ),
                        })
                      );
                    }}
                  >
                    <RemoveRedEyeIcon />
                  </IconButton>
                </Tooltip>,
              ],
            ]}
            title={`محدودیت های توزیع ${product?.label}`}
          />
        </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
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
        {/* <Tooltip title="خروجی اکسل">
          <a href={`${axios.defaults.baseURL}`} rel="noreferrer">
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip> */}
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "کد گله",
          "کد اپیدمیولوژیک",
          "کد پستی",
          "شناسه یکتا",
          "نام گله",
          "کد ملی دامدار",
          "نام دامدار",
          "موبایل",
          "کد پیمانکار",
          "شهرستان",
          // "تعداد دام سبک",
          // "تعداد دام سنگین",
          // "جمع کل گله",
          // "سهمیه دام سبک",
          // "سهمیه دام سنگین",
          // "مجموع سهمیه",
          "عملیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title={`مجوز دریافت ${product?.label}`}
      />
    </Grid>
  );
};
