"use client";

import { cn } from "@/lib/utils";
import { Panel } from "./parts";
import { usePlans, useChangePlan, useSubscription } from "@/hooks/useSubscription";
import {
  BILLING_CYCLE_LABELS,
  quotaLabel,
  type PlanOption,
} from "@/types/subscription";

function CheckIcon({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 20 20" fill="currentColor" className={className} aria-hidden>
      <path
        fillRule="evenodd"
        d="M16.7 5.3a1 1 0 0 1 0 1.4l-7.5 7.5a1 1 0 0 1-1.4 0L3.3 9.7a1 1 0 1 1 1.4-1.4l3.8 3.8 6.8-6.8a1 1 0 0 1 1.4 0Z"
        clipRule="evenodd"
      />
    </svg>
  );
}

/** One plan card. `current` disables the action; `busy` blocks every card. */
function PlanCard({
  plan,
  current,
  busy,
  pending,
  onChoose,
}: {
  plan: PlanOption;
  current: boolean;
  busy: boolean;
  pending: boolean;
  onChoose: (plan: PlanOption) => void;
}) {
  const free = plan.price <= 0;

  return (
    <div
      className={cn(
        "flex flex-col rounded-2xl border p-5 transition-colors",
        current
          ? "border-brand bg-brand/5"
          : "border-white/10 bg-white/[0.02] hover:border-white/20",
      )}
    >
      <div className="flex items-start justify-between gap-3">
        <div>
          <h3 className="text-base font-semibold text-white">{plan.name}</h3>
          {plan.description && (
            <p className="mt-0.5 text-xs text-white/50">{plan.description}</p>
          )}
        </div>
        {current && (
          <span className="shrink-0 rounded-full bg-brand/15 px-2 py-0.5 text-[0.7rem] font-medium text-brand">
            Current
          </span>
        )}
      </div>

      <div className="mt-4 flex items-baseline gap-1.5">
        <span className="text-2xl font-bold text-white">{plan.priceLabel}</span>
        {!free && (
          <span className="text-xs text-white/45">
            {BILLING_CYCLE_LABELS[plan.billingCycle]}
          </span>
        )}
      </div>
      {plan.trialDays > 0 && (
        <p className="mt-1 text-xs text-success">
          {plan.trialDays}-day free trial
        </p>
      )}

      <ul className="mt-4 flex-1 space-y-2">
        <li className="flex items-center gap-2 text-sm text-white/80">
          <CheckIcon className="h-4 w-4 shrink-0 text-success" />
          {quotaLabel(plan.limits.vehicles)}{" "}
          {plan.limits.vehicles === 1 ? "vehicle" : "vehicles"}
        </li>
        <li className="flex items-center gap-2 text-sm text-white/80">
          <CheckIcon className="h-4 w-4 shrink-0 text-success" />
          {quotaLabel(plan.limits.qrStickers)} QR{" "}
          {plan.limits.qrStickers === 1 ? "sticker" : "stickers"}
        </li>
        {plan.benefits.map((benefit) => (
          <li
            key={benefit.key}
            className={cn(
              "flex items-center gap-2 text-sm",
              benefit.highlight ? "font-medium text-white" : "text-white/80",
            )}
          >
            <CheckIcon className="h-4 w-4 shrink-0 text-success" />
            {benefitLabel(benefit)}
          </li>
        ))}
      </ul>

      <button
        type="button"
        disabled={current || busy}
        onClick={() => onChoose(plan)}
        className={cn(
          "mt-5 w-full text-sm",
          current ? "btn-ghost" : free ? "btn-ghost" : "btn-primary",
          (current || busy) && "cursor-not-allowed opacity-60",
        )}
      >
        {current
          ? "Your plan"
          : pending
            ? "Working…"
            : free
              ? `Switch to ${plan.name}`
              : `Upgrade to ${plan.name}`}
      </button>
    </div>
  );
}

/** One display line for an admin-defined custom point. */
function benefitLabel(benefit: PlanOption["benefits"][number]): string {
  if (benefit.type === "boolean") return benefit.label;
  if (benefit.type === "number") {
    const amount = quotaLabel(Number(benefit.value));
    return `${amount} ${benefit.label}${benefit.unit ? ` ${benefit.unit}` : ""}`;
  }
  const text = String(benefit.value ?? "").trim();
  return text ? `${benefit.label}: ${text}` : benefit.label;
}

/**
 * The plan catalogue, driven by `GET /subscription/plans`. Choosing a paid plan
 * opens Razorpay Checkout; the plan is granted only after the API verifies the
 * payment (see `useChangePlan`).
 */
export function PlanPicker() {
  const plans = usePlans();
  const subscription = useSubscription();
  const { changePlan, busy, pendingSlug, error, success } = useChangePlan();

  const currentPlanId = subscription.data?.planId ?? null;

  return (
    <Panel title="Available Plans" subtitle="Change your plan at any time">
      {error && (
        <p
          role="alert"
          className="mb-4 rounded-xl border border-danger/30 bg-danger/10 px-3 py-2 text-sm text-danger"
        >
          {error}
        </p>
      )}
      {success && (
        <p
          role="status"
          className="mb-4 rounded-xl border border-success/30 bg-success/10 px-3 py-2 text-sm text-success"
        >
          {success}
        </p>
      )}

      {plans.isLoading ? (
        <p className="py-6 text-center text-sm text-white/45">Loading plans…</p>
      ) : plans.isError ? (
        <p className="py-6 text-center text-sm text-white/45">
          Couldn&apos;t load plans. Please try again shortly.
        </p>
      ) : plans.data && plans.data.length > 0 ? (
        <div className="grid gap-4 sm:grid-cols-2">
          {plans.data.map((plan) => (
            <PlanCard
              key={plan.id}
              plan={plan}
              current={
                currentPlanId
                  ? plan.id === currentPlanId
                  : plan.slug === subscription.data?.plan
              }
              busy={busy}
              pending={pendingSlug === plan.slug}
              onChoose={changePlan}
            />
          ))}
        </div>
      ) : (
        <p className="py-6 text-center text-sm text-white/45">
          No plans are available right now.
        </p>
      )}
    </Panel>
  );
}
