import React, { useContext, useEffect, useState } from "react";
import {
  Button,
  Tab,
  Tabs,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment";
import { useDispatch } from "react-redux";
import axios from "axios";
import { AppContext } from "../../../../contexts/AppContext";
import {
  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 { RiFileExcel2Fill } from "react-icons/ri";
import { provinceFreeSalesGetDashboardTransactionsService } from "../../services/province-free-sales-get-transaction-dashboard";
import { RiSearchLine } from "react-icons/ri";

export const ProvinceFreeSalesTransactions = () => {
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    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 handleChange = (event, newValue) => {
    setValue(newValue);
  };
  const [dashboardData, setDashboardData] = useState([]);

  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 [value, setValue] = useState(0);

  const fetchApiData = async (page) => {
    let response;
    dispatch(LOADING_START());
    response = await axios.get(
      `poultry-requests-transactions/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&type=${
        value === 0 ? "poultry" : "buyer"
      }`
    );
    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?.orderId,
        item?.poultryRequest?.map((option, index) => (
          <Typography key={index} variant="caption">
            {option.orderCode}
          </Typography>
        )),
        item?.amount?.toLocaleString(),
        `${item?.payerInfo?.fullname} (${item?.payerInfo?.mobile})`,
        item?.refId,
        item?.unionShare?.toLocaleString(),
        item?.companyShare?.toLocaleString(),
        item?.guildsShare?.toLocaleString(),
        item?.otherShare?.toLocaleString(),
      ];
    });

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

  useEffect(() => {
    fetchApiData(1);
    dispatch(
      provinceFreeSalesGetDashboardTransactionsService({
        selectedDate1,
        selectedDate2,
        textValue,
      })
    ).then((r) => {
      setDashboardData(r.payload.data);
    });
  }, [dispatch, selectedDate1, selectedDate2, perPage, value]);

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

    try {
      const response = await axios.get(
        `poultry-requests-transactions/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}&type=${
          value === 0 ? "poultry" : "buyer"
        }`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);

      dispatch(LOADING_END());
      dispatch(
        provinceFreeSalesGetDashboardTransactionsService({
          selectedDate1,
          selectedDate2,
          textValue,
          type: value === 0 ? "poultry" : "buyer",
        })
      ).then((r) => {
        setDashboardData(r.payload.data);
      });
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="center"
      gap={2}
      mt={2}
    >
      <Grid
        container
        xs={12}
        justifyContent="start"
        alignItems="center"
        gap={2}
      >
        <Grid>
          <DatePicker
            label="از تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} size="small" />
            )}
            value={selectedDate1}
            onChange={(e) => {
              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </Grid>
        <Grid>
          <DatePicker
            label="تا تاریخ"
            id="date"
            renderInput={(params) => (
              <TextField style={{ width: "160px" }} {...params} size="small" />
            )}
            value={selectedDate2}
            onChange={(e) => {
              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            }}
          />
        </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>
        <Grid>
          <Tooltip title="خروجی اکسل کلی">
            <a
              href={`${
                axios.defaults.baseURL
              }transacion_out_request_excel/?date1=${selectedDate1}&date2=${selectedDate2}&role=${getRoleFromUrl()}&search=filter&value=${textValue}&type=${
                value === 0 ? "poultry" : "buyer"
              }`}
              rel="noreferrer"
            >
              <Button color="primary">
                <RiFileExcel2Fill size={32} />
              </Button>
            </a>
          </Tooltip>
        </Grid>
      </Grid>
      <Grid container mt={2} mb={4} isDashboard xs={12}>
        <ResponsiveTable
          noPagination
          isDashboard
          columns={[
            "تعداد پرداختی ها",
            "تعداد پرداخت کننده ها",
            "مبلغ کل پرداختی",
            "تعداد مرغداران",
            " پرداختی مرغداران",
            "تعداد خریداران",
            " پرداختی خریداران",
          ]}
          data={[
            [
              dashboardData?.totalNumberOfTransactions?.toLocaleString(),
              dashboardData?.totalNumberOfPayers?.toLocaleString(),
              dashboardData?.totalAmountOfTransactions?.toLocaleString(),
              dashboardData?.totalNumberOfPoultries?.toLocaleString(),
              dashboardData?.totalAmountOfPoultries?.toLocaleString(),
              dashboardData?.totalNumberOfBuyers?.toLocaleString(),
              dashboardData?.totalAmountOfBuyers?.toLocaleString(),
            ],
          ]}
          title={"خلاصه اطلاعات"}
        />
      </Grid>

      <Tabs
        value={value}
        onChange={handleChange}
        aria-label="simple tabs example"
      >
        <Tab label="مرغدار" />
        <Tab label="خریدار" />
      </Tabs>

      {value === 0 ? (
        <ResponsiveTable
          data={tableData}
          columns={[
            "ردیف",
            "شماره سفارش",
            "کد سفارش",
            "مبلغ تراکنش (ریال)",
            "پرداخت کننده",
            "کد پیگیری",
            "سهم اتحادیه (ریال)",
            "سهم شرکت (ریال)",
            "سهم صنف (ریال)",
            "سهم دیگر (ریال)",
          ]}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title="تراکنش های مرغداران"
        />
      ) : (
        <ResponsiveTable
          data={tableData}
          columns={[
            "ردیف",
            "شماره سفارش",
            "کد سفارش",
            "مبلغ تراکنش (ریال)",
            "پرداخت کننده",
            "کد پیگیری",
            "سهم اتحادیه (ریال)",
            "سهم شرکت (ریال)",
            "سهم صنف (ریال)",
            "سهم دیگر (ریال)",
          ]}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title="تراکنش های خریداران"
        />
      )}
    </Grid>
  );
};
