import { createFileRoute, useRouter, Link } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";
import { GlassCard, SectionLabel } from "@/components/GlassCard";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { LogOut, Crown, ShieldCheck, Globe, DollarSign, User as UserIcon, Sparkles, Download, Settings2 } from "lucide-react";
import { formatCurrency } from "@/lib/format";
import { useEntitlements } from "@/lib/useEntitlements";


export const Route = createFileRoute("/_authenticated/profile")({
  head: () => ({
    meta: [
      { title: "Profile — PRUDENTIA" },
      { name: "description", content: "Your PRUDENTIA account, plan, and privacy." },
      { property: "og:title", content: "Profile — PRUDENTIA" },
      { property: "og:description", content: "Account & preferences." },
    ],
  }),
  component: ProfilePage,
});

function ProfilePage() {
  const { user } = Route.useRouteContext();
  const router = useRouter();
  const qc = useQueryClient();

  const profileQ = useQuery({ queryKey: ["profile", user.id], queryFn: async () => (await supabase.from("profiles").select("*").eq("id", user.id).single()).data });
  const txQ = useQuery({ queryKey: ["tx", user.id], queryFn: async () => (await supabase.from("transactions").select("*").eq("user_id", user.id)).data ?? [] });

  const p = profileQ.data;
  const entQ = useEntitlements();
  const ent = entQ.data;

  async function signOut() {
    await supabase.auth.signOut();
    qc.clear();
    router.navigate({ to: "/auth" });
  }

  async function exportCSV() {
    const rows = txQ.data ?? [];
    const header = "date,type,amount,category,merchant,note\n";
    const body = rows.map((t: any) => [t.occurred_at, t.type, t.amount, t.category, t.merchant ?? "", (t.note ?? "").replace(/,/g, ";")].join(",")).join("\n");
    const blob = new Blob([header + body], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = `prudentia-transactions-${Date.now()}.csv`; a.click();
    URL.revokeObjectURL(url);
    toast.success("Exported");
  }

  return (
    <div className="px-4 pt-8 space-y-5">
      <header className="flex items-center gap-4 px-1">
        <div className="size-14 rounded-2xl bg-gradient-to-br from-electric to-purple grid place-items-center">
          <UserIcon className="size-6 text-primary-foreground" />
        </div>
        <div className="flex-1">
          <h1 className="text-xl font-semibold">{p?.name ?? "You"}</h1>
          <p className="text-xs text-muted-foreground">{user.email}</p>
        </div>
        <Link to="/settings" className="size-10 rounded-full glass grid place-items-center" aria-label="Settings">
          <Settings2 className="size-4" />
        </Link>
      </header>


      <GlassCard>
        <SectionLabel>Financial profile</SectionLabel>
        <div className="grid grid-cols-2 gap-3 mt-3">
          <Stat icon={Globe} label="Country" value={p?.country ?? "—"} />
          <Stat icon={DollarSign} label="Currency" value={p?.currency ?? "USD"} />
          <Stat icon={ShieldCheck} label="Risk" value={p?.risk_tolerance ?? "—"} />
          <Stat icon={Sparkles} label="Income" value={formatCurrency(Number(p?.monthly_income ?? 0), p?.currency ?? "USD")} />
        </div>
      </GlassCard>

      <SectionLabel>Plan</SectionLabel>
      <GlassCard>
        <div className="flex items-center justify-between">
          <div>
            <p className="text-[10px] uppercase tracking-widest text-muted-foreground">Current</p>
            <p className="text-lg font-semibold uppercase flex items-center gap-2">
              {ent?.plan ?? "free"} {ent?.plan === "elite" && <Crown className="size-4 text-warning" />}
            </p>
          </div>
          <Button asChild variant="outline" className="rounded-full bg-white/5 border-white/10">
            <Link to="/plans" search={{ from: "profile" }}>{ent?.plan === "free" ? "Upgrade" : "Change plan"}</Link>
          </Button>
        </div>
        {ent && (
          <div className="grid grid-cols-2 gap-3 mt-4">
            <Usage label="AI decisions" used={ent.usage.decisions} limit={ent.limits.decisions} />
            <Usage label="Simulations" used={ent.usage.simulations} limit={ent.limits.simulations} />
          </div>
        )}
        <p className="text-[10px] text-muted-foreground mt-3 text-center">
          {ent?.currentPeriodEnd
            ? `Renews ${new Date(ent.currentPeriodEnd).toLocaleDateString()}`
            : "Free plan — usage resets on the 1st of each month."}
        </p>
      </GlassCard>


      <SectionLabel>Data</SectionLabel>
      <GlassCard>
        <Button onClick={exportCSV} variant="outline" className="w-full rounded-full bg-white/5 border-white/10">
          <Download className="size-4 mr-2" /> Export transactions (CSV)
        </Button>
      </GlassCard>

      <Button onClick={signOut} variant="outline" className="w-full rounded-full bg-white/5 border-white/10 text-destructive">
        <LogOut className="size-4 mr-2" /> Sign out
      </Button>
    </div>
  );
}

function Stat({ icon: Icon, label, value }: { icon: any; label: string; value: string }) {
  return (
    <div className="rounded-2xl bg-white/5 border border-white/5 p-3">
      <div className="flex items-center gap-1.5 text-muted-foreground">
        <Icon className="size-3" />
        <p className="text-[10px] uppercase tracking-widest">{label}</p>
      </div>
      <p className="text-sm font-medium mt-1 capitalize">{value}</p>
    </div>
  );
}

function Usage({ label, used, limit }: { label: string; used: number; limit: number | null }) {
  const pct = limit == null ? 100 : Math.min(100, Math.round((used / limit) * 100));
  return (
    <div className="rounded-2xl bg-white/5 border border-white/5 p-3">
      <p className="text-[10px] uppercase tracking-widest text-muted-foreground">{label}</p>
      <p className="text-sm font-medium mt-1 tabular-nums">
        {limit == null ? "Unlimited" : `${used} / ${limit}`}
      </p>
      <div className="mt-2 h-1 rounded-full bg-white/10 overflow-hidden">
        <div
          className="h-full bg-gradient-to-r from-electric to-purple transition-all"
          style={{ width: `${pct}%` }}
        />
      </div>
    </div>
  );
}
