import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { ActionScreen } from "@/components/bkash/ActionScreen";
import { Html5Qrcode } from "html5-qrcode";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/scan")({
  component: ScanPage,
});

function ScanPage() {
  const navigate = useNavigate();
  const [status, setStatus] = useState("ক্যামেরা চালু হচ্ছে...");
  const elId = "qr-reader";
  const scannerRef = useRef<Html5Qrcode | null>(null);

  useEffect(() => {
    const scanner = new Html5Qrcode(elId, { verbose: false });
    scannerRef.current = scanner;
    let stopped = false;

    scanner
      .start(
        { facingMode: "environment" },
        { fps: 10, qrbox: { width: 240, height: 240 } },
        (text) => {
          if (stopped) return;
          stopped = true;
          handleResult(text);
        },
        () => {}
      )
      .then(() => setStatus("কোড স্ক্যান করুন"))
      .catch(() => setStatus("ক্যামেরা অনুমতি প্রয়োজন"));

    function handleResult(text: string) {
      let phone: string | null = null;
      try {
        const obj = JSON.parse(text);
        if (obj?.t === "bkash" && /^01\d{9}$/.test(obj.phone)) phone = obj.phone;
      } catch {
        if (/^01\d{9}$/.test(text.trim())) phone = text.trim();
      }
      scanner.stop().catch(() => {});
      if (phone) {
        toast.success("নম্বর পাওয়া গেছে");
        navigate({ to: "/send", search: { to: phone } as any });
      } else {
        toast.error("অবৈধ QR কোড");
        navigate({ to: "/" });
      }
    }

    return () => {
      try {
        scanner.stop().catch(() => {});
      } catch {}
    };
  }, [navigate]);

  return (
    <ActionScreen title="QR স্ক্যান" subtitle={status}>
      <div className="bg-black rounded-2xl overflow-hidden">
        <div id={elId} className="w-full aspect-square" />
      </div>
      <p className="text-center text-xs text-muted-foreground mt-4">
        শুধু বিকাশ QR বা ১১ ডিজিটের ফোন নম্বর কাজ করবে
      </p>
    </ActionScreen>
  );
}
