import SectionHeading from "./SectionHeading";
import Reveal from "./Reveal";
import { CheckIcon, ArrowRightIcon } from "./icons";
import endPoints from "@/middleware/endPoints";
import {
  BILLING_CYCLE_LABELS,
  type PlanOption,
} from "@/types/subscription";

/**
 * Trailing "talk to us" card. Not a plan — it has no price and nothing to buy —
 * so it isn't in the catalogue. Delete this constant (and the `<CustomCard/>`
 * below) to show only admin-defined plans.
 */
const CONTACT_CARD = {
  name: "Custom",
  tagline: "Tailored for fleets and businesses.",
  features: [
    "Unlimited vehicles",
    "Everything in Premium",
    "Bulk QR registration",
    "Dedicated account manager",
    "Custom integrations",
  ],
  cta: "Contact Us",
  href: "mailto:info@vehcall.com",
};

interface PlansEnvelope {
  status?: boolean;
  data?: PlanOption[];
}

/**
 * Public plan catalogue, straight from the API.
 *
 * Server-side fetch so the marketing page stays cacheable and the browser makes
 * no extra request. Revalidated every 5 minutes, which is how long an admin's plan
 * edit takes to appear here.
 */
async function fetchPublicPlans(): Promise<PlanOption[] | null> {
  const baseUrl = process.env.NEXT_PUBLIC_API_URL;
  if (!baseUrl) return null;

  try {
    const res = await fetch(`${baseUrl}${endPoints.subscriptionPlans}`, {
      headers: { accept: "application/json" },
      next: { revalidate: 300 },
    });
    if (!res.ok) return null;
    const body = (await res.json()) as PlansEnvelope;
    return body.data ?? null;
  } catch (error) {
    // Never take the landing page down because the API is unreachable.
    console.error("[Pricing] could not load plans:", error);
    return null;
  }
}

function Ribbon() {
  return (
    <span className="absolute -top-3 left-1/2 -translate-x-1/2 rounded-full bg-gradient-to-r from-brand to-electric px-4 py-1 text-xs font-bold text-white">
      Most Popular
    </span>
  );
}

function Card({
  featured,
  children,
}: {
  featured?: boolean;
  children: React.ReactNode;
}) {
  return (
    <div
      className={`relative flex h-full flex-col rounded-3xl p-8 ${
        featured
          ? "border border-brand/40 bg-gradient-to-b from-brand/10 to-panel shadow-[0_30px_80px_-40px_rgba(123,108,253,0.5)] lg:-translate-y-3"
          : "glass"
      }`}
    >
      {featured && <Ribbon />}
      {children}
    </div>
  );
}

function FeatureList({
  features,
  featured,
}: {
  features: string[];
  featured?: boolean;
}) {
  return (
    <ul className="mt-7 flex-1 space-y-3.5">
      {features.map((f) => (
        <li key={f} className="flex items-center gap-3 text-sm">
          <span
            className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full ${
              featured ? "bg-brand text-white" : "bg-brand/15 text-brand"
            }`}
          >
            <CheckIcon width={13} height={13} strokeWidth={2.5} />
          </span>
          <span className="text-white/75">{f}</span>
        </li>
      ))}
    </ul>
  );
}

function Cta({
  label,
  href,
  featured,
}: {
  label: string;
  href: string;
  featured?: boolean;
}) {
  return (
    <a
      href={href}
      className={`mt-8 ${featured ? "btn-primary" : "btn-ghost"} w-full`}
    >
      {label}
      <ArrowRightIcon width={17} height={17} />
    </a>
  );
}

function PlanCard({ plan }: { plan: PlanOption }) {
  const featured = plan.isPopular;
  const free = plan.price <= 0;
  return (
    <Card featured={featured}>
      <h3 className="text-lg font-bold text-white">{plan.name}</h3>
      {plan.description && (
        <p className="mt-1 text-sm text-white/55">{plan.description}</p>
      )}

      <div className="mt-6 flex items-end gap-1">
        <span className="font-display text-4xl font-extrabold text-white">
          {plan.priceLabel}
        </span>
        {!free && (
          <span className="pb-1 text-sm text-white/50">
            {BILLING_CYCLE_LABELS[plan.billingCycle]}
          </span>
        )}
      </div>
      {plan.trialDays > 0 && (
        <p className="mt-1 text-xs text-success">
          {plan.trialDays}-day free trial
        </p>
      )}

      <FeatureList features={plan.features} featured={featured} />

      <Cta
        label={free ? "Get Started" : `Choose ${plan.name}`}
        href="/register"
        featured={featured}
      />
    </Card>
  );
}

function CustomCard() {
  return (
    <Card>
      <h3 className="text-lg font-bold text-white">{CONTACT_CARD.name}</h3>
      <p className="mt-1 text-sm text-white/55">{CONTACT_CARD.tagline}</p>
      <div className="mt-6 flex items-end gap-1">
        <span className="font-display text-4xl font-extrabold text-white">
          Custom
        </span>
      </div>
      <FeatureList features={CONTACT_CARD.features} />
      <Cta label={CONTACT_CARD.cta} href={CONTACT_CARD.href} />
    </Card>
  );
}

export default async function Pricing() {
  const plans = await fetchPublicPlans();

  return (
    <section id="pricing" className="relative py-24 sm:py-28">
      <div className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-white/10 to-transparent" />
      <div className="mx-auto max-w-7xl px-5 sm:px-8">
        <SectionHeading
          eyebrow="Pricing / QR Registration"
          title={
            <>
              Choose your <span className="text-gradient">VehCall plan</span>
            </>
          }
          subtitle="Every plan includes your QR sticker and private, number-free communication."
        />

        <div className="mt-16 grid grid-cols-1 items-stretch gap-6 lg:grid-cols-3">
          {(plans ?? []).map((plan, i) => (
            <Reveal key={plan.id} delay={i * 120} className="h-full">
              <PlanCard plan={plan} />
            </Reveal>
          ))}

          <Reveal delay={(plans?.length ?? 0) * 120} className="h-full">
            <CustomCard />
          </Reveal>
        </div>

        {/* Prices are never invented client-side: if the catalogue can't be
            reached, the paid cards are simply absent rather than stale. */}
        {plans === null && (
          <p className="mt-8 text-center text-sm text-white/45">
            Our plans are temporarily unavailable — please check back shortly or
            get in touch.
          </p>
        )}
      </div>
    </section>
  );
}
