/* eslint-disable @typescript-eslint/no-explicit-any */
import { Setting } from '@/types/setting';
import { usePage } from '@inertiajs/react';
import React, { createContext, useContext, useState } from 'react';
import { toast } from 'sonner';

type BluetoothContextType = {
    bluetoothDevice: BluetoothDevice | null;
    printerServer: BluetoothRemoteGATTServer | null;
    isBluetoothConnected: boolean;
    connectBluetoothPrinter: () => Promise<void>;
    handleTestPrint: () => Promise<void>;
};

type SettingProps = {
    settings : Setting[]
}


const BluetoothContext = createContext<BluetoothContextType | undefined>(undefined);

export function BluetoothProvider({ children }: { children: React.ReactNode }) {
    const { settings } = usePage<SettingProps>().props;
    const [bluetoothDevice, setBluetoothDevice] = useState<BluetoothDevice | null>(null);
    const [printerServer, setPrinterServer] = useState<BluetoothRemoteGATTServer | null>(null);
    const [isBluetoothConnected, setIsBluetoothConnected] = useState(false);
    const prntSetting = settings.find(setting => setting.code === 'PRNT');

    const defaultServices = [
        '00001800-0000-1000-8000-00805f9b34fb',
        '000018f0-0000-1000-8000-00805f9b34fb',
        '0000fee7-0000-1000-8000-00805f9b34fb',
        '0000ff00-0000-1000-8000-00805f9b34fb',
        '49535343-fe7d-4ae5-8fa9-9fafd205e455',
        'e7810a71-73ae-499d-8c15-faa9aef0c3f2',
        'battery_service',
    ];

    let extraServices: string[] = [];
    if (prntSetting?.value) {
        if (Array.isArray(prntSetting.value)) {
            extraServices = prntSetting.value as string[];
        } else if (typeof prntSetting.value === 'string') {
            extraServices = [prntSetting.value];
        }
    }

    const optionalServices = [...new Set([...defaultServices, ...extraServices])];

   const connectBluetoothPrinter = async () => {
    try {
        // ✅ Cek protokol (Web Bluetooth hanya jalan di HTTPS / localhost)
        if (window.location.protocol !== "https:" && window.location.hostname !== "localhost") {
            toast.error("Bluetooth hanya berfungsi di HTTPS atau localhost.");
            return;
        }

        // ✅ Pastikan browser mendukung Web Bluetooth API
        if (!navigator.bluetooth) {
            toast.error("Browser tidak mendukung Web Bluetooth API. Gunakan Chrome, Edge, atau Android.");
            return;
        }

        toast.message("🔍 Memindai perangkat Bluetooth...");

        const device = await navigator.bluetooth.requestDevice({
            acceptAllDevices: true,
            optionalServices,
        });

        if (!device) {
            toast.error("Tidak ada perangkat Bluetooth yang dipilih.");
            return;
        }

        toast.message(`🔗 Menghubungkan ke ${device.name || "printer"}...`);

        const server = await device.gatt?.connect();
        if (!server) throw new Error("Gagal menyambung ke printer");

        setBluetoothDevice(device);
        setPrinterServer(server);
        setIsBluetoothConnected(true);

        toast.success(`Terhubung ke printer: ${device.name || "Unknown"}`);

        // ✅ Monitor jika koneksi terputus
        device.ongattserverdisconnected = () => {
            setIsBluetoothConnected(false);
            setPrinterServer(null);
            toast.warning("Koneksi printer terputus. Silakan hubungkan ulang.");
        };
    } catch (error: any) {
        console.error(error);

        // ✅ Tangani error lebih spesifik dan jelas
        if (error.name === "NotFoundError") {
            toast.error("Tidak ada perangkat yang cocok ditemukan atau pemindaian dibatalkan.");
        } else if (error.name === "InvalidStateError") {
            toast.error("Perangkat sedang tidak dalam kondisi siap digunakan. Coba hidupkan ulang printer.");
        } else if (error.name === "SecurityError") {
            toast.error("Akses Bluetooth ditolak. Izinkan akses dari browser.");
        } else if (error.message?.includes("Invalid Service name")) {
            toast.error("UUID Service printer tidak valid. Periksa kembali pengaturan PRNT di sistem.");
        } else if (error.message?.includes("Origin is not allowed")) {
            toast.error("Bluetooth tidak dapat digunakan di halaman ini. Gunakan HTTPS atau localhost.");
        } else if (error.message?.includes("connect") || error.message?.includes("Gagal konek")) {
            toast.error("Gagal menghubungkan ke printer. Pastikan printer aktif dan dalam jangkauan.");
        } else {
            toast.error(`Gagal menghubungkan printer: ${error.message || "Kesalahan tidak diketahui."}`);
        }
    }
};


    const handleTestPrint = async () => {
        if (!printerServer) {
            toast.error('Printer belum terhubung');
            return;
        }

        try {
            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) {
                        const encoder = new TextEncoder();
                        const data = encoder.encode('Hello dari KasirPro POS!\n\n');
                        await c.writeValue(data);
                        toast.success('✅ Test print terkirim!');
                        return;
                    }
                }
            }

            toast.error('Tidak menemukan karakteristik write');
        } catch (err: any) {
            console.error(err);
            toast.error('Gagal print: ' + err.message);
        }
    };

    return (
        <BluetoothContext.Provider
            value={{
                bluetoothDevice,
                printerServer,
                isBluetoothConnected,
                connectBluetoothPrinter,
                handleTestPrint,
            }}
        >
            {children}
        </BluetoothContext.Provider>
    );
}

export function useBluetooth() {
    const ctx = useContext(BluetoothContext);
    if (!ctx) throw new Error('useBluetooth harus digunakan di dalam <BluetoothProvider>');
    return ctx;
}
