import { createFileRoute } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery } from "@tanstack/react-query";
import { getStudentDashboard } from "@/lib/dashboard.functions";
import { getMyPayments } from "@/lib/payment.functions";
import { DashboardLayout } from "@/components/DashboardLayout";

const dashQ = queryOptions({ queryKey: ["dashboard"], queryFn: () => getStudentDashboard() });
const payQ = queryOptions({ queryKey: ["my-payments"], queryFn: () => getMyPayments() });

export const Route = createFileRoute("/_authenticated/my-payments")({
  loader: ({ context }) => Promise.all([context.queryClient.ensureQueryData(dashQ), context.queryClient.ensureQueryData(payQ)]),
  component: MyPaymentsPage,
});

const STATUS_STYLE: Record<string, string> = {
  pending: "bg-warning/15 text-warning",
  approved: "bg-success/15 text-success",
  rejected: "bg-destructive/15 text-destructive",
};

function MyPaymentsPage() {
  const { data: dash } = useSuspenseQuery(dashQ);
  const { data } = useSuspenseQuery(payQ);
  return (
    <DashboardLayout isAdmin={dash.isAdmin}>
      <h1 className="mb-6 font-display text-3xl font-bold">My Payments</h1>
      {data.payments.length === 0 ? (
        <p className="text-sm text-muted-foreground">No payments yet.</p>
      ) : (
        <div className="overflow-hidden rounded-2xl border border-border bg-card">
          <table className="w-full text-sm">
            <thead className="bg-muted/40 text-xs uppercase tracking-wider text-muted-foreground">
              <tr>
                <th className="px-4 py-3 text-left">Date</th>
                <th className="px-4 py-3 text-left">TrxID</th>
                <th className="px-4 py-3 text-right">Amount</th>
                <th className="px-4 py-3 text-left">Status</th>
                <th className="px-4 py-3 text-left">Note</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {data.payments.map((p: any) => (
                <tr key={p.id}>
                  <td className="px-4 py-3 text-muted-foreground">{new Date(p.created_at).toLocaleDateString()}</td>
                  <td className="px-4 py-3 font-mono text-xs">{p.transaction_id}</td>
                  <td className="px-4 py-3 text-right font-semibold">৳{Number(p.amount).toLocaleString("en-BD")}</td>
                  <td className="px-4 py-3"><span className={`rounded-full px-2.5 py-0.5 text-xs font-semibold ${STATUS_STYLE[p.status]}`}>{p.status}</span></td>
                  <td className="px-4 py-3 text-xs text-muted-foreground">{p.admin_note ?? "—"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </DashboardLayout>
  );
}
