import { Grid } from "../../../../components/grid/Grid";

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 } from "react-redux";
import axios from "axios";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { AppContext } from "../../../../contexts/AppContext";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import { useNavigate } from "react-router-dom";
import {
  ROUTE_ADMINX_TRANSACTIONS,
  ROUTE_CITY_REQUEST_TRANSACTIONS,
  ROUTE_PROVINCE_FINANCIAL_TRANSACTIONS,
  ROUTE_PROVINCE_TRANSACTIONS,
  ROUTE_SUPER_ADMIN_TRANSACTIONS,
} from "../../../../routes/routes";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import ReceiptLongIcon from "@mui/icons-material/ReceiptLong";
export const Transactions = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);
  const [withDate, setWithDate] = useState(true);
  const [openNotif] = useContext(AppContext);

  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 navigate = useNavigate();

  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 [menuState, setMenuState] = useState({ anchorEl: null, item: null });

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `pos-machine-transactions/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }&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);
  //   };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.guildsName || "-",
        `${item?.user?.fullname} (${item?.user?.mobile})`,
        item?.user?.city?.name || "-",
        item?.guildsName || "-",
        item?.licenseNumber || "-",
        item?.transaction?.totalCarcassesWeight?.toLocaleString(),
        item?.transaction?.realAllocatedWeight?.toLocaleString(),
        item?.transaction?.totalRemainWeight?.toLocaleString(),
        item?.transaction?.lenTransaction?.toLocaleString(),
        item?.transaction?.totalPrice?.toLocaleString(),
        <>
          <IconButton
            title="تراکنش‌ها"
            color="primary"
            onClick={() => {
              handleMenuClose();
              navigateToTransactions(item);
            }}
          >
            <ReceiptLongIcon fontSize="small" />
          </IconButton>
        </>,
        //  "ردیف",
        //  "صنف",
        //  "کاربر",
        //  "شهر",
        //  "ورودی به انبار (کیلوگرم)",
        //  "فروش رفته (کیلوگرم)",
        //  "مانده انبار (کیلوگرم)",
        //  "تعداد تراکنش ها",
        //  "مبلغ تراکنش ها",
        //  "عملیات",
      ];
    });

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

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

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

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

  const handleMenuClose = () => {
    setMenuState({ anchorEl: null, item: null });
  };

  const navigateToTransactions = (item) => {
    const filterDateParam = withDate ? "on" : "off";
    navigate(
      `${
        getRoleFromUrl() === "AdminX"
          ? ROUTE_ADMINX_TRANSACTIONS
          : getRoleFromUrl() === "SuperAdmin"
          ? ROUTE_SUPER_ADMIN_TRANSACTIONS
          : getRoleFromUrl() === "ProvinceFinancial"
          ? ROUTE_PROVINCE_FINANCIAL_TRANSACTIONS
          : getRoleFromUrl() === "CityPoultry"
          ? ROUTE_CITY_REQUEST_TRANSACTIONS
          : ROUTE_PROVINCE_TRANSACTIONS
      }/${item?.key}/${item?.guildsName}?filterDate=${filterDateParam}`
    );
  };

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="center"
      gap={2}
      px={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"
                  sx={{ width: { xs: "126px", md: "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"
                  sx={{ width: { xs: "126px", md: "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}0/hatching_excel/`}
                rel="noreferrer"
              > */}
          <Button
            color="success"
            onClick={() => {
              openNotif({
                vertical: "top",
                horizontal: "center",
                msg: "فایل اکسل در حال دانلود می باشد، این علمیات ممکن است زمان بر باشد لطفا صبر کنید.",
                severity: "success",
              });
              const link = `${
                axios.defaults.baseURL
              }all_guilds_transaction_excel/${
                withDate ? `?date1=${selectedDate1}&date2=${selectedDate2}` : ``
              }`;
              window.location.href = link;
            }}
          >
            <RiFileExcel2Fill size={32} />
          </Button>
          {/* </a> */}
        </Tooltip>
      </Grid>

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