/* eslint-disable @typescript-eslint/no-explicit-any */
/// <reference lib="dom" />
import { useBluetooth } from "@/contexts/bluetooth-context";
import { Button } from "@/components/ui/button";
import { Bluetooth } from "lucide-react";
import { toast } from "sonner";

interface BluetoothPrintButtonProps {
    tx: any;
    paperWidth?: number; // Tambahkan prop untuk lebar kertas
}

export default function BluetoothPrintButton({ tx, paperWidth = 32 }: BluetoothPrintButtonProps) {
    const { printerServer, isBluetoothConnected } = useBluetooth();

    const centerText = (text: string, width = paperWidth) => {
        if (text.length >= width) return text;
        const leftPadding = Math.floor((width - text.length) / 2);
        return " ".repeat(leftPadding) + text;
    };

    // formatLine menyesuaikan lebar kertas
    const formatLine = (left: string, right: string, width = paperWidth) => {
        const totalLength = left.length + right.length;
        if (totalLength >= width) return `${left}\n${right}`;
        const spaces = " ".repeat(width - totalLength);
        return `${left}${spaces}${right}`;
    };

    const writeInChunks = async (characteristic: BluetoothRemoteGATTCharacteristic, data: Uint8Array, chunkSize = 200) => {
        for (let i = 0; i < data.length; i += chunkSize) {

            const chunk = data.slice(i, i + chunkSize);
            await characteristic.writeValue(chunk);
            await new Promise((resolve) => setTimeout(resolve, 50));
        }
    };

    const handleBluetoothPrintReceipt = async () => {
        if (!printerServer || !isBluetoothConnected) {
            toast.error("Printer Bluetooth belum terhubung");
            return;
        }

        try {
            const encoder = new TextEncoder();
            const dateNow = new Date().toLocaleString("id-ID", {
                day: "2-digit",
                month: "2-digit",
                year: "numeric",
                hour: "2-digit",
                minute: "2-digit",
            });

            // HEADER
            const headerInfo = [
                formatLine("Invoice", tx.invoice ?? "-"),
                formatLine("Tanggal", dateNow),
                formatLine("Jenis", tx.order_type_label ?? "-"),
                tx.table_number ? formatLine("Meja", String(tx.table_number)) : null,
                tx.customer_name ? formatLine("Pelanggan", tx.customer_name) : null,
                formatLine("Kasir", tx.cashier_name ?? "-"),
            ].filter(Boolean).join("\n");

            // ITEM LIST
            const itemsText = tx.items?.map((it: any) => {
                // Jika nama produk terlalu panjang, bisa di-wrap jadi beberapa baris
                const nameLines = it.name.match(new RegExp(`.{1,${paperWidth}}`, "g")) || [""];

                const qtyPriceLine = formatLine(
                    `${it.qty} x ${it.price.toLocaleString("id-ID")}`,
                    it.total.toLocaleString("id-ID"),
                    paperWidth
                );

                return [...nameLines, qtyPriceLine].join("\n"); // gabungkan tanpa baris kosong
            }).join("\n") ?? "";

            // SUMMARY
            const summaryLines = [
                formatLine("Subtotal", tx.subtotal.toLocaleString("id-ID"), paperWidth),
                tx.discount ? formatLine("Diskon", `-${tx.discount.toLocaleString("id-ID")}`, paperWidth) : null,
                ...(tx.taxes?.filter((t: any) => t.value && t.value !== 0)
                    .map((t: any) => formatLine(t.label, t.value.toLocaleString("id-ID"), paperWidth)) || []),
                formatLine("Total", tx.grand_total.toLocaleString("id-ID"), paperWidth),
            ].filter(Boolean).join("\n");

            // PAYMENT
            const paymentLines = [
                formatLine(`Bayar (${tx.pay_label ?? "-"})`, tx.pay.toLocaleString("id-ID"), paperWidth),
                formatLine("Kembali", tx.change.toLocaleString("id-ID"), paperWidth),
            ].join("\n");

            // SUSUN STRUK
            const struk = `
${centerText(tx.company_name?.toUpperCase() || "")}
${centerText(tx.company_address || "")}
${centerText("Telp: " + (tx.company_phone || ""))}
${"-".repeat(paperWidth)}
${headerInfo}
${"-".repeat(paperWidth)}
${itemsText}
${"-".repeat(paperWidth)}
${summaryLines}
${"-".repeat(paperWidth)}
${paymentLines}
${"-".repeat(paperWidth)}
${centerText("Terima kasih - Simpan struk ini")}
${centerText("sebagai bukti transaksi.")}
\r\n\r\n
`;

            const data = encoder.encode(struk);

            const services = await printerServer.getPrimaryServices();
            for (const service of services) {
                const characteristics = await service.getCharacteristics();
                for (const c of characteristics) {
                    if (c.properties.write || c.properties.writeWithoutResponse) {
                        await writeInChunks(c, data);
                        toast.success("Struk berhasil dikirim ke printer!");
                        return;
                    }
                }
            }

            toast.error("Tidak menemukan karakteristik write di printer");
        } catch (err: any) {
            console.error(err);
            toast.error("Gagal mencetak: " + err.message);
        }
    };

    if (!isBluetoothConnected) return null;

    return (
        <Button
            type="button"
            className="w-full bg-blue-600 hover:bg-blue-700 text-white"
            onClick={handleBluetoothPrintReceipt}
        >
            <Bluetooth className="w-5 h-5 mr-2 text-white" /> Cetak Bluetooth
        </Button>
    );
}
