import { useEffect, useState } from "react";

import PageHeader from "@/components/PageHeader";
import { useInvoicesActions } from "@/hooks/useInvoicesActions";
import { useInvoicesStore } from "@/stores/useInvoicesStore";
import type { ApiInvoice } from "@/types";
import documentIcon from "../../images/icons/guid-icon.svg";
import downloadIcon from "../../images/icons/download-ico.svg";

const invoiceDateFormatter = new Intl.DateTimeFormat("en-US", {
    day: "numeric",
    month: "long",
    year: "numeric",
});

// created_at arrives as an ISO 8601 timestamp; show just the date.
const formatInvoiceDate = (value: string) => {
    const date = new Date(value);

    return Number.isNaN(date.getTime()) ? "" : invoiceDateFormatter.format(date);
};

const invoiceAmountFormatter = new Intl.NumberFormat("en-US", {
    currency: "USD",
    style: "currency",
});

// amount arrives as a decimal string (e.g. "4850.00").
const formatInvoiceAmount = (value: string) => {
    const amount = Number(value);

    return Number.isNaN(amount) ? "" : invoiceAmountFormatter.format(amount);
};

const ReceiptsInvoicesPage = () => {
    const { error, invoices, isLoading } = useInvoicesStore();
    const { downloadAllInvoices, fetchInvoice, fetchInvoices } =
        useInvoicesActions();
    const [lastDownload, setLastDownload] = useState<string>("");

    useEffect(() => {
        void fetchInvoices();
    }, []);

    // The file is private: this hits the authenticated download endpoint, which
    // streams it back with a Content-Disposition attachment header. Same-origin,
    // so the session cookie goes with it.
    const download = (invoice: ApiInvoice) => {
        if (!invoice.download_url) {
            return;
        }

        const link = document.createElement("a");

        link.href = invoice.download_url;
        link.download = invoice.file_name ?? "";
        document.body.appendChild(link);
        link.click();
        link.remove();
    };

    const downloadReceipt = async (invoiceId: number) => {
        const invoice = await fetchInvoice(invoiceId);

        if (invoice) {
            download(invoice);
            setLastDownload(invoice.name);
        }
    };

    // The per-invoice endpoint only streams one file; browsers block firing
    // many downloads at once, so grab a single server-built zip instead.
    const downloadAll = async () => {
        const archive = await downloadAllInvoices();

        if (!archive) {
            return;
        }

        const url = URL.createObjectURL(archive);
        const link = document.createElement("a");

        link.href = url;
        link.download = "invoices.zip";
        document.body.appendChild(link);
        link.click();
        link.remove();
        URL.revokeObjectURL(url);

        setLastDownload("All receipts");
    };

    return (
        <article className="portal-card account-page receipts-invoices-page">
            <PageHeader
                eyebrowParent="Account"
                eyebrowCurrent="Receipts & Invoices"
                title="Receipts & invoices"
                description="Your registration invoices, receipts, and subscription records - all in one place."
            />

            <section className="account-panel">
                <div className="account-panel__head d-flex flex-column flex-md-row align-items-md-center justify-content-md-between gap-4">
                    <h2 className="account-section-title mb-0">
                        Invoices, receipts, and registration records
                    </h2>

                    <button
                        className="btn btn-outline-dark d-inline-flex align-items-center justify-content-center gap-2 account-download-all"
                        disabled={invoices.length === 0}
                        type="button"
                        onClick={() => void downloadAll()}
                    >
                        <img src={downloadIcon} alt="" aria-hidden="true" />
                        <span>Download All</span>
                    </button>
                </div>

                <div className="account-divider" />

                {error ? (
                    <p className="alert alert-danger mb-4" role="alert">
                        {error}
                    </p>
                ) : null}

                {isLoading ? (
                    <p className="text-muted">Loading invoices…</p>
                ) : invoices.length === 0 ? (
                    <p className="text-muted mb-0">No invoices available.</p>
                ) : (
                    <div className="d-flex flex-column gap-4">
                        {invoices.map((invoice) => (
                            <article
                                className="receipt-row d-flex align-items-center gap-3 gap-md-4"
                                key={invoice.id}
                            >
                                <span
                                    className="account-file-icon d-inline-flex align-items-center justify-content-center flex-shrink-0"
                                    aria-hidden="true"
                                >
                                    <img src={documentIcon} alt="" />
                                </span>

                                <div className="min-w-0 flex-grow-1">
                                    <h3 className="receipt-row__title">
                                        {invoice.name}
                                    </h3>
                                    <p className="mb-0">
                                        <span>Paid</span>
                                        <small>
                                            {formatInvoiceDate(
                                                invoice.created_at,
                                            )}{" "}
                                            &middot;{" "}
                                            {formatInvoiceAmount(
                                                invoice.amount,
                                            )}
                                        </small>
                                    </p>
                                </div>

                                <button
                                    className="receipt-row__download d-inline-flex align-items-center justify-content-center flex-shrink-0"
                                    disabled={!invoice.download_url}
                                    type="button"
                                    onClick={() =>
                                        void downloadReceipt(invoice.id)
                                    }
                                    aria-label={`Download ${invoice.name}`}
                                >
                                    <img
                                        src={downloadIcon}
                                        alt=""
                                        aria-hidden="true"
                                    />
                                </button>
                            </article>
                        ))}
                    </div>
                )}

                <p className="visually-hidden" aria-live="polite">
                    {lastDownload
                        ? `${lastDownload} selected for download.`
                        : ""}
                </p>
            </section>
        </article>
    );
};

export default ReceiptsInvoicesPage;
