import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useRef } from "react";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { getMyProfile } from "@/lib/bkash.functions";
import { ActionScreen } from "@/components/bkash/ActionScreen";
import QRCode from "qrcode";
import { toast } from "sonner";
import { Copy, Share2 } from "lucide-react";

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

function MyQR() {
  const getProfile = useServerFn(getMyProfile);
  const q = useQuery({ queryKey: ["profile"], queryFn: () => getProfile() });
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const payload = q.data ? JSON.stringify({ t: "bkash", phone: q.data.phone, name: q.data.full_name }) : "";

  useEffect(() => {
    if (!payload || !canvasRef.current) return;
    QRCode.toCanvas(canvasRef.current, payload, { width: 260, margin: 1, color: { dark: "#000000", light: "#ffffff" } });
  }, [payload]);

  async function copy() {
    if (!q.data) return;
    await navigator.clipboard.writeText(q.data.phone);
    toast.success("নম্বর কপি হয়েছে");
  }
  async function share() {
    if (!q.data) return;
    try {
      await navigator.share?.({ title: "আমার বিকাশ", text: `${q.data.full_name} — ${q.data.phone}` });
    } catch {}
  }

  return (
    <ActionScreen title="আমার QR" subtitle="স্ক্যান করে দ্রুত টাকা পাঠান">
      <div className="bg-card rounded-2xl shadow-[var(--shadow-elevated)] p-6 flex flex-col items-center">
        <div className="p-4 bg-white rounded-2xl">
          <canvas ref={canvasRef} />
        </div>
        <p className="mt-4 font-bold text-lg">{q.data?.full_name ?? "..."}</p>
        <p className="text-sm text-muted-foreground tabular-nums">{q.data?.phone}</p>
        <div className="mt-4 grid grid-cols-2 gap-3 w-full">
          <button onClick={copy} className="h-11 rounded-xl bg-accent text-sm font-semibold flex items-center justify-center gap-2">
            <Copy className="h-4 w-4" /> কপি
          </button>
          <button onClick={share} className="h-11 rounded-xl bg-accent text-sm font-semibold flex items-center justify-center gap-2">
            <Share2 className="h-4 w-4" /> শেয়ার
          </button>
        </div>
      </div>
    </ActionScreen>
  );
}
