import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  Checkbox,
  IconButton,
  TextField,
  Tooltip,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
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 { ProvinceJahadSellReportTransactions } from "../province-jahad-sell-report-transactions/ProvinceJahadSellReportTransactions";
import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye";

import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import { provinceJahadSellReportInfoDashboardService } from "../../services/province-get-jahad-sell-report-dashboard";

export const ProvinceJahadSellReport = ({ product }) => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [withDate, setWithDate] = useState(false);
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  const dispatch = useDispatch();
  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };

  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(
      provinceJahadSellReportInfoDashboardService({
        date1: selectedDate1,
        date2: selectedDate2,
        search: "filter",
        role: getRoleFromUrl(),
        value: textValue,
        name: product?.key,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `cooperative-warehouse/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }&page=${page}&page_size=${perPage}&name=${product?.key}`
    );
    dispatch(LOADING_END());
    getDashboardData();

    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,
        product?.label,
        item?.name,
        item?.user?.fullname,
        item?.user?.provinceName,
        item?.user?.cityName,
        item?.user?.mobile,
        item?.user?.nationalId,
        item?.info?.totalReceiptWeight?.toLocaleString() || 0,
        item?.info?.totalWeight?.toLocaleString() || 0,
        item?.info?.totalAllocatedWeight?.toLocaleString() || 0,
        item?.info?.totalRemainWeight?.toLocaleString() || 0,
        item?.info?.transactions?.toLocaleString() || 0,
        item?.info?.totalTransactionsPrice?.toLocaleString() || 0,
        item?.info?.totalTransactionsWeight?.toLocaleString() || 0,
        <Grid key={i} container gap={1} alignItems="center" direction="column">
          <Tooltip title="جزئیات" placement="left">
            <IconButton
              key={i}
              color="primary"
              onClick={() => {
                dispatch(
                  DRAWER({
                    top: true,
                    title: "تراکنش ها",
                    content: (
                      <Grid
                        container
                        xs={12}
                        justifyContent="center"
                        alignItems="center"
                      >
                        <Grid
                          container
                          xs={10}
                          justifyContent="center"
                          alignItems="center"
                        >
                          <ProvinceJahadSellReportTransactions
                            cooperative_key={item?.key}
                            product={product}
                          />
                        </Grid>
                      </Grid>
                    ),
                  })
                );
              }}
            >
              <RemoveRedEyeIcon />
            </IconButton>
          </Tooltip>
          <Tooltip title="خروجی اکسل">
            <a
              href={`${axios.defaults.baseURL}LiveStock/jahad/live_stock_transaction_excel/?search=filter&value=${textValue}&key=${userKey}&cooperative_key=${item?.key}&name=${product?.key}`}
              rel="noreferrer"
              target="_blank"
            >
              <Button color="success">
                <RiFileExcel2Fill size={24} />
              </Button>
            </a>
          </Tooltip>
        </Grid>,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `cooperative-warehouse/?role=${getRoleFromUrl()}&search=filter&value=${textValue}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }&page=${1}&page_size=${perPage}&name=${product?.key}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
      getDashboardData();
    } 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
          container
          gap={1}
          style={{
            borderStyle: "solid",
            borderWidth: "1px",
            padding: "5px",
            borderRadius: "15px",
            borderColor: "gray",
            justifyContent: "left",
          }}
          alignItems="center"
        >
          <Checkbox
            icon={<ToggleOffOutlinedIcon />}
            checkedIcon={<ToggleOnIcon />}
            checked={withDate}
            onChange={() => setWithDate(!withDate)}
            color="primary"
            size="large"
          />
          <Grid>
            <DatePicker
              disabled={!withDate}
              label="از تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  style={{ width: "160px" }}
                  {...params}
                />
              )}
              value={selectedDate1}
              onChange={(e) => {
                setSelectedDate1(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              disabled={!withDate}
              label="تا تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField
                  size="small"
                  style={{ width: "160px" }}
                  {...params}
                />
              )}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
        </Grid>
        <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
            }LiveStock/jahad/cooperative_warehouse_excel/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&key=${userKey}&name=${
              product?.key
            }`}
            rel="noreferrer"
            target="_blank"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>

        <Tooltip title="خروجی اکسل تراکنش مشکوک">
          <a
            href={`${
              axios.defaults.baseURL
            }LiveStock/jahad/rancher_management/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&key=${userKey}&name=${
              product?.key
            }`}
            rel="noreferrer"
            target="_blank"
          >
            <Button color="error">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>
      <Grid container mt={2} mb={4} isDashboard gap={2}>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "محصول",
            "تعداد کل تراکنش ها",
            "وزن کل تراکنش ها",
            "مبلغ کل تراکنش ها",
            "کل وزن ورود به انبار",
            "کل وزن دریافتی",
            "کل وزن تخصیص داده شده",
            "کل وزن باقی مانده",
          ]}
          data={[
            [
              product?.label,
              dashboardData?.transactions?.toLocaleString(),
              dashboardData?.totalTransactionsWeight?.toLocaleString(),
              dashboardData?.totalTransactionsPrice?.toLocaleString(),
              dashboardData?.totalWeight?.toLocaleString(),
              dashboardData?.totalReceiptWeight?.toLocaleString(),
              dashboardData?.totalAllocatedWeight?.toLocaleString(),
              dashboardData?.totalRemainWeight?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>
      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "محصول",
          "نام تعاونی",
          "کاربر",
          "استان",
          "شهر",
          "موبایل",
          "کد ملی",
          "سهمیه دریافتی",
          "وزن تحویلی",
          "وزن فروش رفته",
          "مانده انبار",
          "تعداد تراکنش ها",
          "جمع کل تراکنش ها",
          "وزن کل تراکنش ها",
          "جزئیات",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="گزارش فروش تعاونی ها"
      />
    </Grid>
  );
};
