import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef } from "react";
import { useServerFn } from "@tanstack/react-start";
import { useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { getMyProfile, listMyTransactions } from "@/lib/bkash.functions";
import { amIAdmin } from "@/lib/admin.functions";
import {
  Send, ArrowDownToLine, Smartphone, Zap, Receipt, CreditCard,
  GraduationCap, ShoppingBag, Heart, MoreHorizontal, Bell, Search,
  Eye, EyeOff, QrCode, Home, Wallet, Inbox, User, Plus, ArrowUpRight,
  ArrowDownLeft, LogOut, Shield, IdCard, AlertTriangle, CheckCircle2, Clock
} from "lucide-react";
import { NotificationBadge } from "@/components/bkash/NotificationBadge";
import { GlobalSearch } from "@/components/bkash/GlobalSearch";

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

const TYPE_META: Record<string, { label: string; icon: any; sign: 1 | -1 }> = {
  send_money: { label: "Send Money", icon: Send, sign: -1 },
  received: { label: "Received", icon: ArrowDownLeft, sign: 1 },
  cash_out: { label: "Cash Out", icon: ArrowDownToLine, sign: -1 },
  mobile_recharge: { label: "Mobile Recharge", icon: Smartphone, sign: -1 },
  pay_bill: { label: "Pay Bill", icon: Zap, sign: -1 },
  payment: { label: "Payment", icon: CreditCard, sign: -1 },
  add_money: { label: "Add Money", icon: Plus, sign: 1 },
};

function Dashboard() {
  const [shown, setShown] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const hideTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const getProfile = useServerFn(getMyProfile);
  const listTx = useServerFn(listMyTransactions);
  const checkAdmin = useServerFn(amIAdmin);
  const navigate = useNavigate();
  const qc = useQueryClient();

  useEffect(() => () => { if (hideTimer.current) clearTimeout(hideTimer.current); }, []);

  function revealBalance() {
    setShown(true);
    if (hideTimer.current) clearTimeout(hideTimer.current);
    hideTimer.current = setTimeout(() => setShown(false), 5000);
  }

  const profileQ = useQuery({ queryKey: ["profile"], queryFn: () => getProfile() });
  const txQ = useQuery({ queryKey: ["transactions"], queryFn: () => listTx() });
  const adminQ = useQuery({ queryKey: ["am-i-admin"], queryFn: () => checkAdmin(), staleTime: 60_000 });

  async function signOut() {
    await qc.cancelQueries();
    qc.clear();
    await supabase.auth.signOut();
    navigate({ to: "/auth", replace: true });
  }

  const balanceStr = profileQ.data
    ? `৳ ${Number(profileQ.data.balance).toLocaleString("en-BD", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
    : "৳ ...";
  const initial = (profileQ.data?.full_name ?? "U").charAt(0).toUpperCase();
  const recentTx = (txQ.data ?? []).slice(0, 5);
  const kycStatus = (profileQ.data as any)?.kyc_status ?? "unverified";
  const verified = kycStatus === "verified";


  return (
    <div className="min-h-screen bg-background pb-24 max-w-[480px] mx-auto">
      <header
        className="relative px-4 pb-20 text-primary-foreground rounded-b-[2rem] shadow-[var(--shadow-elevated)] overflow-hidden"
        style={{
          background: "var(--gradient-balance)",
          paddingTop: "calc(env(safe-area-inset-top, 0px) + 1rem)",
        }}
      >
        {/* decorative blobs */}
        <div className="absolute -top-10 -right-10 h-44 w-44 rounded-full bg-white/10 blur-2xl pointer-events-none" />
        <div className="absolute -bottom-16 -left-10 h-40 w-40 rounded-full bg-white/5 blur-2xl pointer-events-none" />

        <div className="relative grid grid-cols-[minmax(0,1fr)_auto] items-center gap-2">
          <div className="flex min-w-0 items-center gap-3">
            <div className="h-11 w-11 shrink-0 rounded-full bg-white/15 backdrop-blur flex items-center justify-center text-lg font-bold ring-2 ring-white/25 overflow-hidden">
              {(profileQ.data as any)?.avatar_url ? (
                <img src={(profileQ.data as any).avatar_url} alt={profileQ.data?.full_name ?? ""} className="h-full w-full object-cover" />
              ) : (
                initial
              )}
            </div>
            <div className="min-w-0">
              <p className="text-[10px] leading-tight opacity-80">স্বাগতম</p>
              <p className="font-semibold tracking-tight text-sm truncate">{profileQ.data?.full_name ?? "..."}</p>
              <p className="text-[10px] opacity-70 tabular-nums truncate">{profileQ.data?.phone}</p>
            </div>
          </div>
          <div className="flex items-center gap-1.5 shrink-0">
            <button onClick={() => setSearchOpen(true)} className="h-9 w-9 rounded-full bg-white/15 flex items-center justify-center backdrop-blur" aria-label="Search">
              <Search className="h-4 w-4" />
            </button>
            <Link to="/notifications" className="h-9 w-9 rounded-full bg-white/15 flex items-center justify-center backdrop-blur relative" aria-label="Notifications">
              <Bell className="h-4 w-4" />
              <NotificationBadge />
            </Link>
            {adminQ.data?.isAdmin && (
              <Link to="/admin" className="h-9 w-9 rounded-full bg-white/15 flex items-center justify-center backdrop-blur" aria-label="Admin">
                <Shield className="h-4 w-4" />
              </Link>
            )}
            <button onClick={signOut} className="h-9 w-9 rounded-full bg-white/15 flex items-center justify-center backdrop-blur" aria-label="Sign out">
              <LogOut className="h-4 w-4" />
            </button>
          </div>
        </div>

        <div className="relative mt-8 flex justify-center">
          <button
            onClick={revealBalance}
            className="relative bg-white text-foreground rounded-full py-2 flex items-center shadow-[var(--shadow-elevated)] active:scale-95 transition-all duration-300 min-w-[220px] h-12 px-2 overflow-hidden"
            aria-label="ব্যালেন্স দেখতে ক্লিক করুন"
          >
            <span
              className={`h-8 w-8 rounded-full flex items-center justify-center text-white text-sm font-bold shrink-0 absolute top-1/2 -translate-y-1/2 transition-all duration-500 ease-in-out ${
                shown ? "left-[calc(100%-2.5rem)]" : "left-2"
              }`}
              style={{ background: "var(--gradient-primary)" }}
            >
              ৳
            </span>
            <span
              className={`text-base font-bold tabular-nums tracking-tight w-full text-center transition-all duration-300 ${
                shown ? "pr-10 pl-2" : "pl-10 pr-2"
              }`}
            >
              {shown ? balanceStr : "ব্যালেন্স দেখতে ক্লিক করুন"}
            </span>
          </button>
        </div>
      </header>

      <div className="px-4 -mt-12 relative z-10">
        <div className="bg-card rounded-2xl shadow-[var(--shadow-elevated)] p-4 grid grid-cols-3 gap-2">
          <QuickAction icon={QrCode} label="My QR" to="/qr" verified={verified} />
          <QuickAction icon={Plus} label="Add Money" to="/add-money" verified={verified} />
          <QuickAction icon={ArrowUpRight} label="Statement" to="/statement" verified={true} />
        </div>
      </div>

      <KycBanner status={kycStatus} />

      <section className="px-4 mt-6">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-base font-bold tracking-tight">সার্ভিস</h2>
        </div>
        <div className="bg-card rounded-2xl p-3 shadow-[var(--shadow-card)] grid grid-cols-4 gap-y-4 gap-x-1">
          <ServiceItem icon={Send} label="Send Money" to="/send" verified={verified} />
          <ServiceItem icon={ArrowDownToLine} label="Cash Out" to="/cash-out" verified={verified} />
          <ServiceItem icon={Smartphone} label="Mobile Recharge" to="/recharge" verified={verified} />
          <ServiceItem icon={CreditCard} label="Payment" to="/payment" verified={verified} />
          <ServiceItem icon={Zap} label="Pay Bill" to="/pay-bill" verified={verified} />
          <ServiceItem icon={Plus} label="Add Money" to="/add-money" verified={verified} />
          <ServiceItem icon={GraduationCap} label="Education Fee" to="/pay-bill" verified={verified} />
          <ServiceItem icon={Heart} label="Donation" to="/payment" verified={verified} />
          <ServiceItem icon={Receipt} label="Request Money" to="/request-money" verified={verified} />
          <ServiceItem icon={MoreHorizontal} label="More" to="/more" verified={true} />
        </div>
      </section>


      <section className="px-4 mt-5">
        <div className="rounded-2xl p-4 text-primary-foreground relative overflow-hidden shadow-[var(--shadow-card)]"
          style={{ background: "var(--gradient-primary)" }}>
          <div className="relative z-10">
            <p className="text-xs font-semibold opacity-90 uppercase tracking-wider">ক্যাশব্যাক অফার</p>
            <h3 className="text-lg font-bold mt-1 leading-tight">বিল পরিশোধে ২০০ টাকা পর্যন্ত ক্যাশব্যাক</h3>
            <Link to="/pay-bill" className="mt-3 inline-block bg-white text-primary text-xs font-bold px-3.5 py-1.5 rounded-full">
              এখনই পরিশোধ
            </Link>
          </div>
          <div className="absolute -right-6 -bottom-6 h-32 w-32 rounded-full bg-white/10" />
          <div className="absolute right-6 top-3 h-16 w-16 rounded-full bg-white/10" />
        </div>
      </section>

      <section className="px-4 mt-6">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-base font-bold tracking-tight">সাম্প্রতিক লেনদেন</h2>
          <Link to="/statement" className="text-xs font-semibold text-primary">সব দেখুন</Link>
        </div>
        <div className="bg-card rounded-2xl shadow-[var(--shadow-card)] divide-y divide-border">
          {txQ.isLoading && <div className="p-6 text-center text-sm text-muted-foreground">লোড হচ্ছে...</div>}
          {!txQ.isLoading && recentTx.length === 0 && (
            <div className="p-6 text-center text-sm text-muted-foreground">এখনো কোনো লেনদেন নেই</div>
          )}
          {recentTx.map((t: any) => {
            const meta = TYPE_META[t.type] ?? TYPE_META.payment;
            const Icon = meta.icon;
            const positive = meta.sign === 1;
            return (
              <div key={t.id} className="flex items-center gap-3 p-3.5">
                <div className={`h-11 w-11 rounded-full flex items-center justify-center shrink-0 ${positive ? "bg-success/10" : "bg-accent"}`}>
                  <Icon className={`h-5 w-5 ${positive ? "text-success" : "text-primary"}`} strokeWidth={2.2} />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="font-semibold text-sm truncate">{t.counterparty_name ?? meta.label}</p>
                  <p className="text-xs text-muted-foreground truncate">
                    {meta.label} · {new Date(t.created_at).toLocaleString("en-GB", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" })}
                  </p>
                </div>
                <div className="text-right">
                  <p className={`font-bold text-sm tabular-nums ${positive ? "text-success" : "text-foreground"}`}>
                    {positive ? "+" : "-"}৳{Number(t.amount).toLocaleString()}
                  </p>
                </div>
              </div>
            );
          })}
        </div>
      </section>

      <GlobalSearch open={searchOpen} onClose={() => setSearchOpen(false)} />
    </div>
  );
}

function QuickAction({ icon: Icon, label, to, verified = true }: { icon: any; label: string; to?: string; verified?: boolean }) {
  const target = verified ? to : "/kyc";
  const inner = (
    <div className="flex flex-col items-center gap-1.5 py-1.5 active:scale-95 transition-transform">
      <div className="h-10 w-10 rounded-xl bg-primary/10 flex items-center justify-center relative">
        <Icon className="h-5 w-5 text-primary" strokeWidth={2.2} />
        {!verified && <span className="absolute -top-0.5 -right-0.5 h-3 w-3 rounded-full bg-destructive ring-2 ring-card" />}
      </div>
      <span className="text-[11px] font-semibold text-foreground/80">{label}</span>
    </div>
  );
  return target ? <Link to={target}>{inner}</Link> : <button>{inner}</button>;
}

function ServiceItem({ icon: Icon, label, to, verified = true }: { icon: any; label: string; to?: string; verified?: boolean }) {
  const target = verified ? to : "/kyc";
  const inner = (
    <div className="flex flex-col items-center gap-1.5 py-2 group active:scale-95 transition-transform">
      <div className="h-12 w-12 rounded-2xl bg-accent flex items-center justify-center group-hover:bg-primary/10 transition-colors relative">
        <Icon className="h-5 w-5 text-primary" strokeWidth={2.2} />
        {!verified && <span className="absolute -top-1 -right-1 h-3.5 w-3.5 rounded-full bg-destructive ring-2 ring-card" />}
      </div>
      <span className="text-[10.5px] font-medium text-center leading-tight text-foreground/80 px-0.5">{label}</span>
    </div>
  );
  return target ? <Link to={target}>{inner}</Link> : <button className="w-full">{inner}</button>;
}

function KycBanner({ status }: { status: string }) {
  if (status === "verified") return null;
  const map: Record<string, { icon: any; bg: string; title: string; body: string }> = {
    unverified: { icon: AlertTriangle, bg: "bg-warning/15 text-warning-foreground border-warning/40", title: "NID ভেরিফাই করুন", body: "লেনদেন করতে পরিচয় যাচাই করা বাধ্যতামূলক।" },
    pending: { icon: Clock, bg: "bg-primary/10 border-primary/30", title: "AI চেক চলছে", body: "একটু পরে আবার দেখুন।" },
    needs_review: { icon: Clock, bg: "bg-primary/10 border-primary/30", title: "অ্যাডমিন রিভিউতে", body: "রিভিউ শেষ হলে জানানো হবে।" },
    rejected: { icon: AlertTriangle, bg: "bg-destructive/10 border-destructive/30 text-destructive", title: "NID রিজেক্ট হয়েছে", body: "আবার আপলোড করে চেষ্টা করুন।" },
  };
  const s = map[status] ?? map.unverified;
  const Icon = s.icon;
  return (
    <div className="px-4 mt-4">
      <Link to="/kyc" className={`block rounded-2xl border p-3.5 ${s.bg} shadow-[var(--shadow-card)]`}>
        <div className="flex items-center gap-3">
          <div className="h-10 w-10 rounded-full bg-white/70 grid place-items-center shrink-0">
            <Icon className="h-5 w-5" />
          </div>
          <div className="flex-1 min-w-0">
            <p className="font-bold text-sm">{s.title}</p>
            <p className="text-[11px] opacity-80 mt-0.5">{s.body}</p>
          </div>
          <span className="text-[11px] font-bold underline">খুলুন</span>
        </div>
      </Link>
    </div>
  );
}


function NavItem({ icon: Icon, label, active, to }: { icon: any; label: string; active?: boolean; to?: string }) {
  const inner = (
    <div className={`flex flex-col items-center gap-1 py-2.5 ${active ? "text-primary" : "text-muted-foreground"}`}>
      <Icon className="h-5 w-5" strokeWidth={active ? 2.4 : 2} />
      <span className="text-[10px] font-semibold">{label}</span>
    </div>
  );
  return to ? <Link to={to}>{inner}</Link> : <button>{inner}</button>;
}
