import { GetServerSideProps, NextPage } from 'next';
import { useRef } from 'react';
import { useRouter } from 'next/router';
import { Button, Empty, Spin } from 'antd';
import { PrinterOutlined } from '@ant-design/icons';
import { NextSeo } from 'next-seo';
import ReactToPrint from 'react-to-print';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { useQuery } from '@tanstack/react-query';
import { getInvoiceByBookOrderId } from '@/services/bill';
import Logo from '../../../../public/logo-text.png';
import Image from 'next/image';
import { currencyFormatter } from '@/utils/currencyFormatter';
import Unauthorized from '@/pages/unauthorized';
import { BookOrderStatus } from '@/types/book-order';
import { dateTransformer } from '@/utils/timeTransformer';
import { getSupport } from '@/services/company-info';

const ReceiptPage: NextPage = () => {
    const router = useRouter();
    const { bookOrderId } = router.query;
    const buttonRef = useRef<any>();
    let componentRef = useRef<any>() as any;

    const pageStyle = `
        @page {
            size: A4;
            margin: 8mm 10mm;
        }
        
        @media print {
            .quotation {
                margin: 1rem;
                padding: 1rem;
            }
            label {
                font-size: 14px;
            }
            .data {
                font-size: 12px;
            }
            table {
                border-collapse: collapse;
            }
            tbody tr, tbody td, thead tr, thead th {
                border: 1px solid black !important;
            }
            thead tr th {
                font-size: 12px !important;
            }
        }
    `;

    const { isFetching, data } = useQuery({
        queryKey: ['invoice', bookOrderId as string],
        queryFn: async () => {
            const response = await getInvoiceByBookOrderId(bookOrderId as string);

            return response.data;
        },
    });

    const { isFetching: isCompanyInformationFetching, data: companyInformation } = useQuery({
        queryKey: ['companyInformation'],
        queryFn: async () => {
            const response = await getSupport();
            return response.data;
        },
    });

    if (isFetching || isCompanyInformationFetching) {
        return <Spin spinning />;
    }

    if (!data) {
        return <Empty />;
    }

    if (data?.status !== BookOrderStatus.PAID) {
        return <Unauthorized />;
    }

    return (
        <div>
            <NextSeo title={data.displayId} />
            <div className="overflow-x-auto bill">
                <div className="!font-sans ">
                    <div className="bg-white " ref={(el) => (componentRef = el)}>
                        <div id="header">
                            {/* Logo */}
                            <div>
                                <div className="w-[320px]">
                                    <Image src={Logo} alt="Logo" className="w-full h-full" />
                                </div>
                            </div>
                            {/* Title */}
                            <div className="flex justify-end my-5 title">
                                <h1 className="text-3xl font-bold">RECEIPT</h1>
                            </div>

                            {/* Applicant Form */}
                            <div className="flex mt-2 flex-col">
                                <div className="flex flex-row">
                                    <div className="basis-[50%] print:basis-1/2 pr-10">
                                        <label className="inline-block font-semibold mb-3">FROM:</label>
                                        <p className="m-0 mb-2 data">Impact Life Solutions</p>
                                        <p className="m-0 mb-2 data">{companyInformation?.address}</p>
                                        <p className="m-0 mb-2 data">{companyInformation?.contactNumber}</p>
                                    </div>
                                    <div className="basis-[50%] print:basis-1/2 pr-10">
                                        <label className="inline-block font-semibold mb-3">TO:</label>
                                        <p className="m-0 mb-2 data">{data.member?.fullName}</p>
                                        <p className="m-0 mb-2 data">{data.member?.address}</p>
                                        <p className="m-0 mb-2 data">{data.member?.phoneNumber}</p>
                                    </div>
                                </div>
                                <div className="print:basis-1/2 mt-8">
                                    <div className="mb-2">
                                        <span>
                                            <label className="inline-block font-semibold !w-[150px]">DATE</label>:
                                        </span>
                                        <span className="ml-3 data">{dateTransformer(data.updatedAt)}</span>
                                    </div>
                                    <div className="mb-2">
                                        <span>
                                            <label className="inline-block font-semibold !w-[150px]">REF. NUMBER</label>:
                                        </span>
                                        <span className="ml-3 data">{'OR-' + data.displayId}</span>
                                    </div>
                                    {/* <div className="mb-2">
                                    <span>
                                        <label className="inline-block font-semibold !w-[150px]">CUSTOMER ID</label>:
                                    </span>
                                    <span className="ml-3 data">{'[CUSTOMER_ID]'}</span>
                                </div> */}
                                </div>
                            </div>

                            {/* Product Info Form */}
                            <table className="mt-5 w-full">
                                <thead className="text-gray-700 bg-gray-200">
                                    <tr>
                                        <th style={{ width: '10%' }}>No.</th>
                                        <th style={{ width: '55%' }}>PRODUCT</th>
                                        <th style={{ width: '10%' }}>QTY</th>
                                        <th style={{ width: '10%' }}>UNIT PRICE</th>
                                        <th style={{ width: '15%' }}>AMOUNT (MYR)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td className="text-center">{1}</td>
                                        <td className="text-center">{data.book?.name}</td>
                                        <td className="!px-3 text-center data">{data.quantity}</td>
                                        <td className="text-center data">{data.bookPrice}</td>
                                        <td className="text-center data">{currencyFormatter(data.bookPrice * data.quantity)}</td>
                                    </tr>
                                </tbody>
                                <tfoot>
                                    <tr className="leading-loose">
                                        <td colSpan={4} className="text-right !border-0 !pr-2">
                                            <span className="font-semibold data">SUBTOTAL</span>
                                        </td>
                                        <td className="text-center">
                                            <span className="font-bold data">{currencyFormatter(data.bookPrice * data.quantity)}</span>
                                        </td>
                                    </tr>
                                    {/* <tr>
                                    <td colSpan={5} className="text-right !border-0 !pr-2">
                                        <span className="font-bold">
                                            DISCOUNT ({quotation?.quotationInfo.discountUnit === 'Percentage' ? '%' : quotation?.currency})
                                        </span>
                                    </td>
                                    <td className="text-center">
                                        <span className="font-bold">{formatCurrency(quotation?.quotationInfo.discount)}</span>
                                    </td>
                                </tr>
                                <tr>
                                    <td colSpan={5} className="text-right !border-0 !pr-2">
                                        <span className="font-bold">
                                            TAX ({quotation?.quotationInfo.taxUnit === 'Percentage' ? '%' : quotation?.currency})
                                        </span>
                                    </td>
                                    <td className="text-center">
                                        <span className="font-bold">{formatCurrency(quotation?.quotationInfo.tax)}</span>
                                    </td>
                                </tr> */}
                                    <tr>
                                        <td colSpan={4} className="text-right !border-0 !pr-2">
                                            <span className="font-semibold data">TOTAL</span>
                                        </td>
                                        <td className="text-center">
                                            <span className="font-bold data">{currencyFormatter(data.bookPrice * data.quantity)}</span>
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>

                            <div className="mt-5 remark_and_term_and_condition">
                                {/* <div>
                                <h2>Additional Info:</h2>
                                <p className="whitespace-pre-wrap !">{quotation?.quotationInfo.additionalInfo}</p>
                            </div> */}
                                {/* <div className="mt-10 w-[70%] print:w-full">
                                <h2>Terms and Conditions:</h2>
                                <Markup
                                    tagName="p"
                                    className="previewContent !"
                                    content={quotation?.organization.organizationTnC ?? null}
                                />
                                 <p className="break-words whitespace-pre-wrap !">{quotation?.organization.organizationTnC}</p> 
                            </div>*/}
                            </div>
                            <div className="mt-[100px] text-center text-[14px]">
                                <p className="font-bold">THANK YOU FOR YOUR BUSINESS!</p>
                                <p>This is computer generated. No signature is required.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div className="text-center">
                <ReactToPrint
                    pageStyle={pageStyle}
                    trigger={() => (
                        <Button size="large" type="primary" icon={<PrinterOutlined />} ref={buttonRef}>
                            Print
                        </Button>
                    )}
                    content={() => componentRef as any}
                />
            </div>
        </div>
    );
};

export default ReceiptPage;

export const getServerSideProps: GetServerSideProps = async ({ req, locale, resolvedUrl }) => {
    return {
        props: {
            ...(await serverSideTranslations(locale as string, ['bill', 'layout', 'common', 'messages', 'api-messages'])),
        },
    };
};
