import React, { useEffect, useState } from "react";
import Box from "@app-emos/layout/Box";
import { TableView } from "@amxchange/grid-view-web-client";
import ContentWrapper from "@app-emos/layout/ContentWrapper";
import { PAYMENT_VOUCHER_INQUIRY_VIEW_NAME } from "./constants";
import {FETCH_BRANCH_HEADER_DATA, BRANCH_ID} from "../PaymentVoucherCreation/constants"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import approvedReject from "@app-emos/assets/utils/svgs/approved.svg";
import printVoucher from "@app-emos/assets/utils/svgs/print.svg";
import editIcon from "@app-emos/assets/utils/svgs/edit.svg";
import bankChequekIcon from "@app-emos/assets/utils/svgs/bank-check.svg";
import viewIconsvg from "@app-emos/assets/utils/svgs/view.svg";
import disbursementIcon from "@app-emos/assets/utils/svgs/refresh.svg";
import cancelIcon from "@app-emos/assets/utils/svgs/cancel.svg";
import { downloadPdf } from "../../PettyCash/utils/downloadPdf";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import moment from "moment";
import DataService from "@common-services/DataService";
import {
    faEye,
    faPenToSquare,
    faCircleXmark,
    faPrint,
    faMoneyCheck,
    faArrowRightArrowLeft,
    faCircleCheck
} from "@fortawesome/free-solid-svg-icons";
import ToastUtil from "@common-utils/ToastUtil";
import { FETCH_PRINT_DOCUMENT_DATA } from "../PaymentVoucherCreation/constants";
import { AuthService } from "@common-services/AuthService";

