import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { Wallet, ArrowDownToLine, Sparkles, Gift, ListChecks, History, Download } from "lucide-react";
import { AppShell } from "@/components/app/AppShell";
import { supabase } from "@/integrations/supabase/client";
import { inr, useMe, useSettings } from "@/lib/app";
import { TaskLogo } from "@/components/app/TaskLogo";

export const Route = createFileRoute("/_authenticated/dashboard")({
  head: () => ({ meta: [{ title: "Dashboard – RozTask" }, { name: "description", content: "Your RozTask wallet and earnings." }, { property: "og:title", content: "Dashboard – RozTask" }, { property: "og:description", content: "Your RozTask wallet and earnings." }, { property: "og:type", content: "website" }, { name: "twitter:card", content: "summary" }] }),
  component: Dashboard,
});

function Dashboard() {
  const { data: me } = useMe();
  const { data: s } = useSettings();
  const p = me?.profile;
  const { data: d } = useQuery({
    queryKey: ["dash-counts"],
    queryFn: async () => {
      const [{ data: subs }, { data: tasks }] = await Promise.all([
        supabase.from("submissions").select("status,task_id"),
        supabase.from("tasks").select("id,task_number,app_name,reward,icon_url").eq("is_active", true).order("sort_order").order("task_number"),
      ]);
      const taken = new Set(subs?.filter((x) => x.status !== "rejected").map((x) => x.task_id));
      const open = (tasks ?? []).filter((t) => !taken.has(t.id));
      return {
        done: subs?.filter((x) => x.status === "approved").length ?? 0,
        pending: subs?.filter((x) => x.status === "pending").length ?? 0,
        open,
      };
    },
  });

  const actions = [
    { to: "/tasks", l: "Tasks", i: ListChecks },
    { to: "/refer", l: "Refer & Earn", i: Gift },
    { to: "/withdraw", l: "Withdraw", i: ArrowDownToLine },
    { to: "/history", l: "History", i: History },
  ] as const;

  return (
    <AppShell>
      <div className="mb-4 flex items-center justify-between gap-3">
        <div className="min-w-0">
          <p className="text-sm text-muted-foreground">Welcome back,</p>
          <h1 className="truncate text-3xl font-extrabold">{p?.full_name?.split(" ")[0] || "there"} 👋</h1>
        </div>
        <Link to="/download" className="flex shrink-0 items-center gap-2 rounded-full bg-gradient-primary px-4 py-2.5 text-sm font-bold text-primary-foreground shadow-glow">
          <Download className="h-4 w-4" /> Install App
        </Link>
      </div>

      <div className="animate-rise relative overflow-hidden rounded-3xl border border-border bg-card p-5 text-foreground shadow-card">
        <div className="pointer-events-none absolute -right-16 -top-24 h-48 w-64 rotate-[-18deg] rounded-[50%] bg-gradient-curve opacity-80 blur-[2px]" />
        <div className="pointer-events-none absolute -right-10 -top-20 h-40 w-56 rotate-[-18deg] rounded-[50%] border-2 border-primary-foreground/50" />
        <p className="flex items-center gap-2 relative text-sm font-semibold text-muted-foreground"><Wallet className="h-4 w-4" /> Total Balance</p>
        <p className="relative mt-1 text-5xl font-black">{inr(p?.balance)}</p>
        <div className="mt-4 grid grid-cols-2 gap-3">
          <div className="rounded-2xl bg-secondary p-3"><p className="text-xs text-muted-foreground">Total Earnings</p><p className="text-xl font-extrabold">{inr(p?.total_earned)}</p></div>
          <div className="rounded-2xl bg-secondary p-3"><p className="text-xs text-muted-foreground">Total Withdrawals</p><p className="text-xl font-extrabold">{inr(p?.total_withdrawn)}</p></div>
        </div>
        <div className="mt-4 grid grid-cols-2 gap-3">
          <Link to="/withdraw" className="flex h-12 items-center justify-center gap-2 rounded-full bg-primary font-bold text-primary-foreground shadow-glow"><ArrowDownToLine className="h-4 w-4" /> Withdraw</Link>
          <Link to="/tasks" className="flex h-12 items-center justify-center gap-2 rounded-full bg-soft font-bold text-foreground"><Sparkles className="h-4 w-4 text-primary" /> Earn more</Link>
        </div>
      </div>

      <div className="mt-5 grid grid-cols-4 gap-2">
        {actions.map((a) => (
          <Link key={a.to} to={a.to} className="glass-card flex flex-col items-center gap-2 rounded-2xl px-1 py-3 text-center">
            <span className="flex h-11 w-11 items-center justify-center rounded-full bg-soft text-primary"><a.i className="h-5 w-5" /></span>
            <span className="text-[11px] font-semibold leading-tight">{a.l}</span>
          </Link>
        ))}
      </div>

      <div className="mt-6 mb-3 flex items-center justify-between"><h2 className="text-xl font-extrabold">Available Tasks</h2><Link to="/tasks" className="text-sm font-semibold text-primary">View all</Link></div>
      <div className="space-y-3">
        {d?.open.slice(0, 5).map((t) => (
          <Link key={t.id} to="/tasks" className="glass-card flex items-center gap-4 rounded-3xl p-4">
            <span className="flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-2xl bg-gradient-primary text-lg font-black text-primary-foreground">
              <TaskLogo source={t.icon_url} name={t.app_name} className="h-full w-full object-cover" />
            </span>
            <div className="min-w-0 flex-1"><p className="text-xs text-muted-foreground">Task #{t.task_number}</p><p className="truncate font-bold">{t.app_name}</p></div>
            <span className="shrink-0 rounded-full bg-primary px-3 py-1 font-extrabold text-primary-foreground">+{inr(t.reward)}</span>
          </Link>
        ))}
        {d && d.open.length === 0 && <p className="text-sm text-muted-foreground">All tasks done! New tasks coming soon.</p>}
      </div>
    </AppShell>
  );
}
