"use client";

import { useState, useTransition } from "react";
import { Check } from "lucide-react";
import { Button } from "@/components/ui/Button";
import { PLAN_DEFINITIONS, isStripeConfigured } from "@/config/plans";
import {
  createCheckoutSession,
  createBillingPortalSession,
  downgradeToFree,
} from "@/lib/actions/billing";
import { swalConfirm } from "@/lib/utils/swal";
import type { BillingPageData } from "@/lib/queries/billing-queries";
import type { BillingCycle, PlanTier } from "@/types";

interface BillingPlansProps {
  billing: BillingPageData;
}

export function BillingPlans({ billing }: BillingPlansProps) {
  const [cycle, setCycle] = useState<BillingCycle>(
    billing.billingCycle as BillingCycle
  );
  const [error, setError] = useState<string | null>(null);
  const [pending, startTransition] = useTransition();

  const stripeReady = isStripeConfigured();

  function handleUpgrade(planTier: PlanTier) {
    if (planTier === "enterprise") {
      window.location.href =
        "mailto:sales@surveystronghold.com?subject=Enterprise%20plan";
      return;
    }

    setError(null);
    startTransition(async () => {
      const result = await createCheckoutSession({ planTier, billingCycle: cycle });
      if (!result.success) {
        setError(result.error);
        return;
      }
      if (result.data?.url) {
        window.location.href = result.data.url;
      }
    });
  }

  function handlePortal() {
    setError(null);
    startTransition(async () => {
      const result = await createBillingPortalSession();
      if (!result.success) {
        setError(result.error);
        return;
      }
      if (result.data?.url) window.location.href = result.data.url;
    });
  }

  function handleDowngrade() {
    void (async () => {
      const ok = await swalConfirm({
        title: "Downgrade to Free?",
        text: "You will lose access to Pro features immediately. This cannot be undone.",
        confirmText: "Downgrade",
        cancelText: "Keep Pro",
        danger: true,
      });
      if (!ok) return;
      startTransition(async () => {
        const result = await downgradeToFree();
        if (!result.success) setError(result.error);
      });
    })();
  }

  const quotaPercent = Math.min(
    100,
    (billing.responseQuotaUsed / Math.max(billing.responseQuotaLimit, 1)) * 100
  );

  return (
    <div className="space-y-6">
      <div className="rounded-lg border border-border bg-card p-5 shadow">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <p className="text-xs font-semibold uppercase text-muted">
              Current plan
            </p>
            <p className="font-mono text-2xl font-extrabold capitalize text-navy">
              {billing.planTier}
            </p>
            <p className="text-xs capitalize text-muted">
              {billing.subscriptionStatus.replace("_", " ")} · {billing.billingCycle}
            </p>
          </div>
          <div className="flex flex-wrap gap-2">
            {billing.hasStripeSubscription && stripeReady && (
              <Button variant="outline" size="sm" loading={pending} onClick={handlePortal}>
                {pending ? "Loading…" : "Manage subscription"}
              </Button>
            )}
            {billing.planTier !== "free" && (
              <Button variant="outline" size="sm" loading={pending} onClick={handleDowngrade}>
                {pending ? "Downgrading…" : "Downgrade to Free"}
              </Button>
            )}
          </div>
        </div>
        <div className="mt-4">
          <div className="mb-1 flex justify-between text-xs text-muted">
            <span>Response quota</span>
            <span className="font-mono">
              {billing.responseQuotaUsed.toLocaleString()}/
              {billing.responseQuotaLimit >= 1000
                ? `${billing.responseQuotaLimit / 1000}k`
                : billing.responseQuotaLimit}
            </span>
          </div>
          <div className="h-2 overflow-hidden rounded-full bg-bg">
            <div
              className="h-full bg-accent"
              style={{ width: `${quotaPercent}%` }}
            />
          </div>
        </div>
      </div>

      {!stripeReady && (
        <div className="rounded-lg border border-warning/30 bg-warning-bg px-4 py-3 text-sm text-warning">
          Stripe is not configured. Add STRIPE_SECRET_KEY and price IDs to enable
          checkout. Admins can assign plans manually.
        </div>
      )}

      <div className="flex items-center justify-center gap-3 text-sm font-semibold">
        <span className={cycle === "monthly" ? "text-navy" : "text-muted"}>
          Monthly
        </span>
        <button
          type="button"
          onClick={() =>
            setCycle((c) => (c === "monthly" ? "annual" : "monthly"))
          }
          className={`relative h-7 w-12 rounded-full transition-colors ${
            cycle === "annual" ? "bg-primary" : "bg-border"
          }`}
          aria-label="Toggle billing cycle"
        >
          <span
            className={`absolute top-0.5 h-6 w-6 rounded-full bg-white shadow transition-transform ${
              cycle === "annual" ? "translate-x-[22px]" : "translate-x-0.5"
            }`}
          />
        </button>
        <span className={cycle === "annual" ? "text-navy" : "text-muted"}>
          Annual
        </span>
        <span className="rounded-full bg-success-bg px-2 py-0.5 text-[10px] font-bold text-success">
          Save 20%
        </span>
      </div>

      <div className="grid gap-4 lg:grid-cols-3">
        {(["free", "pro", "enterprise"] as PlanTier[]).map((tier) => {
          const plan = PLAN_DEFINITIONS[tier];
          const isCurrent = billing.planTier === tier;
          const priceCents =
            cycle === "annual"
              ? plan.annualPriceCents
              : plan.monthlyPriceCents;
          const displayPrice =
            tier === "enterprise"
              ? "Custom"
              : tier === "free"
                ? "$0"
                : `$${Math.round(
                    (cycle === "annual" ? priceCents / 12 : priceCents) / 100
                  )}`;

          return (
            <div
              key={tier}
              className={`relative rounded-lg border bg-card p-5 shadow ${
                plan.featured
                  ? "border-primary ring-2 ring-primary/20"
                  : "border-border"
              }`}
            >
              {plan.featured && (
                <span className="absolute -top-2.5 left-4 rounded-full bg-primary px-2.5 py-0.5 text-[10px] font-bold text-white">
                  Most popular
                </span>
              )}
              <p className="text-sm font-bold capitalize text-navy">{plan.name}</p>
              <p className="mt-1 font-mono text-3xl font-extrabold">
                {displayPrice}
                {tier !== "enterprise" && (
                  <span className="text-sm font-normal text-muted">/mo</span>
                )}
              </p>
              <p className="mt-2 text-xs text-muted">{plan.description}</p>
              <ul className="my-4 space-y-2">
                {plan.features.map((f) => (
                  <li key={f} className="flex items-start gap-2 text-xs">
                    <Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-success" />
                    {f}
                  </li>
                ))}
              </ul>
              {isCurrent ? (
                <Button variant="outline" className="w-full" disabled>
                  Current plan
                </Button>
              ) : tier === "free" ? (
                <Button
                  variant="outline"
                  className="w-full"
                  loading={pending}
                  disabled={billing.planTier === "free"}
                  onClick={handleDowngrade}
                >
                  {pending ? "Downgrading…" : "Downgrade"}
                </Button>
              ) : (
                <Button
                  variant={plan.featured ? "primary" : "outline"}
                  className="w-full"
                  loading={pending}
                  onClick={() => handleUpgrade(tier)}
                >
                  {pending ? "Redirecting…" : tier === "enterprise" ? "Talk to sales" : "Upgrade"}
                </Button>
              )}
            </div>
          );
        })}
      </div>

      {error && <p className="text-sm text-danger">{error}</p>}
    </div>
  );
}
