"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { CreditCard, ExternalLink, Sparkles } from "lucide-react";
import { PLANS, type PlanKey } from "@/lib/plans";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";

interface BillingSettingsProps {
  plan: string;
  stripeCurrentPeriodEnd: string | null;
  stripeSubscriptionId: string | null;
}

export function BillingSettings({
  plan,
  stripeCurrentPeriodEnd,
  stripeSubscriptionId,
}: BillingSettingsProps) {
  const router = useRouter();
  const [portalLoading, setPortalLoading] = useState(false);

  const currentPlan = (plan in PLANS ? plan : "free") as PlanKey;
  const planInfo = PLANS[currentPlan];
  const isSubscribed = !!stripeSubscriptionId && currentPlan !== "free";
  const periodEnd = stripeCurrentPeriodEnd
    ? new Date(stripeCurrentPeriodEnd)
    : null;

  async function handleManageSubscription() {
    setPortalLoading(true);

    try {
      const response = await fetch("/api/stripe/portal", { method: "POST" });
      const data = (await response.json()) as { url?: string; error?: string };

      if (!response.ok) {
        throw new Error(data.error || "Failed to open billing portal");
      }

      if (data.url) {
        window.location.href = data.url;
      }
    } catch (error) {
      console.error("Portal error:", error);
      alert("Something went wrong. Please try again.");
    } finally {
      setPortalLoading(false);
    }
  }

  return (
    <div className="rounded-xl bg-gray-900 ring-1 ring-gray-800">
      <div className="border-b border-gray-800 px-6 py-4">
        <h3 className="flex items-center gap-2 text-lg font-semibold text-white">
          <CreditCard className="h-5 w-5 text-indigo-400" />
          Billing &amp; Subscription
        </h3>
      </div>

      <div className="space-y-6 p-6">
        {/* Current Plan */}
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm text-gray-400">Current Plan</p>
            <div className="mt-1 flex items-center gap-2">
              <span className="text-xl font-bold text-white">
                {planInfo.name}
              </span>
              {currentPlan !== "free" && (
                <span
                  className={cn(
                    "rounded-full px-2.5 py-0.5 text-xs font-medium",
                    plan === "past_due"
                      ? "bg-red-500/20 text-red-400"
                      : "bg-indigo-500/20 text-indigo-400",
                  )}
                >
                  {plan === "past_due" ? "Past Due" : "Active"}
                </span>
              )}
            </div>
          </div>

          {isSubscribed && planInfo.price > 0 && (
            <div className="text-right">
              <p className="text-2xl font-bold text-white">
                ${planInfo.price}
                <span className="text-sm font-normal text-gray-400">
                  /{currentPlan === "team" ? "seat/mo" : "mo"}
                </span>
              </p>
            </div>
          )}
        </div>

        {/* Next Billing Date */}
        {isSubscribed && periodEnd && (
          <div className="rounded-lg bg-gray-800/50 px-4 py-3">
            <p className="text-sm text-gray-400">
              {plan === "past_due"
                ? "Payment overdue since"
                : "Next billing date"}
            </p>
            <p className="mt-0.5 text-sm font-medium text-white">
              {periodEnd.toLocaleDateString("en-US", {
                year: "numeric",
                month: "long",
                day: "numeric",
              })}
            </p>
          </div>
        )}

        {/* Actions */}
        <div className="flex flex-wrap gap-3">
          {isSubscribed ? (
            <Button
              variant="secondary"
              onClick={handleManageSubscription}
              disabled={portalLoading}
            >
              {portalLoading ? (
                <span className="flex items-center gap-2">
                  <svg
                    className="h-4 w-4 animate-spin"
                    viewBox="0 0 24 24"
                    fill="none"
                  >
                    <circle
                      className="opacity-25"
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      strokeWidth="4"
                    />
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                    />
                  </svg>
                  Loading...
                </span>
              ) : (
                <>
                  <ExternalLink className="h-4 w-4" />
                  Manage Subscription
                </>
              )}
            </Button>
          ) : null}

          {currentPlan === "free" || plan === "past_due" ? (
            <Button
              variant="primary"
              onClick={() => router.push("/pricing")}
              className="bg-indigo-500 shadow-lg shadow-indigo-500/25 hover:bg-indigo-600"
            >
              <Sparkles className="h-4 w-4" />
              {plan === "past_due" ? "Fix Payment" : "Upgrade Plan"}
            </Button>
          ) : (
            <Button
              variant="ghost"
              onClick={() => router.push("/pricing")}
            >
              View Plans
            </Button>
          )}
        </div>

        {/* Free Plan Info */}
        {currentPlan === "free" && (
          <div className="rounded-lg border border-dashed border-gray-700 bg-gray-800/30 px-4 py-3">
            <p className="text-sm text-gray-400">
              You&apos;re on the free plan. Upgrade to Pro for cloud cost
              intelligence, global router data, and multi-device mesh.
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
