import { AlertTriangle, Clock3, CreditCard, Sparkles } from "lucide-react";
import { Link } from "@inertiajs/react";
import { pricing } from "@/routes/subscription";
import { Button } from "@/components/ui/button";
import type { TradingSubscription } from "@/components/trading/SubscriptionGate";

type LifecycleState =
    | "trial_ending"
    | "trial_expired"
    | "subscription_ending"
    | "expired"
    | "none";

function getState(subscription?: TradingSubscription | null): {
    state: LifecycleState;
    days: number | null;
} {
    if (!subscription) return { state: "none", days: null };

    if (subscription.trial_expired || !subscription.active) {
        return {
            state: subscription.trial_expired ? "trial_expired" : "expired",
            days: 0,
        };
    }

    if (!subscription.ends_at) return { state: "none", days: null };

    const end = new Date(subscription.ends_at).getTime();
    if (!Number.isFinite(end)) return { state: "none", days: null };

    const diff = end - Date.now();
    const days = Math.max(0, Math.ceil(diff / 86400000));

    if (subscription.slug === "free" && days <= 3) {
        return { state: "trial_ending", days };
    }

    if (days <= 3) {
        return { state: "subscription_ending", days };
    }

    return { state: "none", days };
}

export default function SubscriptionLifecycleBanner({
    subscription,
}: {
    subscription?: TradingSubscription | null;
}) {
    const { state, days } = getState(subscription);
    if (state === "none") return null;

    const expired = state === "trial_expired" || state === "expired";
    const title = expired
        ? state === "trial_expired"
            ? "Your trial has expired"
            : "Your subscription has expired"
        : state === "trial_ending"
          ? `Your trial ends in ${days} ${days === 1 ? "day" : "days"}`
          : `Your plan ends in ${days} ${days === 1 ? "day" : "days"}`;

    const description = expired
        ? "Some analysis features may be unavailable until you activate an eligible plan."
        : "Review your plan before access changes. Your current analysis workspace remains available while the plan is active.";

    return (
        <section
            className={`mb-3 rounded-xl border px-3 py-3 sm:px-4 ${
                expired
                    ? "border-destructive/30 bg-destructive/5"
                    : "border-warning-500/30 bg-warning-500/5"
            }`}
            role="status"
            aria-live="polite"
        >
            <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                <div className="flex min-w-0 items-start gap-2.5 sm:gap-3">
                    <div className="mt-0.5 rounded-lg border border-border bg-background p-2 text-muted-foreground">
                        {expired ? (
                            <AlertTriangle
                                className="h-4 w-4"
                                aria-hidden="true"
                            />
                        ) : (
                            <Clock3 className="h-4 w-4" aria-hidden="true" />
                        )}
                    </div>
                    <div className="min-w-0">
                        <p className="text-xs font-semibold text-foreground">
                            {title}
                        </p>
                        <p className="mt-0.5 text-[11px] leading-relaxed text-muted-foreground">
                            {description}
                        </p>
                    </div>
                </div>
                <Button
                    asChild
                    size="sm"
                    className="h-9 w-full shrink-0 gap-1.5 text-xs sm:h-8 sm:w-auto"
                >
                    <Link href={pricing.url()}>
                        {expired ? (
                            <CreditCard
                                className="h-3.5 w-3.5"
                                aria-hidden="true"
                            />
                        ) : (
                            <Sparkles
                                className="h-3.5 w-3.5"
                                aria-hidden="true"
                            />
                        )}
                        {expired ? "View plans" : "Review plan"}
                    </Link>
                </Button>
            </div>
        </section>
    );
}
