import { GetServerSideProps, NextPage } from 'next';
import { useRef } from 'react';
import { useRouter } from 'next/router';
import { Button, Divider, 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 { getInvoiceByBookTokenSubscriptionId } from '@/services/bill';
import Logo from '../../../../public/logo-text.png';
import Image from 'next/image';
import { currencyFormatter } from '@/utils/currencyFormatter';
import HtmlParser from '@/components/HtmlParser';
import { dateTransformer } from '@/utils/timeTransformer';
import { getSupport } from '@/services/company-info';

const InvoicePage: NextPage = () => {
    const router = useRouter();
    const { bookTokenSubscriptionId } = router.query;
    const buttonRef = useRef<HTMLButtonElement>(null); // Type button ref
    const componentRef = useRef<HTMLDivElement | null>(null); // Type div ref

    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', bookTokenSubscriptionId as string],
        queryFn: async () => {
            const response = await getInvoiceByBookTokenSubscriptionId(bookTokenSubscriptionId as string);
            return response.data;
        },
    });

    const { isFetching: isBankDetailFetching, data: bankDetails } = useQuery({
        queryKey: ['companyInformation'],
        queryFn: async () => {
            const response = await getSupport();
            return response.data;
        },
    });

    return isFetching || isBankDetailFetching ? (
        <Spin spinning />
    ) : !data ? (
        <Empty />
    ) : (
        <div>
            <NextSeo title={data.displayId} />
            <div className="overflow-x-auto bill">
                <div className="!font-sans">
                    <div className="bg-white" ref={componentRef}>
                        <div id="header">
                            {/* Logo */}
                            <div>
                                <div className="w-[320px]">
                                    <Image src={Logo} alt="Logo" width={320} height={100} />
                                </div>
                            </div>
                            {/* Title */}
                            <div className="flex justify-end my-5 title">
                                <h1 className="text-3xl font-bold">INVOICE</h1>
                            </div>
                            {/* Applicant Form */}
                            <div className="flex mt-2">
                                <div className="basis-[60%] print:basis-1/2 pr-10">
                                    <label className="inline-block font-semibold mb-3">BILL 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 className="basis-[40%] print:basis-1/2 pl-5">
                                    <div className="mb-2">
                                        <span>
                                            <label className="inline-block font-semibold !w-[150px]">DATE</label>:
                                        </span>
                                        <span className="ml-3 data">{dateTransformer(data.createdAt)}</span>
                                    </div>
                                    <div className="mb-2">
                                        <span>
                                            <label className="inline-block font-semibold !w-[150px]">REF. NUMBER</label>:
                                        </span>
                                        <span className="ml-3 data">{'INV-' + data.displayId}</span>
                                    </div>
                                </div>
                            </div>
                            <Divider className="bg-black" />
                            {/* Payment Method in English and Simplified Chinese */}
                            <div className="flex flex-row w-full">
                                <div className="mt-2 basis-1/2">
                                    <div className="mb-2">
                                        <span>
                                            <label className="inline-block font-semibold !w-[150px]">PAYMENT METHOD</label>:
                                        </span>
                                        <span className="ml-3 data">{'Online Banking'}</span>
                                    </div>
                                    <div className="mb-2">
                                        <span>
                                            <label className="inline-block font-semibold !w-[150px]">BANK</label>:
                                        </span>
                                        <span className="ml-3 data">{bankDetails?.bankName}</span>
                                    </div>
                                    <div className="mb-2">
                                        <span>
                                            <label className="inline-block font-semibold !w-[150px]">ACCOUNT NO.</label>:
                                        </span>
                                        <span className="ml-3 data">{bankDetails?.accountNumber}</span>
                                    </div>
                                </div>
                            </div>
                            {/* Product Info Form */}
                            <table className="mt-6 w-full">
                                <thead className="text-gray-700 bg-gray-200">
                                    <tr>
                                        <th style={{ width: '5%' }}>No.</th>
                                        <th style={{ width: '25%' }}>PRODUCT</th>
                                        <th style={{ width: '45%' }}>DESCRIPTION</th>
                                        <th style={{ width: '5%' }}>QTY</th>
                                        <th style={{ width: '10%' }}>UNIT PRICE (MYR)</th>
                                        <th style={{ width: '10%' }}>AMOUNT (MYR)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td className="text-center">{1}</td>
                                        <td className="text-center">{data.package.name}</td>
                                        <td className="text-center">
                                            <HtmlParser html={data.package?.description ?? '-'} />
                                        </td>
                                        <td className="!px-3 text-center data">{data.quantity}</td>
                                        <td className="text-center data">{data.package.price}</td>
                                        <td className="text-center data">{currencyFormatter(data.price)}</td>
                                    </tr>
                                </tbody>
                                <tfoot>
                                    <tr className="leading-loose">
                                        <td colSpan={5} 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.price)}</span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colSpan={5} 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.price)}</span>
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>
                            <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.current}
                />
            </div>
        </div>
    );
};

export default InvoicePage;

export const getServerSideProps: GetServerSideProps = async ({ req, locale, resolvedUrl }) => {
    return {
        props: {
            ...(await serverSideTranslations(locale as string, ['bill', 'layout', 'common', 'messages', 'api-messages'])),
        },
    };
};