import { useState } from 'react';
import CustomTableHead from '@/Component/Common/Tables/CustomTableHead';
import { formatNumberWithCommas } from '@/Utils/Other/FormatNumberWithCommas';
import moment from 'moment';
import NoDataTable from '@/Component/Common/Tables/NoData/NoDataTable';
import TableHoc from '@/Utils/HOC/TableHoc';
import { TableEyeSVG } from '@/Component/Common/SVGs/CommonSVG';
import CustomFetch from '@/Utils/APIRequest/AxiosInstance';
import { AdminSubscriptionHistoryAPI } from '@/Utils/APIRequest/Endpoints';
import { CustomToast } from '@/Utils/CustomToast';
import Loader from '@/Layout/Loader';

const SubscriptionHistoryTable = (props) => {
    const { apiData, translations } = props;
    const SubHistoryData = apiData?.data?.data;
    const [openingInvoiceId, setOpeningInvoiceId] = useState<any>(null);
    const [urlLoader, setUrlLoader] = useState<any>(false);

    const handleOpenInvoice = async (history: any) => {

        try {
            setUrlLoader(true);
            setOpeningInvoiceId(history?.id);
            const response: any = await CustomFetch({ url: `${AdminSubscriptionHistoryAPI}/${history?.id}/invoice` }, null, false);
            const invoiceUrl = response?.data?.url;
            if (!invoiceUrl) return;
            window.open(invoiceUrl, '_blank', 'noopener,noreferrer');
        } finally {
            setOpeningInvoiceId(null);
            setUrlLoader(false);
        }
    };

    const tableHeadData = {
        head: [
            { title: translations?.srNo, sorting: false },
            { title: translations?.planName, sorting: false },
            { title: translations?.amount, sorting: false },
            { title: translations?.interval, sorting: false },
            { title: translations?.startDate, apiKey: "start_date", sorting: true },
            { title: translations?.endDate, apiKey: "end_date", sorting: true },
            { title: translations?.status, apiKey: "status", sorting: true },
            { title: translations?.invoice, sorting: false },
        ]
    }

    if (urlLoader) return <Loader />;

    return (
        <>
            <table className="w-full text-sm text-left rtl:text-right">
                <CustomTableHead tableHeadData={tableHeadData} params={apiData?.params} setParams={apiData?.setParams} />
                <tbody>
                    {
                        SubHistoryData?.length > 0
                            ?
                            SubHistoryData?.map((history, index) => (
                                <tr className="border-b border-lightGray last:border-none font-normal hover:bg-lightGray/20 align-middle text-xs" key={index}>
                                    <td className="px-5 py-4">
                                        {((apiData?.params.page - 1) * apiData?.params.per_page) + 1 + index}
                                    </td>
                                    <td className="px-5 py-4">
                                        {history?.plan?.name}
                                    </td>
                                    <td className="px-5 py-4">
                                        ${formatNumberWithCommas(history?.amount_usd)} USD
                                    </td>
                                    <td className="px-5 py-4 capitalize">
                                        {history?.interval === 'month' ? translations.monthly : translations.yearly}
                                    </td>
                                    <td className="px-5 py-4">
                                        {moment.utc(history?.start_date).local().format('DD MMM YYYY')}
                                    </td>
                                    <td className="px-5 py-4">
                                        {moment.utc(history?.end_date).local().format('DD MMM YYYY')}
                                    </td>
                                    <td className="px-5 py-4 capitalize">
                                        <span className={`${history?.status === 'active' ? 'bg-green-500' : history?.status === 'canceled' ? 'bg-red-500' : history?.status === 'pending' ? 'bg-darkGray' : 'bg-yellow-500'} inline-block px-2 py-1 rounded-md text-white text-xs`}>{translations[history?.status]}</span>
                                    </td>
                                    <td className="px-5 py-4">
                                        <button
                                            onClick={() => handleOpenInvoice(history)}
                                            disabled={openingInvoiceId === history?.id}
                                        >
                                            <TableEyeSVG />
                                        </button>
                                    </td>
                                </tr>
                            ))
                            : <NoDataTable colSpan={8} />
                    }
                </tbody>
            </table>
        </>
    )
}

export default TableHoc(SubscriptionHistoryTable)
