import {
  Button,
  Checkbox,
  FormControlLabel,
  IconButton,
  TextField,
  Tooltip,
} from "@mui/material";
import axios from "axios";
import { useContext, useEffect, useState } from "react";
// import { RiFileExcel2Fill } from "react-icons/ri";
// import { useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import moment from "moment";
import { DatePicker } from "@mui/x-date-pickers";
import { AppContext } from "../../../../contexts/AppContext";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatJustDate } from "../../../../utils/formatTime";
import { RiFileExcel2Fill } from "react-icons/ri";
import { useDispatch, useSelector } from "react-redux";
import { ProvinceKillHousePaidFeeEditDescription } from "../province-killhouse-paid-fee-edit-description/ProvinceKillHousePaidFeeEditDescription";
import EditIcon from "@mui/icons-material/Edit";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
  OPEN_MODAL,
} from "../../../../lib/redux/slices/appSlice";
import ProvinceKillhousePaidFeeChangePaymentType from "../province-killhouse-paid-fee-change-payment-type/ProvinceKillhousePaidFeeChangePaymentType";
import ShowImage from "../../../../components/show-image/ShowImage";
import { ProvinceWagePaymentTransactionsUploadDoc } from "../province-wage-payment-transactions-upload-doc/ProvinceWagePaymentTransactionsUploadDoc";
import { ProvinceWagePaymentCreateTransaction } from "../province-wage-payment-create-transaction/ProvinceWagePaymentCreateTransaction";
import { ProvinceWagePaymentTransactionsOperations } from "../province-wage-payment-transactions-operations/ProvinceWagePaymentTransactionsOperations";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { RiSearchLine } from "react-icons/ri";

