import { GetServerSideProps, NextPage } from 'next';
import { useRef } from 'react';
import { Button, Empty, Spin } from 'antd';
import { PrinterOutlined } from '@ant-design/icons';
import ReactToPrint from 'react-to-print';
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import dayjs from 'dayjs';
import { useQuery } from '@tanstack/react-query';
import Logo from '../../../../public/logo-text.png';
import Image from 'next/image';
import { currencyFormatter } from '@/utils/currencyFormatter';
import { getBookQuotation } from '@/services/bill';
import { getSupport } from '@/services/company-info';

const QuotationPage: NextPage = () => {
    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: ['quotation'],
        queryFn: async () => {
            const response = await getBookQuotation();

            return response.data;
        },
    });

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

    const totalPrice = data?.reduce((acc, curr) => acc + curr.price, 0);

    const quantity = 1;

    return isFetching || isCompanyInformationFetching ? (
        <Spin spinning />
    ) : !data ? (
        <Empty />
    ) : (
        <div>
            <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">QUOTATION</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">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-[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">{dayjs.tz().format('DD/MM/YYYY')}</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>
                                    {data.map((product, index) => (
                                        <tr key={product.id}>
                                            <td className="text-center">{index + 1}</td>
                                            <td className="text-center">{product.name}</td>
                                            <td className="!px-3 text-center data">{quantity}</td>
                                            <td className="text-center data">{product.price}</td>
                                            <td className="text-center data">{currencyFormatter(product.price * 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">{totalPrice ? currencyFormatter(totalPrice * quantity) : '0'}</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">{totalPrice ? currencyFormatter(totalPrice * quantity) : '0'}</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 QuotationPage;

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