import { CapacitorBarcodeScanner } from "@capacitor/barcode-scanner";
import { Capacitor } from "@capacitor/core";
import { toastController } from "@ionic/vue";

export interface QRScanResult {
  text: string;
  format: string;
  rawValue: string;
  displayValue: string;
}

export interface ScannerOptions {
  title?: string;
}

export function useQRScanner() {
  const { t } = useI18n();
  const { vibrate } = useHaptics();
  const isSupported = Capacitor.isNativePlatform();

  async function showError(message: string) {
    const toast = await toastController.create({
      message,
      duration: 2000,
      position: "bottom",
      color: "danger",
    });
    await toast.present();
  };

  async function open(options?: ScannerOptions): Promise<QRScanResult | null> {
    try {
      if (!isSupported) {
        await showError(t("scanner.notSupported"));
        return null;
      }

      vibrate();

      const result = await CapacitorBarcodeScanner.scanBarcode({
        hint: 0,
        scanInstructions: options?.title || t("scanner.hint"),
        cameraDirection: 1,
      });

      if (result.ScanResult) {
        vibrate();
        return {
          text: result.ScanResult,
          format: result.format?.toString() || "UNKNOWN",
          rawValue: result.ScanResult,
          displayValue: result.ScanResult,
        };
      }

      return null;
    }
    catch (error: any) {
      console.log("error.message", error.message);
      if (error.code !== "OS-PLUG-BARC-0006") {
        await showError(t("scanner.openError"));
      }
      return null;
    }
  }

  return {
    isSupported,
    open,
  };
}
