import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import RNBluetoothClassic from "react-native-bluetooth-classic";
import { usePrinter } from "../hooks/usePrinter";
import { BluetoothDeviceSelectModal } from "./BluetoothDeviceSelectModal";

export interface PrinterHandler {
  printDocument: (dataToBePrinted: string) => Promise<void>;
}

interface PrinterProps {
  onComplete?: (isPrinted: boolean) => void;
}

export const Printer = forwardRef<PrinterHandler, PrinterProps>(
  ({ onComplete }, ref) => {
    const {
      isPaxDevice,
      isNexGoDevice,
      printWithPax,
      printWithNexGo,
      printWithBluetooth,
    } = usePrinter();
    const [isBlueetoothModalVisible, setShowBluetoothModal] =
      useState(false);
    const dataToBePrintedRef = useRef<string | null>(null);

    useImperativeHandle(ref, () => ({
      async printDocument(dataToBePrinted: string) {
        try {
          if (isPaxDevice) {
            await printWithPax(dataToBePrinted);
            onComplete?.(true);
            return;
          }
          if (isNexGoDevice) {
            await printWithNexGo(dataToBePrinted);
            onComplete?.(true);
            return;
          }

          dataToBePrintedRef.current = dataToBePrinted;
          setShowBluetoothModal(true);
        } catch (error) {
          onComplete?.(false);
          console.log(error);
        }
      },
    }));

    const handlePrint = async (deviceId: string) => {
      if (!dataToBePrintedRef.current) return;

      const devices = await RNBluetoothClassic.getBondedDevices();
      const device = devices.find((d) => d.id === deviceId);

      if (device) {
        await printWithBluetooth(device, dataToBePrintedRef.current);
        onComplete?.(true);
        setShowBluetoothModal(false);
        return;
      }

      console.error("Bluetooth device not found");
    };

    if (isPaxDevice) {
      return null;
    }

    return (
      isBlueetoothModalVisible && (
        <BluetoothDeviceSelectModal
          onDeviceSelected={handlePrint}
          handleSheetClose={() => {
            setShowBluetoothModal(false);
          }}
        />
      )
    );
  }
);