export const ProvinceWagePaymentTransactions = ({ province }) => {
  //   const authToken = useSelector((state) => state.userSlice.authToken);
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [page, setPage] = useState(1);
  const [withDate, setWithDate] = useState(false);
  const dispatch = useDispatch();
  const [textValue, setTextValue] = useState("");
  const userKey = useSelector((state) => state.userSlice.userProfile.key);
  const [tableData, setTableData] = useState([]);

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

  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

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

  const fetchApiData = async (page) => {
    const response = await axios.get(
      `${
        province ? province + "parent-company-" : ""
      }total-internal-transactions/?search=filter&value=${textValue}&page=${page}&role=${getRoleFromUrl()}&page_size=${perPage}${
        withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
      }`
    );
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    dispatch(LOADING_START());
    try {
      const response = await axios.get(
        `${
          province ? province + "parent-company-" : ""
        }total-internal-transactions/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}${
          withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : ``
        }`
      );
      setData(response.data.results);
      setTotalRows(response.data.count);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

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

  const getOthersShare = (item) => {
    if (
      getRoleFromUrl() === "AdminX" ||
      getRoleFromUrl() === "SuperAdmin" ||
      getRoleFromUrl() === "ProvinceOperator"
    ) {
      return [
        item?.guildsShare?.toLocaleString(),
        item?.companyShare?.toLocaleString(),
        item?.otherShare?.toLocaleString(),
      ];
    } else {
      return [];
    }
  };

  const getRoleColumns = () => {
    if (
      getRoleFromUrl() === "AdminX" ||
      getRoleFromUrl() === "SuperAdmin" ||
      getRoleFromUrl() === "ProvinceOperator"
    ) {
      return ["سهم صنف (﷼)", "سهم شرکت (﷼)", "سهم دامپزشک (﷼)"];
    } else {
      return [];
    }
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        `${
          item?.payerType === "kill_house"
            ? `کشتارگاه / کشتارکن ${item?.killHouse?.name}`
            : item?.payerType === "chain_company"
            ? `شرکت زنجیره ${item?.chainCompany?.name}`
            : `خریدار (${
                item?.outProvincePoultryRequestBuyer?.unitName
                  ? item?.outProvincePoultryRequestBuyer?.unitName
                  : "-"
              })`
        }`,
        formatJustDate(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={fetchApiData}
                        item={item}
                      />
                    ),
                  })
                );
              }}
            >
              <EditIcon />
            </IconButton>
          </Grid>
        ) : item?.transactionType === "wage-gateway-auto" ? (
          "آنلاین"
        ) : item?.transactionType === "correspondence" ? (
          "مکاتبات"
        ) : (
          "دستی"
        ),
        item?.refId,
        item?.orderId,
        `${item?.payerInfo?.fullname} (${item?.payerInfo?.mobile})`,
        item?.cardHolderPan,
        item?.transactionAmount.toLocaleString(),
        item?.unionShare?.toLocaleString(),
        ...getOthersShare(item),
        item?.image &&
        (getRoleFromUrl() === "AdminX" || getRoleFromUrl() === "SuperAdmin") ? (
          <Grid mt={1}>
            <ShowImage src={item?.image} />
            <ProvinceWagePaymentTransactionsUploadDoc
              key={item.key}
              isSingular
              item={item}
              updateTable={fetchApiData}
            />
          </Grid>
        ) : getRoleFromUrl() === "ParentCompany" ? (
          <ShowImage src={item?.image} />
        ) : (
          <ProvinceWagePaymentTransactionsUploadDoc
            key={item.key}
            isSingular
            item={item}
            updateTable={fetchApiData}
          />
        ),
        getRoleFromUrl() === "SuperAdmin" || getRoleFromUrl() === "AdminX" ? (
          <Grid container xs={12} alignItems="center">
            {item?.description ? item?.description : "-"}{" "}
            <IconButton
              aria-label="delete"
              color="primary"
              onClick={() => {
                dispatch(
                  OPEN_MODAL({
                    title: "ویرایش توضیحات",
                    content: (
                      <ProvinceKillHousePaidFeeEditDescription
                        fetchApiData={fetchApiData}
                        item={item}
                      />
                    ),
                  })
                );
              }}
            >
              <EditIcon />
            </IconButton>
          </Grid>
        ) : item?.description ? (
          item?.description
        ) : (
          "-"
        ),
        <ProvinceWagePaymentTransactionsOperations
          key={i}
          item={item}
          fetchApiData={fetchApiData}
        />,
      ];
    });

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

  return (
    <Grid container justifyContent="end">
      <Grid
        container
        alignItems="center"
        justifyContent="space-between"
        gap={2}
        paddingTop={2}
        mb={1}
        width="100%"
      >
        <Grid container alignItems="center" gap={SPACING.SMALL}>
          {getRoleFromUrl() === "AdminX" && (
            <Button
              variant="contained"
              onClick={() => {
                dispatch(
                  DRAWER({
                    title: "ایجاد تراکنش",
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    content: (
                      <ProvinceWagePaymentCreateTransaction
                        fetchApiData={fetchApiData}
                      />
                    ),
                  })
                );
              }}
            >
              ایجاد تراکنش
            </Button>
          )}
          <Grid
            container
            style={{
              borderStyle: "solid",
              borderWidth: "1px",
              padding: "10px",
              borderRadius: "15px",
              borderColor: "gray",
              justifyContent: "left",
            }}
          >
            <Grid>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={withDate}
                    onChange={() => setWithDate(!withDate)}
                    color="primary"
                  />
                }
              />
            </Grid>
            <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>
          <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>
            <Tooltip title="خروجی اکسل">
              <a
                href={`${
                  province ? province : axios.defaults.baseURL
                }payment_transactions_province_excel/?role=${getRoleFromUrl()}&key=${userKey}${
                  withDate
                    ? `&date1=${selectedDate1}&date2=${selectedDate2}`
                    : ``
                }`}
                rel="noreferrer"
              >
                <Button color="success">
                  <RiFileExcel2Fill size={32} />
                </Button>
              </a>
            </Tooltip>
          </Grid>
        </Grid>
      </Grid>

      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "ماهیت تراکنش",
          "تاریخ پرداخت",
          "نوع پرداخت",
          "شماره پیگیری",
          "شماره درخواست",
          "پرداخت کننده",
          "شماره کارت",
          "مبلغ کل",
          "سهم اتحادیه (﷼)",
          ...getRoleColumns(),
          "تصویر تراکنش",
          "توضیحات",
          ...(getRoleFromUrl() === "AdminX" ? ["عملیات"] : []),
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title={
          getRoleFromUrl() === "ParentCompany" ? "تراکنش ها" : "ثبت تراکنش ها"
        }
      />
    </Grid>
  );
};
