"use client";

import { useState } from "react";
import { toast } from "sonner";
import { Check } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";

type Tier = "free" | "pro" | "family";

type PlanCard = {
  tier: Tier;
  name: string;
  monthlyPrice: string;
  yearlyPrice: string | null;
  features: string[];
  purchasable: boolean;
};

export function BillingPlanCards({ currentTier, plans }: { currentTier: Tier; plans: PlanCard[] }) {
  const [checkingOut, setCheckingOut] = useState<Tier | null>(null);

  async function checkout(tier: "pro" | "family") {
    setCheckingOut(tier);
    try {
      const res = await fetch("/api/v1/billing/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ tier, interval: "month" }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error((data as { error?: string }).error ?? "Checkout failed");
      }
      const { url } = (await res.json()) as { url: string };
      window.location.assign(url);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Checkout failed");
      setCheckingOut(null);
    }
  }

  return (
    <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
      {plans.map((plan) => {
        const isCurrent = plan.tier === currentTier;
        return (
          <Card key={plan.tier} className={cn(isCurrent && "border-primary")}>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle>{plan.name}</CardTitle>
                {isCurrent && <Badge>Current plan</Badge>}
              </div>
              <p className="text-2xl font-bold">{plan.monthlyPrice}</p>
            </CardHeader>
            <CardContent className="space-y-3">
              <ul className="space-y-1.5 text-sm">
                {plan.features.map((f) => (
                  <li key={f} className="flex items-start gap-2">
                    <Check className="h-4 w-4 text-primary shrink-0 mt-0.5" />
                    <span>{f}</span>
                  </li>
                ))}
              </ul>
              {!isCurrent && plan.purchasable && plan.tier !== "free" && (
                <Button
                  className="w-full"
                  disabled={checkingOut !== null}
                  onClick={() => { void checkout(plan.tier as "pro" | "family"); }}
                >
                  {checkingOut === plan.tier ? "Redirecting…" : `Switch to ${plan.name}`}
                </Button>
              )}
              {!isCurrent && !plan.purchasable && plan.tier !== "free" && (
                <p className="text-xs text-muted-foreground">Not available yet — pricing not configured.</p>
              )}
            </CardContent>
          </Card>
        );
      })}
    </div>
  );
}
