"use client";

import { useSubscriptionStatus, useCreateCheckoutSession, useCreatePortalSession } from "@/lib/hooks/use-subscription";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Crown, Sparkles, ExternalLink, Loader2 } from "lucide-react";
import { toast } from "sonner";

const STRIPE_PRICE_MONTHLY = process.env.NEXT_PUBLIC_STRIPE_PRICE_MONTHLY ?? "";
const STRIPE_PRICE_YEARLY = process.env.NEXT_PUBLIC_STRIPE_PRICE_YEARLY ?? "";

interface LimitBarProps {
  label: string;
  max: number | null;
}

function LimitBar({ label, max }: LimitBarProps) {
  const isUnlimited = max === null || max === -1;
  return (
    <div className="space-y-1.5">
      <div className="flex items-center justify-between text-sm">
        <span className="text-muted-foreground">{label}</span>
        <span className="font-medium">{isUnlimited ? "Unlimited" : max}</span>
      </div>
      <div className="h-2 w-full rounded-full bg-muted">
        <div
          className="h-full rounded-full bg-primary transition-all"
          style={{ width: isUnlimited ? "100%" : "0%" }}
        />
      </div>
    </div>
  );
}

function getOrigin() {
  if (typeof window !== "undefined") return window.location.origin;
  return "";
}

export function SubscriptionStatus() {
  const { data: status, isLoading } = useSubscriptionStatus();
  const checkoutMutation = useCreateCheckoutSession();
  const portalMutation = useCreatePortalSession();

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Subscription</CardTitle>
          <CardDescription>Your current plan and usage limits.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="flex items-center gap-3">
            <Skeleton className="h-6 w-20 rounded-full" />
            <Skeleton className="h-4 w-16" />
          </div>
          {Array.from({ length: 4 }).map((_, i) => (
            <div key={i} className="space-y-1.5">
              <div className="flex justify-between">
                <Skeleton className="h-4 w-24" />
                <Skeleton className="h-4 w-12" />
              </div>
              <Skeleton className="h-2 w-full rounded-full" />
            </div>
          ))}
        </CardContent>
      </Card>
    );
  }

  if (!status) return null;

  const tier = status.tier ?? "free";
  const isFree = tier === "free";
  const isPro = tier === "pro" || tier === "premium";
  const source = status.subscription_source;

  // Get limits for the user's current tier (fall back to free limits)
  const currentLimits = status.limits?.[tier] ?? status.limits?.["free"];

  function handleCheckout(priceId: string) {
    const origin = getOrigin();
    checkoutMutation.mutate(
      {
        price_id: priceId,
        success_url: `${origin}/subscription/success`,
        cancel_url: `${origin}/subscription/cancel`,
      },
      {
        onSuccess: (data) => {
          window.location.href = data.checkout_url;
        },
        onError: (error) => {
          toast.error(error.message || "Failed to start checkout");
        },
      },
    );
  }

  function handleManageSubscription() {
    const origin = getOrigin();
    portalMutation.mutate(
      { return_url: `${origin}/app/settings/subscription` },
      {
        onSuccess: (data) => {
          window.location.href = data.portal_url;
        },
        onError: (error) => {
          toast.error(error.message || "Failed to open subscription portal");
        },
      },
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Subscription</CardTitle>
        <CardDescription>Your current plan and usage limits.</CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Tier badge and status */}
        <div className="flex items-center gap-3">
          <Badge variant={isPro ? "default" : "secondary"} className="gap-1">
            {isPro ? <Crown className="size-3" /> : null}
            {tier.charAt(0).toUpperCase() + tier.slice(1)}
          </Badge>
          <span className="text-sm text-muted-foreground">
            {status.is_active ? "Active" : "Inactive"}
          </span>
          {status.trial_active && status.trial_end && (
            <Badge variant="outline" className="text-xs">
              Trial ends on{" "}
              {new Date(status.trial_end).toLocaleDateString(undefined, {
                year: "numeric",
                month: "short",
                day: "numeric",
              })}
            </Badge>
          )}
        </div>

        {/* Expiry date for pro */}
        {isPro && status.expires_at && (
          <p className="text-sm text-muted-foreground">
            Renews on{" "}
            <span className="font-medium text-foreground">
              {new Date(status.expires_at).toLocaleDateString(undefined, {
                year: "numeric",
                month: "long",
                day: "numeric",
              })}
            </span>
          </p>
        )}

        {/* Limits */}
        {currentLimits && (
          <div className="space-y-4">
            <h3 className="text-sm font-medium">Plan Limits</h3>
            <LimitBar label="Residences" max={currentLimits.properties} />
            <LimitBar label="Tasks per Residence" max={currentLimits.tasks} />
            <LimitBar label="Contractors" max={currentLimits.contractors} />
            <LimitBar label="Documents" max={currentLimits.documents} />
          </div>
        )}

        {/* Manage subscription for Pro users */}
        {isPro && source === "stripe" && (
          <Button
            variant="outline"
            className="gap-2"
            onClick={handleManageSubscription}
            disabled={portalMutation.isPending}
          >
            {portalMutation.isPending ? (
              <Loader2 className="size-4 animate-spin" />
            ) : (
              <ExternalLink className="size-4" />
            )}
            Manage Subscription
          </Button>
        )}

        {isPro && (source === "ios" || source === "apple") && (
          <p className="text-sm text-muted-foreground">
            Manage your subscription in the App Store on your iOS device.
          </p>
        )}

        {isPro && source === "android" && (
          <p className="text-sm text-muted-foreground">
            Manage your subscription in Google Play on your Android device.
          </p>
        )}

        {/* Upgrade CTA for free tier */}
        {isFree && (
          <div className="rounded-lg border border-primary/20 bg-primary/5 p-4">
            <div className="flex items-start gap-3">
              <Sparkles className="size-5 text-primary mt-0.5" />
              <div className="space-y-3">
                <div className="space-y-1">
                  <p className="text-sm font-medium">Upgrade to Pro</p>
                  <p className="text-sm text-muted-foreground">
                    Unlock unlimited residences, tasks, and more features.
                  </p>
                </div>
                <div className="flex flex-wrap gap-2">
                  <Button
                    size="sm"
                    onClick={() => handleCheckout(STRIPE_PRICE_MONTHLY)}
                    disabled={checkoutMutation.isPending || !STRIPE_PRICE_MONTHLY}
                  >
                    {checkoutMutation.isPending ? (
                      <Loader2 className="size-4 animate-spin mr-1" />
                    ) : null}
                    Monthly Pro
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    onClick={() => handleCheckout(STRIPE_PRICE_YEARLY)}
                    disabled={checkoutMutation.isPending || !STRIPE_PRICE_YEARLY}
                  >
                    {checkoutMutation.isPending ? (
                      <Loader2 className="size-4 animate-spin mr-1" />
                    ) : null}
                    Annual Pro
                  </Button>
                </div>
              </div>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
