import {
  Button,
  IconButton,
  Pagination,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import axios from "axios";
import { useContext, useEffect, useRef, useState } from "react";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { PageTable } from "../../../../components/page-table/PageTable";
import { SPACING } from "../../../../data/spacing";
import { DatePicker } from "@mui/x-date-pickers";
import moment from "moment/moment";
import { AppContext } from "../../../../contexts/AppContext";
import { format } from "date-fns-jalali";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import BoxList from "../../../../components/box-list/BoxList";
import PrintIcon from "@mui/icons-material/Print";
import { useReactToPrint } from "react-to-print";
import SuccessTransactionRecipt from "../success-transaction-recipt/SuccessTransactionRecipt";

export const SuccessTransactions = () => {
  const authToken = useSelector((state) => state.userSlice.authToken);
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  const userInfo = useSelector((state) => state.userSlice);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);
  const [dataTableM, setDataTableM] = useState([]);
  const dispatch = useDispatch();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);

  const [textValue, setTextValue] = useState("");

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

  const fetchApiData = async (page, textValue) => {
    setLoading(true);
    const response = await axios.get(
      `transactions/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&date1=${selectedDate1}&date2=${selectedDate2}&state=completed&role=${getRoleFromUrl()}`
    );
    setData(response.data.results);
    setTotalRows(response.data.count);
    setLoading(false);
    dispatch(LOADING_END());
  };

  const [page, setPage] = useState(0);
  const handleChangePageM = (event, newPage) => {
    dispatch(LOADING_START());
    setPage(newPage);
    fetchApiData(newPage + 1, textValue);
  };

  const handlePageChange = (page) => {
    fetchApiData(page, textValue);
  };

  const handlePerRowsChange = async (newPerPage, page) => {
    setLoading(true);
    const response = await axios.get(
      `transactions/?search=filter&value=${textValue}&page=${page}&page_size=${newPerPage}&date1=${selectedDate1}&date2=${selectedDate2}&state=completed&role=${getRoleFromUrl()}`
    );

    setData(response.data.results);
    setTotalRows(response.data.count);
    setPerPage(newPerPage);

    setLoading(false);
  };

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    setLoading(true);
    try {
      const response = await axios.get(
        `transactions/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&state=completed&role=${getRoleFromUrl()}`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
    } catch (error) {
      console.error("Error fetching data:", error);
    } finally {
      setLoading(false);
    }
  };

  const [reciptData, setReciptData] = useState();

  const componentRef = useRef();
  const printPDF = useReactToPrint({
    content: () => componentRef.current,
    documentTitle: `گزارش پرونده `,
  });

  const setPdfOptions = (item) => {
    setReciptData(item);
    if (reciptData) {
      printPDF();
    }
  };

  const columns = [
    {
      name: "تاریخ و زمان",
      selector: (item) => {
        return format(new Date(item.createDate), "yyyy/MM/dd hh:mm:ss");
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "پرداخت کننده",
      selector: (item) => {
        return item.payer;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "تعداد سفارشات",
      selector: (item) => {
        return item.information?.totalRequestNumber;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "تعداد کل (قطعه)",
      selector: (item) => {
        return item.information?.totalQuantity;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "وزن کل (کیلوگرم)",
      selector: (item) => {
        return item.information?.totalWeight;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "شماره درخواست",
      selector: (item) => {
        return item.orderId;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "شماره پیگیری",
      selector: (item) => {
        return item.saleReferenceId;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "کدسفارش",
      selector: (item) => {
        return item.orderId;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "شماره کارت",
      selector: (item) => {
        return item.cardHolderPan;
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "قیمت",
      selector: (item) => {
        return item?.amount?.toLocaleString() + " ﷼";
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
    {
      name: "چاپ رسید",
      selector: (item) => {
        return (
          <>
            <IconButton
              aria-label="delete"
              color="primary"
              onClick={() => {
                setPdfOptions(item);
              }}
            >
              <PrintIcon />
            </IconButton>
          </>
        );
      },
      sortable: true,
      wrap: true,
      allowOverflow: true,
      center: true,
      // width: "90px",
    },
  ];

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={2}
      paddingTop={2}
      mb={1}
      width="100%"
    >
      <Grid container alignItems="center" gap={SPACING.SMALL}>
        <Typography>تراکنش های موفق</Typography>
        <Grid container gap={SPACING.SMALL}>
          <Grid>
            <DatePicker
              label="از تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField style={{ width: "160px" }} {...params} />
              )}
              value={selectedDate1}
              onChange={(e) => {
                setSelectedDate1(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
          <Grid>
            <DatePicker
              label="تا تاریخ"
              id="date"
              renderInput={(params) => (
                <TextField style={{ width: "160px" }} {...params} />
              )}
              value={selectedDate2}
              onChange={(e) => {
                setSelectedDate2(moment(e).format("YYYY-MM-DD"));
              }}
            />
          </Grid>
        </Grid>
        <form onSubmit={handleSubmit}>
          <TextField
            id="outlined-basic"
            size="small"
            autocompleted="off"
            label="جستجو"
            variant="outlined"
            style={{ width: 250 }}
            onChange={handleTextChange}
          />
          <Button
            // disabled={!textValue}
            type="submit"
            onClick={handleSubmit}
            endIcon={<RiSearchLine />}
          >
            جستجو
          </Button>
        </form>
        <Tooltip title="خروجی اکسل">
          <a
            href={`${axios.defaults.baseURL}successful_transactions_excel/?date1=${selectedDate1}&date2=${selectedDate2}&key=${userInfo?.userProfile?.key}`}
            rel="noreferrer"
          >
            <Button color="success">
              <RiFileExcel2Fill size={32} />
            </Button>
          </a>
        </Tooltip>
      </Grid>
    </Grid>
  );

  const columnNames = columns.map((column) => column.name);
  const isMobile = window.innerWidth <= 600;

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        format(new Date(item.createDate), "yyyy/MM/dd hh:mm:ss"),
        item.information?.totalRequestNumber,
        item.information?.totalQuantity,
        item.information?.totalQuantity,
        item.payerInfo,
        item.refId,
        item.trackingCode,
        item.cardHolderPan,
        item.orderId,
      ];
    });

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

  return (
    <Grid container justifyContent="center" gap={SPACING.SMALL}>
      <div style={{ visibility: "hidden", position: "absolute" }}>
        <SuccessTransactionRecipt ref={componentRef} item={reciptData} />
      </div>
      {isMobile ? (
        <>
          {tableTitle}
          <BoxList columns={columnNames} data={dataTableM} />
          <Pagination
            count={Math.ceil(totalRows / 10)}
            page={page + 1}
            variant="outlined"
            onChange={(event, newPage) => {
              handleChangePageM(event, newPage - 1);
            }}
          />
        </>
      ) : (
        <PageTable
          title={tableTitle}
          columns={columns}
          data={data}
          progressPending={loading}
          pagination
          paginationServer
          paginationTotalRows={totalRows}
          onChangeRowsPerPage={handlePerRowsChange}
          onChangePage={handlePageChange}
        />
      )}
    </Grid>
  );
};
