import { createFileRoute } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";

import type { Plan } from "@rubis/shared";
import { api } from "@/lib/api";
import { queryKeys } from "@/lib/queryKeys";
import { PlanCard, CreatePlanCard } from "@/components/plans/PlanCard";

type PlanWithUsage = Plan & { usageCount: number };

export const Route = createFileRoute("/_app/plans")({
  component: PlansLibraryPage,
  loader: ({ context }) => {
    void context.queryClient.prefetchQuery({
      queryKey: queryKeys.plans.all(),
      queryFn: () => api.get<PlanWithUsage[]>("/api/v1/plans"),
    });
  },
});

function PlansLibraryPage() {
  const { data: plans = [], isPending } = useQuery({
    queryKey: queryKeys.plans.all(),
    queryFn: () => api.get<PlanWithUsage[]>("/api/v1/plans"),
  });

  // Le plan le plus utilisé reçoit le badge "★ Le plus utilisé". On ne le
  // calcule que s'il y a au moins une facture active (sinon le badge n'a
  // pas de sens).
  const mostUsedPlanId = plans.reduce<string | null>((best, plan) => {
    if (plan.usageCount <= 0) return best;
    if (!best) return plan.id;
    const bestPlan = plans.find((p) => p.id === best);
    return plan.usageCount > (bestPlan?.usageCount ?? 0) ? plan.id : best;
  }, null);

  return (
    <div className="flex flex-col gap-6">
      <div>
        <h1 className="font-display text-[26px] font-bold tracking-[-0.022em] text-ink">
          Plans de <em className="text-rubis">relance</em>
        </h1>
        <p className="mt-1.5 max-w-xl text-[14px] text-ink-3 leading-relaxed">
          Un plan = une cadence d&apos;emails automatisée que Rubis joue pour
          vous. Quatre modèles vous sont fournis — modifiables, mais déjà bien
          calibrés.
        </p>
      </div>

      {isPending ? (
        <PlansSkeleton />
      ) : (
        <ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 lg:gap-5">
          {plans.map((plan) => (
            <li key={plan.id}>
              <PlanCard plan={plan} isMostUsed={plan.id === mostUsedPlanId} />
            </li>
          ))}
          <li>
            <CreatePlanCard />
          </li>
        </ul>
      )}
    </div>
  );
}

function PlansSkeleton() {
  return (
    <ul className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 lg:gap-5">
      {Array.from({ length: 4 }).map((_, idx) => (
        <li
          key={idx}
          className="rounded-card border border-line bg-white p-6 h-[240px] animate-pulse"
        >
          <div className="h-4 w-1/2 rounded bg-cream-2" />
          <div className="mt-4 space-y-2">
            <div className="h-3 w-2/3 rounded bg-cream-2" />
            <div className="h-3 w-1/2 rounded bg-cream-2" />
            <div className="h-3 w-3/5 rounded bg-cream-2" />
          </div>
        </li>
      ))}
    </ul>
  );
}
