import {
  Button,
  Checkbox,
  IconButton,
  Popover,
  TextField,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  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 ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { AppContext } from "../../../../contexts/AppContext";
import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined";
import ToggleOnIcon from "@mui/icons-material/ToggleOn";
import {
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import { useReactToPrint } from "react-to-print";
import SuccessTransactionRecipt from "../success-transaction-recipt/SuccessTransactionRecipt";
import EditIcon from "@mui/icons-material/Edit";
import { Grid } from "../../../../components/grid/Grid";
import ProvinceKillhousePaidFeeChangePaymentType from "../province-killhouse-paid-fee-change-payment-type/ProvinceKillhousePaidFeeChangePaymentType";
import ProvincePaymentFactorFile from "../province-payment-factor-file/ProvincePaymentFactorFile";
import ArticleIcon from "@mui/icons-material/Article";
import DescriptionIcon from "@mui/icons-material/Description";
import { useContext, useEffect, useRef, useState } from "react";
import PrintIcon from "@mui/icons-material/Print";
import TuneIcon from "@mui/icons-material/Tune";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatJustDate, formatJustTime } from "../../../../utils/formatTime";
import { SPACING } from "../../../../data/spacing";
import { ProvinceKillHousePaidFeeEditDescription } from "../province-killhouse-paid-fee-edit-description/ProvinceKillHousePaidFeeEditDescription";
import { RiSearchLine } from "react-icons/ri";

export const ProvinceKillhousePaidFee = ({ killhouseKey, type }) => {
  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 [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 [withDate, setWithDate] = useState(false);

  const fetchApiData = async (page) => {
    dispatch(LOADING_START());
    const response = await axios.get(
      `internal-transactions/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&type=paid&${type}=${killhouseKey}&role=${getRoleFromUrl()}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }`
    );

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

  const [reciptData, setReciptData] = useState();

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

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

  // factor pdf

  const [factorData, setFactorData] = useState();

  const componentFactorRef = useRef();

  const printFactorPDF = useReactToPrint({
    content: () => componentFactorRef.current,
    documentTitle: `فاکتور پرداخت`,
    pageStyle: `
      @page {
        size: landscape;
        margin: 0;
        dir: rtl;
        margin: 20px;
      }
      body {
        -webkit-print-color-adjust: exact;
      }
    `,
  });

  const setFactorPdfOptions = (item) => {
    setFactorData(item);
    setTimeout(() => {
      printFactorPDF();
    }, 1);
  };

  const KillhousePaidFeeActions = ({ item }) => {
    const [anchorEl, setAnchorEl] = useState(null);

    const handleClick = (event) => {
      setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
      setAnchorEl(null);
    };

    const open = Boolean(anchorEl);
    const id = open ? `paid-fee-actions-${item?.key}` : undefined;

    const handlePrint = () => {
      handleClose();
      setPdfOptions(item);
    };

    const handleFactor = (isUnion) => {
      handleClose();
      setFactorPdfOptions({ item, isUnion });
    };

    return (
      <div>
        <IconButton
          aria-describedby={id}
          color="primary"
          onClick={handleClick}
          size="small"
        >
          <TuneIcon fontSize="small" />
        </IconButton>
        <Popover
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "right",
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left",
          }}
          id={id}
          open={open}
          anchorEl={anchorEl}
          onClose={handleClose}
        >
          <List sx={{ p: 1 }}>
            <ListItem disablePadding>
              <ListItemButton
                sx={{ color: "error.main" }}
                onClick={handlePrint}
              >
                <ListItemIcon sx={{ minWidth: 36, color: "inherit" }}>
                  <PrintIcon fontSize="small" />
                </ListItemIcon>
                <Typography variant="body2" color="inherit">
                  چاپ رسید
                </Typography>
              </ListItemButton>
            </ListItem>
            <ListItem disablePadding>
              <ListItemButton
                sx={{ color: "primary.main" }}
                onClick={() => handleFactor(true)}
              >
                <ListItemIcon sx={{ minWidth: 36, color: "inherit" }}>
                  <ArticleIcon fontSize="small" />
                </ListItemIcon>
                <Typography variant="body2" color="inherit">
                  فاکتور اتحادیه
                </Typography>
              </ListItemButton>
            </ListItem>
            <ListItem disablePadding>
              <ListItemButton
                sx={{ color: "success.main" }}
                onClick={() => handleFactor(false)}
              >
                <ListItemIcon sx={{ minWidth: 36, color: "inherit" }}>
                  <DescriptionIcon fontSize="small" />
                </ListItemIcon>
                <Typography variant="body2" color="inherit">
                  فاکتور سامانه
                </Typography>
              </ListItemButton>
            </ListItem>
          </List>
        </Popover>
      </div>
    );
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${formatJustDate(item.date)} ساعت (${formatJustTime(item.date)})`,
        getRoleFromUrl() === "SuperAdmin" ? (
          <Grid container xs={12} alignItems="center">
            {item?.transactionType === "wage-gateway-auto"
              ? "آنلاین"
              : item?.transactionType === "correspondence"
              ? "مکاتبات"
              : "دستی"}
            <IconButton
              aria-label="delete"
              color="primary"
              onClick={() => {
                dispatch(
                  OPEN_MODAL({
                    title: "ویرایش نوع پرداخت",
                    content: (
                      <ProvinceKillhousePaidFeeChangePaymentType
                        fetchApiData={updateTable}
                        item={item}
                      />
                    ),
                  })
                );
              }}
            >
              <EditIcon />
            </IconButton>
          </Grid>
        ) : item?.transactionType === "wage-gateway-auto" ? (
          "آنلاین"
        ) : item?.transactionType === "correspondence" ? (
          "مکاتبات"
        ) : (
          "دستی"
        ),
        `${item?.payerInfo?.fullname} (${item?.payerInfo?.mobile})`,
        item?.orderId,
        item?.refId,
        item?.orderId,
        item?.cardHolderPan,
        item?.transactionAmount?.toLocaleString(),
        getRoleFromUrl() === "SuperAdmin" ? (
          <Grid container xs={12} alignItems="center">
            {item?.description ? item?.description : "-"}{" "}
            <IconButton
              aria-label="delete"
              color="primary"
              onClick={() => {
                dispatch(
                  OPEN_MODAL({
                    title: "ویرایش توضیحات",
                    content: (
                      <ProvinceKillHousePaidFeeEditDescription
                        fetchApiData={updateTable}
                        item={item}
                      />
                    ),
                  })
                );
              }}
            >
              <EditIcon />
            </IconButton>
          </Grid>
        ) : item?.description ? (
          item?.description
        ) : (
          "-"
        ),
        <KillhousePaidFeeActions key={item?.key ?? i} item={item} />,
      ];
    });

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

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

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

    try {
      const response = await axios.get(
        `internal-transactions/?search=filter&value=${textValue}&page=${page}&page_size=${perPage}&type=paid&${type}=${killhouseKey}&role=${getRoleFromUrl()}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }`
      );
      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}>
      <Grid
        container
        alignItems="center"
        justifyContent="space-between"
        gap={2}
        paddingTop={2}
        mb={1}
        width="100%"
      >
        <div style={{ visibility: "hidden", position: "absolute" }}>
          <SuccessTransactionRecipt
            ref={componentRef}
            item={reciptData}
            isPayment
          />
          <ProvincePaymentFactorFile
            ref={componentFactorRef}
            item={factorData?.item}
            user={factorData?.item?.killHouse?.killHouseOperator?.user}
            union={factorData?.item?.unionInfo}
            isUnion={factorData?.isUnion}
          />
        </div>

        <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 container alignItems="center" gap={SPACING.SMALL}>
          <form onSubmit={handleSubmit}>
            <TextField
              id="outlined-basic"
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              onChange={handleTextChange}
            />
            <Button
              // disabled={!textValue}
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </form>
        </Grid>
      </Grid>

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