import { createFileRoute } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { Check, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { changeMyPlan, listPlans } from "@/lib/plans.functions";
import { getMe } from "@/lib/dashboard.functions";

export const Route = createFileRoute("/_authenticated/subscription")({
  head: () => ({ meta: [{ title: "Subscription — eBay BOS" }] }),
  component: SubscriptionPage,
});

function SubscriptionPage() {
  const qc = useQueryClient();
  const fetchPlans = useServerFn(listPlans);
  const fetchMe = useServerFn(getMe);
  const doChange = useServerFn(changeMyPlan);

  const plans = useQuery({
    queryKey: ["plans-public"],
    queryFn: () => fetchPlans({ data: undefined as never }),
  });
  const me = useQuery({ queryKey: ["me"], queryFn: () => fetchMe({ data: undefined as never }) });

  const switchMut = useMutation({
    mutationFn: (planId: string) => doChange({ data: { plan_id: planId } }),
    onSuccess: () => {
      toast.success("Plan updated");
      qc.invalidateQueries({ queryKey: ["me"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <div className="mx-auto max-w-5xl space-y-6 px-6 py-8">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Subscription</h1>
        <p className="mt-1 text-sm text-muted-foreground">
          Current plan: <span className="font-medium">{me.data?.plan?.name ?? "Free"}</span>
        </p>
      </div>

      {plans.isLoading && (
        <div className="flex justify-center py-12">
          <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
        </div>
      )}

      <div className="grid gap-4 md:grid-cols-3">
        {plans.data?.map((p) => {
          const isCurrent = me.data?.plan?.code === p.code;
          const isFree = (p.price_cents ?? 0) === 0;
          const features = Object.entries((p.features as Record<string, unknown>) ?? {})
            .filter(([, v]) => v)
            .map(([k]) => k);
          return (
            <div
              key={p.id}
              className={`flex flex-col rounded-xl border bg-card p-6 ${
                isCurrent ? "ring-2 ring-primary" : ""
              }`}
            >
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-semibold">{p.name}</h3>
                {isCurrent && <Badge>Current</Badge>}
              </div>
              <div className="mt-3 flex items-baseline gap-1">
                <span className="text-3xl font-bold">
                  ${(p.price_cents / 100).toFixed(0)}
                </span>
                <span className="text-sm text-muted-foreground">/{p.interval}</span>
              </div>
              {p.description && (
                <p className="mt-2 text-sm text-muted-foreground">{p.description}</p>
              )}
              <ul className="mt-4 flex-1 space-y-2 text-sm">
                {features.map((f) => (
                  <li key={f} className="flex items-center gap-2">
                    <Check className="h-4 w-4 text-primary" /> {f.replace(/_/g, " ")}
                  </li>
                ))}
                {features.length === 0 && (
                  <li className="text-muted-foreground">Standard features included.</li>
                )}
              </ul>
              <Button
                className="mt-6"
                variant={isCurrent ? "outline" : "default"}
                disabled={isCurrent || switchMut.isPending}
                onClick={() => {
                  if (!isFree) {
                    toast.info("Paid checkout is coming in Phase 2.");
                    return;
                  }
                  switchMut.mutate(p.id);
                }}
              >
                {isCurrent ? "Current plan" : isFree ? "Switch to Free" : "Upgrade"}
              </Button>
            </div>
          );
        })}
      </div>
    </div>
  );
}
