"use client"

import {
  useCreateCheckoutMutation,
  useCreatePortalMutation,
  useSubscriptionQuery,
} from "@/services/billing"
import { useTranslations } from "next-intl"

export default function BillingPage() {
  const t = useTranslations("billing")
  const { data: subscription, isLoading } = useSubscriptionQuery()
  const checkoutMutation = useCreateCheckoutMutation()
  const portalMutation = useCreatePortalMutation()

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    )
  }

  const isTrialing = subscription?.status === "TRIALING"
  const isActive = subscription?.status === "ACTIVE"
  const isPastDue = subscription?.status === "PAST_DUE"
  const isCanceled = subscription?.status === "CANCELED"

  const trialDaysLeft = subscription?.trialEndsAt
    ? Math.max(
        0,
        Math.ceil(
          (new Date(subscription.trialEndsAt).getTime() - Date.now()) /
            (1000 * 60 * 60 * 24)
        )
      )
    : 0

  const trialExpired = isTrialing && trialDaysLeft <= 0

  const plans = [
    {
      tier: "STARTER",
      name: t("starter"),
      price: t("starterPrice"),
      description: t("starterDesc"),
      memberLimit: 30,
    },
    {
      tier: "PRO",
      name: t("pro"),
      price: t("proPrice"),
      description: t("proDesc"),
      memberLimit: 100,
    },
    {
      tier: "ENTERPRISE",
      name: t("enterprise"),
      price: t("enterprisePrice"),
      description: t("enterpriseDesc"),
      memberLimit: 500,
    },
  ]

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">{t("title")}</h1>
      </div>

      {/* Current Plan Card */}
      <div className="rounded-lg border bg-card p-6 shadow-sm">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-sm text-muted-foreground">{t("currentPlan")}</p>
            <p className="text-2xl font-bold">
              {subscription?.planTier === "TRIAL"
                ? t("trial")
                : subscription?.planTier === "STARTER"
                  ? t("starter")
                  : subscription?.planTier === "PRO"
                    ? t("pro")
                    : t("enterprise")}
            </p>
          </div>
          <div className="text-right">
            {isActive && (
              <span className="inline-flex items-center rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-800 dark:bg-green-900/30 dark:text-green-400">
                {t("active")}
              </span>
            )}
            {isPastDue && (
              <span className="inline-flex items-center rounded-full bg-yellow-100 px-2.5 py-0.5 text-xs font-medium text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400">
                {t("pastDue")}
              </span>
            )}
            {isCanceled && (
              <span className="inline-flex items-center rounded-full bg-red-100 px-2.5 py-0.5 text-xs font-medium text-red-800 dark:bg-red-900/30 dark:text-red-400">
                {t("canceled")}
              </span>
            )}
            {isTrialing && !trialExpired && (
              <span className="inline-flex items-center rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-900/30 dark:text-blue-400">
                {t("trial")}
              </span>
            )}
          </div>
        </div>

        {/* Trial countdown */}
        {isTrialing && !trialExpired && (
          <p className="mt-2 text-sm text-muted-foreground">
            {t("trialDaysLeft", { days: trialDaysLeft })}
          </p>
        )}

        {/* Member usage */}
        {subscription && (
          <div className="mt-4">
            <p className="text-sm text-muted-foreground">{t("memberLimit")}</p>
            <p className="text-sm font-medium">
              {t("membersUsed", {
                used: "—",
                limit: subscription.memberLimit,
              })}
            </p>
          </div>
        )}

        {/* Next billing date */}
        {subscription?.currentPeriodEnd && isActive && (
          <div className="mt-4">
            <p className="text-sm text-muted-foreground">{t("nextBilling")}</p>
            <p className="text-sm font-medium">
              {new Date(subscription.currentPeriodEnd).toLocaleDateString(
                "de-DE"
              )}
            </p>
          </div>
        )}

        {/* Manage billing button */}
        {subscription?.hasStripeSubscription && (
          <button
            onClick={() => portalMutation.mutate()}
            disabled={portalMutation.isPending}
            className="mt-4 inline-flex items-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium shadow-sm hover:bg-accent hover:text-accent-foreground"
          >
            {portalMutation.isPending ? "..." : t("manageBilling")}
          </button>
        )}
      </div>

      {/* Trial expired banner */}
      {trialExpired && (
        <div className="rounded-lg border border-destructive/50 bg-destructive/10 p-4">
          <p className="text-sm font-medium text-destructive">
            {t("trialExpired")}
          </p>
        </div>
      )}

      {/* Plan selection */}
      {(!subscription?.hasStripeSubscription || trialExpired) && (
        <div>
          <h2 className="text-lg font-semibold mb-4">{t("upgrade")}</h2>
          <div className="grid gap-4 md:grid-cols-3">
            {plans.map((plan) => (
              <div
                key={plan.tier}
                className="rounded-lg border bg-card p-6 shadow-sm flex flex-col"
              >
                <h3 className="text-lg font-semibold">{plan.name}</h3>
                <p className="mt-1 text-2xl font-bold">
                  {plan.price}
                  {plan.tier !== "ENTERPRISE" && (
                    <span className="text-sm font-normal text-muted-foreground">
                      /Monat
                    </span>
                  )}
                </p>
                <p className="mt-2 text-sm text-muted-foreground flex-1">
                  {plan.description}
                </p>
                <button
                  onClick={() => {
                    if (plan.tier !== "ENTERPRISE") {
                      checkoutMutation.mutate(plan.tier)
                    }
                  }}
                  disabled={
                    checkoutMutation.isPending || plan.tier === "ENTERPRISE"
                  }
                  className="mt-4 w-full rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"
                >
                  {checkoutMutation.isPending
                    ? "..."
                    : plan.tier === "ENTERPRISE"
                      ? "Kontakt aufnehmen"
                      : t("selectPlan")}
                </button>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}
