import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { getMyProfile } from "@/lib/bkash.functions";
import { supabase } from "@/integrations/supabase/client";
import { ActionScreen } from "@/components/bkash/ActionScreen";
import { ChevronRight, LogOut, Shield, Bell, HelpCircle, FileText, QrCode, User, Headphones } from "lucide-react";
import { NotificationBadge } from "@/components/bkash/NotificationBadge";
import { useAppSettings } from "@/hooks/useAppSettings";

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

function AccountPage() {
  const getProfile = useServerFn(getMyProfile);
  const q = useQuery({ queryKey: ["profile"], queryFn: () => getProfile() });
  const qc = useQueryClient();
  const navigate = useNavigate();

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

  const name = q.data?.full_name ?? "...";
  const initial = name.charAt(0).toUpperCase();
  const avatarUrl = (q.data as any)?.avatar_url ?? null;

  return (
    <ActionScreen title="আমার অ্যাকাউন্ট">
      <div className="bg-card rounded-2xl shadow-[var(--shadow-elevated)] p-5 flex items-center gap-4 relative">
        <Link to="/profile-info" className="h-16 w-16 rounded-full overflow-hidden ring-2 ring-primary/20 grid place-items-center text-2xl font-bold text-primary-foreground shrink-0"
          style={{ background: "var(--gradient-primary)" }}>
          {avatarUrl ? <img src={avatarUrl} alt={name} className="h-full w-full object-cover" /> : initial}
        </Link>
        <div className="min-w-0 flex-1">
          <p className="font-bold text-lg truncate">{name}</p>
          <p className="text-sm text-muted-foreground tabular-nums">{q.data?.phone}</p>
        </div>
        <Link to="/profile-info" className="absolute top-3 right-3 text-xs text-primary font-semibold">দেখুন →</Link>
      </div>

      <div className="bg-card rounded-2xl shadow-[var(--shadow-card)] mt-4 divide-y divide-border overflow-hidden">
        <Row icon={QrCode} label="আমার QR কোড" to="/qr" />
        <Row icon={FileText} label="স্টেটমেন্ট" to="/statement" />
        <Row icon={User} label="প্রোফাইল তথ্য" to="/profile-info" />
        <Row icon={Bell} label="নোটিফিকেশন" to="/notifications" badge />
        <Row icon={Headphones} label="লাইভ সাপোর্ট" to="/support" />
        <Row icon={Shield} label="নিরাপত্তা ও পিন" />
        <Row icon={HelpCircle} label="সাহায্য কেন্দ্র" />
      </div>


      <button onClick={signOut} className="mt-5 w-full h-12 rounded-full border border-destructive/30 text-destructive font-semibold flex items-center justify-center gap-2">
        <LogOut className="h-4 w-4" /> সাইন আউট
      </button>
      <FooterText />
    </ActionScreen>
  );
}

function FooterText() {
  const { settings } = useAppSettings();
  return (
    <p className="text-center text-[10px] text-muted-foreground mt-4">{settings.footer_text || `© ${settings.app_name}`} • v1.0.0</p>
  );
}


function Row({ icon: Icon, label, to, badge }: { icon: any; label: string; to?: string; badge?: boolean }) {
  const inner = (
    <div className="flex items-center gap-3 p-4 active:bg-accent">
      <div className="relative h-9 w-9 rounded-xl bg-accent flex items-center justify-center">
        <Icon className="h-4 w-4 text-primary" />
        {badge && <NotificationBadge />}
      </div>
      <span className="flex-1 text-sm font-medium">{label}</span>
      <ChevronRight className="h-4 w-4 text-muted-foreground" />
    </div>
  );
  return to ? <Link to={to}>{inner}</Link> : <button className="w-full text-left">{inner}</button>;
}