function index() {
    const [vatApplicable, setVatApplicabe] = useState(false);
    const [success, setSuccess] = useState(false);
    const [rotate, setRotate] = useState(false);
    const [isVatApplicable, setIsVatApplicable] = useState(false);

    const handleSuccess = () => {
        setSuccess(true);
    };

    const reloadPage = () => {
        // Rotate the button
        setRotate(true);

        // After 2 seconds, reload the page
        setTimeout(() => {
            window.location.reload();
        }, 2000);
    };

    // const handleCLickPrintCPVPVoucher = async voucherId => {
    //     if (!voucherId) return;
    //     const docData = await fetchPrintDataCPVP(voucherId, "CPV");
    //     console.log({ docData: docData });
    //     docData && downloadPdf(docData, "CPV");
    // };

    // const fetchPrintDataCPVP = async (voucherId, documentType) => {
    //     let docData = null;
    //     console.log(voucherId, "fetchPrintDataCPVP");
    //     try {
    //         const response = await DataService.post(FETCH_PRINT_DOCUMENT_DATA, {
    //             pettyCashHeaderId: voucherId,
    //             documentType: documentType
    //         });
    //         if (response.status === "200") {
    //             const docTypes = {
    //                 CPV: "cpvDocument"
    //             };
    //             docData = response.results[0][docTypes[documentType]];
    //             ToastUtil.success(`${documentType} Document Downloaded Successfully`);
    //         } else if (res.response?.data.messageKey) {
    //             ToastUtil.error(res.response?.data.message, res.response?.data.messageKey);
    //         }
    //         console.log(response.data.results[0], "voucher id");
    //     } catch (e) {
    //         console.log(e, "Error fetching print data");
    //     } finally {
    //         return docData;
    //     }
    // };

    const fetchHeaderData = async () => {
        try {
            const res = await DataService.get(`${FETCH_BRANCH_HEADER_DATA}?branchId=${BRANCH_ID}`);
            setIsVatApplicable(res.data.results[0].vatApplicable);
        } catch (err) {
            console.error("Error while fetching header Data ", err);
        }
    };

    useEffect(() => {
        fetchHeaderData();
    }, []);

    const handleCLickPrintCPVPVoucher = async (voucherId, docType) => {
        if (AuthService.isActionAllowed("PAYMENT_VOUCHER.INQUIRY", ["DOWNLOAD"])) {
            if (!voucherId) return;
            const docTypes = {
                CPVP: "CPVP"
            };
            const docData = await fetchPrintDataCPVP(voucherId, "CPVP");
            docData && downloadPdf(docData, docTypes[docType], isVatApplicable);
        } else {
            ToastUtil.error("Permission for this action is not present!!", "ACTION_NOT_ALLOWED");
        }
    };

    const fetchPrintDataCPVP = async voucherId => {
        let docData = null;
        console.log(voucherId, "fetchPrintData");
        try {
            const response = await DataService.post(`/api/paymentvoucher/print-voucher`, {
                voucherId: voucherId
            });
            if (response.status === "200") {
                // console.log({ response: response.results[0] }, "auaauauau");

                docData = response.results[0];
                ToastUtil.success(`Document Downloaded Successfully`);
            }
            console.log(response.data.results[0], "voucher id");
        } catch (e) {
            console.log(e, "Error fetching print data");
        } finally {
            return docData;
        }
    };

    const handleCLickPrintVoucher = async (voucherId, docType) => {
        const permission = "PAYMENT_VOUCHER.INQUIRY";
        const actions = ["DOWNLOAD"];
        if (AuthService.isActionAllowed(permission, actions)) {
            if (!voucherId) return;
            const docTypes = {
                BC: "BCV",
                BW: "BWV"
            };
            const docData = await fetchPrintData(voucherId, "BCWC");
            docData && downloadPdf(docData, docTypes[docType],isVatApplicable);
        } else {
            ToastUtil.error("You are not authorized to download this document");
        }
    };

    const fetchPrintData = async voucherId => {
        let docData = null;
        console.log(voucherId, "fetchPrintData");
        try {
            const response = await DataService.post(`/api/paymentvoucher/print-voucher`, {
                voucherId: voucherId
            });
            if (response.status === "200") {
                // console.log({ response: response.results[0] }, "auaauauau");

                docData = response.results[0];
                ToastUtil.success(`Document Downloaded Successfully`);
            }
            console.log(response.data.results[0], "voucher id");
        } catch (e) {
            console.log(e, "Error fetching print data");
        } finally {
            return docData;
        }
    };

    const getParticularDayOfMonth = (dayFlag = "F") => {
        const date = new Date();
        const currYear = date.getFullYear();
        const currMonth = date.getMonth();
        if (dayFlag === "L") {
            const lastDayOfMonth = new Date(currYear, currMonth + 1, 0);
            return lastDayOfMonth.valueOf(); //timestamp
        } else if (dayFlag === "F") {
            const firstDayOfMonth = new Date(currYear, currMonth, 1);
            return firstDayOfMonth.valueOf(); //timestamp
        } else {
            return date.valueOf(); // Return current date timestamp if dayFlag is not "F" or "L"
        }
    };

    const history = useHistory();

    const handleClick = voucherId => {
        console.log("Payment View");
        const permission = "PAYMENT_VOUCHER.INQUIRY";
        const actions = ["VIEW"];

        if (AuthService.isActionAllowed(permission, actions)) {
            history.push(`/emos/app/payment-voucher/view/voucherId=${voucherId}`);
        } else {
            ToastUtil.error("You are not authorized to perform this action");
        }
    };

    const handleEditClick = voucherId => {
        const permission = "PAYMENT_VOUCHER.INQUIRY";
        const actions = ["EDIT"];
        if (AuthService.isActionAllowed(permission, actions)) {
            history.push(`/emos/app/payment-voucher/edit/voucherId=${voucherId}`);
        } else {
            ToastUtil.error("You are not authorized to perform this action");
        }
    };

    const handleApproveClick = pvHeaderId => {
        const permission = "PAYMENT_VOUCHER.INQUIRY";
        const actions = ["APPROVE"];
        if (AuthService.isActionAllowed(permission, actions)) {
            history.push(`/emos/app/payment-voucher/approve-reject/pvHeaderId=${pvHeaderId}`);
        } else {
            ToastUtil.error("You are not authorized to perform this action");
        }
    };

    const handleDisbursementClick = pvHeaderId => {
        const permission = "PAYMENT_VOUCHER.INQUIRY";
        const actions = ["DISBURSEMENT"];
        if (AuthService.isActionAllowed(permission, actions)) {
            history.push(`/emos/app/payment-voucher/disbursement/pvHeaderId=${pvHeaderId}`);
        } else {
            ToastUtil.error("You are not authorized to perform this action");
        }
    };

    const handlePrintChequeClick = pvHeaderId => {
        const permission = "PAYMENT_VOUCHER.INQUIRY";
        const actions = ["DOWNLOAD_CHEQUE"];
        if (AuthService.isActionAllowed(permission, actions)) {
            history.push(`/emos/app/payment-voucher/print-cheque/pvHeaderId=${pvHeaderId}`);
        } else {
            ToastUtil.error("You are not authorized to perform this action");
        }
    };

    const handlePrintCancellationClick = pvHeaderId => {
        const permission = "PAYMENT_VOUCHER.INQUIRY";
        const actions = ["CANCEL_VOUCHER"];
        if (AuthService.isActionAllowed(permission, actions)) {
            history.push(`/emos/app/payment-voucher/cancellation/pvHeaderId=${pvHeaderId}`);
        } else {
            ToastUtil.error("You are not authorized to perform this action");
        }
    };
    return (
        <ContentWrapper containerClass={"payment-voucher-creation"}>
            <Box title={`Payment Voucher Inquiry`}>
                <div className="reload-page">
                    <svg
                        className={`icon ${rotate ? "rotate" : ""}`}
                        height="24"
                        viewBox="0 0 24 24"
                        width="24"
                        xmlns="http://www.w3.org/2000/svg"
                        style={{
                            fill: "rgb(60,98,115)",
                            position: "relative",
                            bottom: "50px",
                            left: "95%",
                            fontWeight: "bold",
                            cursor: "pointer"
                        }}
                        onClick={reloadPage}
                    >
                        <path
                            d="m23.8995816 10.3992354c0 .1000066-.1004184.1000066-.1004184.2000132 0 0 0 .1000066-.1004184.1000066-.1004184.1000066-.2008369.2000132-.3012553.2000132-.1004184.1000066-.3012552.1000066-.4016736.1000066h-6.0251046c-.6025105 0-1.0041841-.4000264-1.0041841-1.00006592 0-.60003954.4016736-1.00006591 1.0041841-1.00006591h3.5146443l-2.8117154-2.60017136c-.9037657-.90005932-1.9079498-1.50009886-3.0125523-1.90012523-2.0083682-.70004614-4.2175733-.60003954-6.12552305.30001977-2.0083682.90005932-3.41422594 2.50016478-4.11715481 4.5002966-.20083682.50003295-.80334728.80005275-1.30543933.60003954-.50209205-.10000659-.80334728-.70004613-.60251046-1.20007909.90376569-2.60017136 2.71129707-4.60030318 5.12133891-5.70037568 2.41004184-1.20007909 5.12133894-1.30008569 7.63179914-.40002637 1.4058578.50003296 2.7112971 1.30008569 3.7154812 2.40015819l3.0125523 2.70017795v-3.70024386c0-.60003955.4016736-1.00006591 1.0041841-1.00006591s1.0041841.40002636 1.0041841 1.00006591v6.00039545.10000662c0 .1000066 0 .2000132-.1004184.3000197zm-3.1129707 3.7002439c-.5020921-.2000132-1.1046025.1000066-1.3054394.6000396-.4016736 1.1000725-1.0041841 2.200145-1.9079497 3.0001977-1.4058578 1.5000989-3.5146444 2.3001516-5.623431 2.3001516-2.10878662 0-4.11715482-.8000527-5.72384938-2.4001582l-2.81171548-2.6001714h3.51464435c.60251046 0 1.0041841-.4000263 1.0041841-1.0000659 0-.6000395-.40167364-1.0000659-1.0041841-1.0000659h-6.0251046c-.10041841 0-.10041841 0-.20083682 0s-.10041841 0-.20083682 0c0 0-.10041841 0-.10041841.1000066-.10041841 0-.20083682.1000066-.20083682.2000132s0 .1000066-.10041841.1000066c0 .1000066-.10041841.1000066-.10041841.2000132v.2000131.1000066 6.0003955c0 .6000395.40167364 1.0000659 1.0041841 1.0000659s1.0041841-.4000264 1.0041841-1.0000659v-3.7002439l2.91213389 2.8001846c1.80753138 2.0001318 4.31799163 3.0001977 7.02928871 3.0001977 2.7112971 0 5.2217573-1.0000659 7.1297071-2.9001911 1.0041841-1.0000659 1.9079498-2.3001516 2.4100418-3.7002439.1004185-.6000395-.2008368-1.2000791-.7029288-1.3000857z"
                            transform=""
                        />
                    </svg>
                </div>
                <TableView
                    view={`${PAYMENT_VOUCHER_INQUIRY_VIEW_NAME}`}
                    additionalColumns={[
                        {
                            accessor: "noKey",
                            Header: "ACTION",
                            width: 250,
                            Cell: row => {
                                const { DOCUMENT_STATUS } = row.original;
                                const { VOUCHER_TYPE_DESC } = row.original;
                                // const {DISBURSEMENT_REF} = row.original
                                const { VCHTYP } = row.original;
                                // const { STATUS_DESC } = row.original;
                                const showSpecificIcons = DOCUMENT_STATUS === "Y";
                                const viewIcon = DOCUMENT_STATUS === "C";
                                const unApprovedIcons = DOCUMENT_STATUS === "U";
                                const rejectIcons = DOCUMENT_STATUS === "R";
                                const showPrintVoucehr = VOUCHER_TYPE_DESC === "Bank Payment With Cheque";
                                // const disbursementCancelIcon = DISBURSEMENT_REF === !null;
                                // const showDisbursement
                                const printCashPayment = VOUCHER_TYPE_DESC === "Cash Payment";
                                // console.log(DOC_STATUS.status);
                                return (
                                    <div
                                        style={{
                                            width: "100%",
                                            display: "flex",
                                            justifyContent: "flex-start",
                                            alignItems: "center",
                                            gap: "1rem",
                                            marginLeft: "10px"
                                        }}
                                    >
                                        {viewIcon && (
                                            <img
                                                style={{
                                                    width: "2rem",
                                                    display: "inline-block",
                                                    borderRadius: "50%",
                                                    transition: "transform 0.3s ease-in-out, filter 0.3s ease-in-out",
                                                    cursor: "pointer"
                                                }}
                                                title="View Voucher"
                                                src={viewIconsvg}
                                                onClick={() => handleClick(row.original.PV_HEADER_ID)}
                                                onMouseEnter={e => {
                                                    e.target.style.opacity = 1;
                                                    e.target.style.backgroundColor = "none";
                                                }}
                                                onMouseLeave={e => {
                                                    e.target.style.opacity = 1;
                                                    e.target.style.backgroundColor = "white";
                                                }}
                                            />
                                        )}

                                        {showSpecificIcons && !viewIcon && (
                                            <>
                                                <img
                                                    style={{
                                                        width: "2rem",
                                                        display: "inline-block",
                                                        borderRadius: "50%",
                                                        transition:
                                                            "transform 0.3s ease-in-out, filter 0.3s ease-in-out",
                                                        cursor: "pointer"
                                                    }}
                                                    title="View Voucher"
                                                    src={viewIconsvg}
                                                    onClick={() => handleClick(row.original.PV_HEADER_ID)}
                                                    onMouseEnter={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "none";
                                                    }}
                                                    onMouseLeave={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "white";
                                                    }}
                                                />
                                                <img
                                                    style={{
                                                        width: "2rem",
                                                        height: "30px",
                                                        display: "inline-block",
                                                        borderRadius: "50%",
                                                        transition:
                                                            "transform 0.3s ease-in-out, filter 0.3s ease-in-out",
                                                        cursor: "pointer"
                                                    }}
                                                    src={disbursementIcon}
                                                    title="Disbursement Voucher"
                                                    cursor={"pointer"}
                                                    onClick={() => handleDisbursementClick(row.original.PV_HEADER_ID)}
                                                    onMouseEnter={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "none";
                                                    }}
                                                    onMouseLeave={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "white";
                                                    }}
                                                />
                                                <img
                                                    style={{
                                                        width: "2rem",
                                                        height: "30px",
                                                        display: "inline-block",
                                                        borderRadius: "50%",
                                                        transition:
                                                            "transform 0.3s ease-in-out, filter 0.3s ease-in-out",
                                                        cursor: "pointer"
                                                    }}
                                                    src={printVoucher}
                                                    title="Print Voucher"
                                                    onClick={() =>
                                                        printCashPayment
                                                            ? handleCLickPrintCPVPVoucher(
                                                                  row.original.PV_HEADER_ID,
                                                                  "CPVP"
                                                              )
                                                            : handleCLickPrintVoucher(
                                                                  row.original.PV_HEADER_ID,
                                                                  row.original.VCHTYP
                                                              )
                                                    }
                                                    onMouseEnter={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "none";
                                                    }}
                                                    onMouseLeave={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "white";
                                                    }}
                                                />
                                                <img
                                                    style={{
                                                        width: "2rem",
                                                        height: "30px",
                                                        display: "inline-block",
                                                        borderRadius: "50%",
                                                        transition:
                                                            "transform 0.3s ease-in-out, filter 0.3s ease-in-out",
                                                        cursor: "pointer"
                                                    }}
                                                    src={cancelIcon}
                                                    title="Cancel Voucher"
                                                    onClick={() =>
                                                        handlePrintCancellationClick(row.original.PV_HEADER_ID)
                                                    }
                                                    onMouseEnter={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "none";
                                                    }}
                                                    onMouseLeave={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "white";
                                                    }}
                                                />
                                            </>
                                        )}

                                        {unApprovedIcons && (
                                            <>
                                                <img
                                                    style={{
                                                        width: "2rem",
                                                        display: "inline-block",
                                                        borderRadius: "50%",
                                                        transition:
                                                            "transform 0.3s ease-in-out, filter 0.3s ease-in-out",
                                                        cursor: "pointer"
                                                    }}
                                                    title="View Voucher"
                                                    src={viewIconsvg}
                                                    onClick={() => handleClick(row.original.PV_HEADER_ID)}
                                                    onMouseEnter={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "none";
                                                    }}
                                                    onMouseLeave={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "white";
                                                    }}
                                                />
                                                <img
                                                    style={{
                                                        width: "2rem",
                                                        display: "inline-block",
                                                        borderRadius: "50%",
                                                        transition:
                                                            "transform 0.3s ease-in-out, filter 0.3s ease-in-out",
                                                        cursor: "pointer"
                                                    }}
                                                    src={editIcon}
                                                    title="Edit Voucher"
                                                    onClick={() => handleEditClick(row.original.PV_HEADER_ID)}
                                                    onMouseEnter={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "none";
                                                    }}
                                                    onMouseLeave={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "white";
                                                    }}
                                                />
                                                <img
                                                    style={{
                                                        width: "2rem",
                                                        height: "30px",
                                                        display: "inline-block",
                                                        borderRadius: "50%",
                                                        transition:
                                                            "transform 0.3s ease-in-out, filter 0.3s ease-in-out",
                                                        cursor: "pointer"
                                                    }}
                                                    src={printVoucher}
                                                    title="Print Voucher"
                                                    onClick={() =>
                                                        printCashPayment
                                                            ? handleCLickPrintCPVPVoucher(
                                                                  row.original.PV_HEADER_ID,
                                                                  "CPVP"
                                                              )
                                                            : handleCLickPrintVoucher(
                                                                  row.original.PV_HEADER_ID,
                                                                  row.original.VCHTYP
                                                              )
                                                    }
                                                    onMouseEnter={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "none";
                                                    }}
                                                    onMouseLeave={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "white";
                                                    }}
                                                />
                                                <img
                                                    src={approvedReject}
                                                    alt="Approve Reject"
                                                    style={{
                                                        width: "2rem",
                                                        height: "30px",
                                                        display: "inline-block",
                                                        borderRadius: "50%",
                                                        transition:
                                                            "transform 0.3s ease-in-out, filter 0.3s ease-in-out",
                                                        cursor: "pointer"
                                                    }}
                                                    title="Approve Reject"
                                                    onClick={() => handleApproveClick(row.original.PV_HEADER_ID)}
                                                    onMouseEnter={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "none";
                                                    }}
                                                    onMouseLeave={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "white";
                                                    }}
                                                />
                                                {showPrintVoucehr && (
                                                    <img
                                                        style={{
                                                            width: "2rem",
                                                            color: "red",
                                                            display: "inline-block",
                                                            borderRadius: "50%",
                                                            transition:
                                                                "transform 0.3s ease-in-out, filter 0.3s ease-in-out",
                                                            cursor: "pointer"
                                                        }}
                                                        src={bankChequekIcon}
                                                        title="Print Cheque"
                                                        onClick={() =>
                                                            handlePrintChequeClick(row.original.PV_HEADER_ID)
                                                        }
                                                        onMouseEnter={e => {
                                                            e.target.style.opacity = 1;
                                                            e.target.style.backgroundColor = "none";
                                                        }}
                                                        onMouseLeave={e => {
                                                            e.target.style.opacity = 1;
                                                            e.target.style.backgroundColor = "white";
                                                        }}
                                                    />
                                                )}
                                            </>
                                        )}

                                        {rejectIcons && (
                                            <>
                                                <img
                                                    style={{
                                                        width: "2rem",
                                                        display: "inline-block",
                                                        borderRadius: "50%",
                                                        transition:
                                                            "transform 0.3s ease-in-out, filter 0.3s ease-in-out",
                                                        cursor: "pointer"
                                                    }}
                                                    title="View Voucher"
                                                    src={viewIconsvg}
                                                    onClick={() => handleClick(row.original.PV_HEADER_ID)}
                                                    onMouseEnter={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "none";
                                                    }}
                                                    onMouseLeave={e => {
                                                        e.target.style.opacity = 1;
                                                        e.target.style.backgroundColor = "white";
                                                    }}
                                                />
                                            </>
                                        )}
                                    </div>
                                );
                            }
                        }
                    ]}
                    overrideColumns={[
                        {
                            accessor: "DOCUMENT_DATE",
                            Cell: row => <span>{moment(row.original.DOCUMENT_DATE).format("DD-MM-YYYY")}</span>,
                            Header: "DATE",
                            width: 200
                        },
                        {
                            accessor: "VOUCHER_TYPE_DESC",
                            Header: "VOUCHER TYPE",
                            width: 300
                        },
                        {
                            Header: "VAT AMOUNT",
                            accessor: "VAT_AMOUNT",
                            show: isVatApplicable,
                            Cell: row => {
                                return <div>{row.value}</div>;
                            }
                        }
                    ]}
                    filterConfig={{
                        /* Setting default Vals for Status, from date and to date*/

                        FROM_DATE_FILTER: {
                            defaultValue: getParticularDayOfMonth("F")
                        },
                        TO_DATE_FILTER: {
                            defaultValue: new Date().valueOf(),
                            disableFuture: true
                        }
                    }}
                    defaultPageSize={5}
                    extraConfig={{
                        sortColumn: "DOCUMENT_DATE" && "PV_HEADER_ID",
                        sortOrder: "DESC"
                    }}
                />
            </Box>
        </ContentWrapper>
    );
}

export default index;
