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 { getInvoiceByBookTokenSubscriptionId } 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 { BookTokenSubscriptionStatus } from '@/types';
import HtmlParser from '@/components/HtmlParser';
import { dateTransformer } from '@/utils/timeTransformer';
import { getSupport } from '@/services/company-info';

const ReceiptPage: NextPage = () => {
    const router = useRouter();
    const { bookTokenSubscriptionId } = 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', bookTokenSubscriptionId as string],
        queryFn: async () => {
            const response = await getInvoiceByBookTokenSubscriptionId(bookTokenSubscriptionId 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?.paymentStatus !== BookTokenSubscriptionStatus.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>
                            </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 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'])),
        },
    };
};
