"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import {
  Check, Crown, Zap, Building2,
  AlertTriangle, ExternalLink, CreditCard, Loader2, Star,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { cn, formatDate } from "@/lib/utils";
import { STRIPE_PLANS } from "@/lib/stripe";
import { toast } from "sonner";

// ─── Types ─────────────────────────────────────────────────────

type PlanKey = "FREE" | "PRO" | "BUSINESS";

type SubscriptionData = {
  plan: PlanKey;
  status: "ACTIVE" | "TRIALING" | "PAST_DUE" | "CANCELED" | "INCOMPLETE";
  currentPeriodEnd?: string | null;
  cancelAtPeriodEnd?: boolean;
  stripeCustomerId?: string | null;
};

// ─── Config UI des plans ───────────────────────────────────────

const PLAN_UI: Record<PlanKey, {
  icon: React.ElementType;
  iconClass: string;
  borderClass: string;
  headerClass: string;
  priceColor: string;
  badge?: string;
  popular?: boolean;
}> = {
  FREE: {
    icon: Zap,
    iconClass: "text-slate-500",
    borderClass: "",
    headerClass: "bg-slate-50 dark:bg-slate-900/40",
    priceColor: "text-slate-800 dark:text-slate-200",
  },
  PRO: {
    icon: Crown,
    iconClass: "text-amber-500",
    borderClass: "border-amber-300 dark:border-amber-700",
    headerClass: "bg-gradient-to-br from-amber-50 to-orange-50 dark:from-amber-900/20 dark:to-orange-900/20",
    priceColor: "text-amber-700 dark:text-amber-400",
    badge: "Populaire",
    popular: true,
  },
  BUSINESS: {
    icon: Building2,
    iconClass: "text-blue-600",
    borderClass: "border-blue-300 dark:border-blue-700",
    headerClass: "bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20",
    priceColor: "text-blue-700 dark:text-blue-400",
    badge: "Tout inclus",
  },
};

const STATUS_CONFIG: Record<SubscriptionData["status"], { label: string; variant: "default" | "secondary" | "destructive" | "outline" | "warning" | "success" }> = {
  ACTIVE:     { label: "Actif",         variant: "success" as any },
  TRIALING:   { label: "Essai gratuit", variant: "secondary" },
  PAST_DUE:   { label: "Paiement dû",   variant: "warning" as any },
  CANCELED:   { label: "Annulé",        variant: "destructive" },
  INCOMPLETE: { label: "Incomplet",     variant: "outline" },
};

// ─── Mock data ─────────────────────────────────────────────────

const MOCK_SUBSCRIPTION: SubscriptionData = {
  plan: "FREE",
  status: "ACTIVE",
  currentPeriodEnd: null,
  cancelAtPeriodEnd: false,
  stripeCustomerId: null,
};

// ─── Composant carte plan ──────────────────────────────────────

function PlanCard({
  planKey,
  plan,
  currentPlan,
  isLoading,
  onUpgrade,
  onManage,
  hasStripeCustomer,
}: {
  planKey: PlanKey;
  plan: (typeof STRIPE_PLANS)[PlanKey];
  currentPlan: PlanKey;
  isLoading: boolean;
  onUpgrade: (planKey: PlanKey) => void;
  onManage: () => void;
  hasStripeCustomer: boolean;
}) {
  const ui = PLAN_UI[planKey];
  const Icon = ui.icon;
  const isCurrent = currentPlan === planKey;
  const isDowngrade = currentPlan === "BUSINESS" && planKey === "PRO" ||
                      currentPlan !== "FREE" && planKey === "FREE";

  return (
    <Card className={cn(
      "relative flex flex-col transition-all duration-200",
      ui.borderClass && `border-2 ${ui.borderClass}`,
      ui.popular && "shadow-lg scale-[1.02]",
      isCurrent && "ring-2 ring-primary ring-offset-2"
    )}>
      {/* Badge */}
      {(ui.badge || isCurrent) && (
        <div className="absolute -top-3 left-1/2 -translate-x-1/2 z-10">
          <span className={cn(
            "inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-semibold shadow-sm",
            isCurrent
              ? "bg-primary text-primary-foreground"
              : ui.popular
                ? "bg-amber-500 text-white"
                : "bg-blue-600 text-white"
          )}>
            {isCurrent ? (
              <><Star className="h-3 w-3 fill-current" /> Plan actuel</>
            ) : (
              ui.badge
            )}
          </span>
        </div>
      )}

      {/* Header */}
      <div className={cn("rounded-t-[calc(var(--radius)-1px)] px-6 pt-8 pb-5", ui.headerClass)}>
        <div className="flex items-center gap-3 mb-3">
          <div className={cn(
            "h-10 w-10 rounded-xl flex items-center justify-center",
            planKey === "FREE" ? "bg-slate-200 dark:bg-slate-700" :
            planKey === "PRO" ? "bg-amber-100 dark:bg-amber-900/40" :
            "bg-blue-100 dark:bg-blue-900/40"
          )}>
            <Icon className={cn("h-5 w-5", ui.iconClass)} />
          </div>
          <div>
            <h3 className="font-bold text-lg leading-tight">{plan.name}</h3>
            <p className="text-xs text-muted-foreground">
              {planKey === "FREE" ? "Pour commencer" : planKey === "PRO" ? "Pour les pros" : "Pour les équipes"}
            </p>
          </div>
        </div>
        <div className={cn("text-3xl font-extrabold tabular-nums", ui.priceColor)}>
          {plan.price === 0 ? (
            "Gratuit"
          ) : (
            <>
              {plan.price} €
              <span className="text-sm font-normal text-muted-foreground ml-1">/mois</span>
            </>
          )}
        </div>
        {plan.price > 0 && (
          <p className="text-xs text-muted-foreground mt-1">
            Soit {Math.round(plan.price * 12 * 0.85)} € /an (−15% annuel)
          </p>
        )}
      </div>

      <Separator />

      {/* Features */}
      <CardContent className="flex-1 px-6 py-4">
        <ul className="space-y-2.5">
          {plan.features.map((feature, i) => (
            <li key={i} className="flex items-start gap-2.5">
              <Check className={cn(
                "h-4 w-4 mt-0.5 shrink-0",
                planKey === "FREE" ? "text-slate-500" :
                planKey === "PRO" ? "text-amber-500" :
                "text-blue-600"
              )} />
              <span className="text-sm text-muted-foreground leading-snug">{feature}</span>
            </li>
          ))}
        </ul>
      </CardContent>

      {/* CTA */}
      <div className="px-6 pb-6">
        {isCurrent ? (
          hasStripeCustomer ? (
            <Button
              variant="outline"
              className="w-full gap-2"
              onClick={onManage}
              disabled={isLoading}
            >
              {isLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <CreditCard className="h-4 w-4" />}
              Gérer mon abonnement
            </Button>
          ) : (
            <Button variant="outline" className="w-full" disabled>
              Plan actuel
            </Button>
          )
        ) : planKey === "FREE" && currentPlan !== "FREE" ? (
          <Button
            variant="outline"
            className="w-full text-muted-foreground"
            onClick={onManage}
            disabled={isLoading}
          >
            Rétrograder (via portail)
          </Button>
        ) : (
          <Button
            className={cn(
              "w-full gap-2 font-semibold",
              planKey === "PRO"
                ? "bg-amber-500 hover:bg-amber-600 text-white"
                : "bg-blue-600 hover:bg-blue-700 text-white"
            )}
            onClick={() => onUpgrade(planKey)}
            disabled={isLoading}
          >
            {isLoading ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Icon className="h-4 w-4" />
            )}
            Passer au plan {plan.name}
          </Button>
        )}
      </div>
    </Card>
  );
}

// ─── Composant principal ───────────────────────────────────────

export default function AbonnementPage() {
  const { data: session } = useSession();
  const router = useRouter();
  const [subscription, setSubscription] = useState<SubscriptionData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);

  // Chargement abonnement actuel
  useEffect(() => {
    if (!session?.user) return;
    fetch("/api/organizations/current")
      .then((r) => r.json())
      .then((data) => {
        if (data.success && data.data?.subscription) {
          const sub = data.data.subscription;
          setSubscription({
            plan: sub.plan ?? "FREE",
            status: sub.status ?? "ACTIVE",
            currentPeriodEnd: sub.currentPeriodEnd,
            cancelAtPeriodEnd: sub.cancelAtPeriodEnd ?? false,
            stripeCustomerId: data.data.stripeCustomerId,
          });
        } else {
          setSubscription(MOCK_SUBSCRIPTION);
        }
      })
      .catch(() => setSubscription(MOCK_SUBSCRIPTION))
      .finally(() => setIsLoading(false));
  }, [session?.user]);

  const handleUpgrade = async (planKey: PlanKey) => {
    setActionLoading(true);
    try {
      const plan = STRIPE_PLANS[planKey];
      const priceId = plan.monthlyPriceId;
      if (!priceId) {
        toast.error("Ce plan n'est pas encore disponible");
        return;
      }
      const res = await fetch("/api/stripe/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ priceId, planKey }),
      });
      const json = await res.json();
      if (json.url) {
        router.push(json.url);
      } else {
        toast.error(json.error ?? "Impossible de créer la session de paiement");
      }
    } catch {
      toast.error("Erreur lors de la redirection vers le paiement");
    } finally {
      setActionLoading(false);
    }
  };

  const handleManagePortal = async () => {
    setActionLoading(true);
    try {
      const res = await fetch("/api/stripe/portal", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ returnUrl: window.location.href }),
      });
      const json = await res.json();
      if (json.url) {
        router.push(json.url);
      } else {
        toast.error(json.error ?? "Impossible d'accéder au portail de gestion");
      }
    } catch {
      toast.error("Erreur lors de la redirection vers le portail");
    } finally {
      setActionLoading(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-24">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  const currentPlan = subscription?.plan ?? "FREE";
  const statusCfg = STATUS_CONFIG[subscription?.status ?? "ACTIVE"];
  const isExpiringSoon = subscription?.currentPeriodEnd &&
    new Date(subscription.currentPeriodEnd).getTime() - Date.now() < 7 * 24 * 3600 * 1000;

  return (
    <div className="space-y-8 max-w-5xl mx-auto">
      {/* En-tête */}
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Abonnement</h1>
        <p className="text-sm text-muted-foreground mt-0.5">
          Gérez votre plan et votre facturation
        </p>
      </div>

      {/* Statut actuel */}
      <Card className="bg-gradient-to-r from-primary/5 to-transparent border-primary/20">
        <CardContent className="py-5">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div className="flex items-center gap-4">
              {(() => {
                const ui = PLAN_UI[currentPlan];
                const Icon = ui.icon;
                return (
                  <div className={cn(
                    "h-12 w-12 rounded-xl flex items-center justify-center",
                    currentPlan === "FREE" ? "bg-slate-100 dark:bg-slate-800" :
                    currentPlan === "PRO" ? "bg-amber-100 dark:bg-amber-900/40" :
                    "bg-blue-100 dark:bg-blue-900/40"
                  )}>
                    <Icon className={cn("h-6 w-6", ui.iconClass)} />
                  </div>
                );
              })()}
              <div>
                <div className="flex items-center gap-2 flex-wrap">
                  <p className="font-semibold text-lg">{STRIPE_PLANS[currentPlan].name}</p>
                  <Badge variant={statusCfg.variant as any} className="text-xs">
                    {statusCfg.label}
                  </Badge>
                  {subscription?.cancelAtPeriodEnd && (
                    <Badge variant="destructive" className="text-xs gap-1">
                      <AlertTriangle className="h-3 w-3" />
                      Annulation prévue
                    </Badge>
                  )}
                </div>
                {subscription?.currentPeriodEnd && (
                  <p className="text-sm text-muted-foreground mt-0.5">
                    {subscription.cancelAtPeriodEnd ? "Se termine le" : "Renouvellement le"}{" "}
                    <span className="font-medium">{formatDate(subscription.currentPeriodEnd, "dd MMMM yyyy")}</span>
                  </p>
                )}
                {currentPlan === "FREE" && (
                  <p className="text-sm text-muted-foreground mt-0.5">
                    Plan gratuit — mettez à niveau pour débloquer toutes les fonctionnalités
                  </p>
                )}
              </div>
            </div>
            {subscription?.stripeCustomerId && (
              <Button
                variant="outline"
                size="sm"
                className="gap-1.5 shrink-0"
                onClick={handleManagePortal}
                disabled={actionLoading}
              >
                {actionLoading ? (
                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                ) : (
                  <ExternalLink className="h-3.5 w-3.5" />
                )}
                Gérer la facturation
              </Button>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Alerte expiration */}
      {isExpiringSoon && !subscription?.cancelAtPeriodEnd && (
        <Card className="border-amber-300 bg-amber-50 dark:bg-amber-900/10 dark:border-amber-700">
          <CardContent className="py-4">
            <div className="flex items-start gap-3">
              <AlertTriangle className="h-5 w-5 text-amber-600 shrink-0 mt-0.5" />
              <div>
                <p className="font-semibold text-amber-800 dark:text-amber-400 text-sm">
                  Abonnement expirant bientôt
                </p>
                <p className="text-sm text-amber-700 dark:text-amber-500 mt-0.5">
                  Votre abonnement expire le{" "}
                  {subscription?.currentPeriodEnd && formatDate(subscription.currentPeriodEnd, "dd MMMM yyyy")}.
                  Renouvelez-le pour éviter toute interruption de service.
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Plans */}
      <div>
        <h2 className="text-lg font-semibold mb-1">Choisissez votre plan</h2>
        <p className="text-sm text-muted-foreground mb-6">
          Tous les plans incluent une période d&apos;essai de 14 jours. Annulation à tout moment.
        </p>
        <div className="grid gap-6 md:grid-cols-3">
          {(Object.keys(STRIPE_PLANS) as PlanKey[]).map((planKey) => (
            <PlanCard
              key={planKey}
              planKey={planKey}
              plan={STRIPE_PLANS[planKey]}
              currentPlan={currentPlan}
              isLoading={actionLoading}
              onUpgrade={handleUpgrade}
              onManage={handleManagePortal}
              hasStripeCustomer={!!subscription?.stripeCustomerId}
            />
          ))}
        </div>
      </div>

      {/* FAQ rapide */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-base">Questions fréquentes</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {[
            {
              q: "Puis-je changer de plan à tout moment ?",
              a: "Oui, vous pouvez passer à un plan supérieur ou inférieur à tout moment. La différence est calculée au prorata."
            },
            {
              q: "Mes données sont-elles conservées si je rétrograde ?",
              a: "Vos données sont toujours conservées. Cependant, certaines fonctionnalités peuvent devenir inaccessibles selon le plan choisi."
            },
            {
              q: "Comment annuler mon abonnement ?",
              a: "Vous pouvez annuler depuis le portail de gestion Stripe. L'annulation prend effet à la fin de la période en cours."
            },
          ].map((item, i) => (
            <div key={i} className={cn("space-y-1", i > 0 && "pt-4 border-t")}>
              <p className="font-medium text-sm">{item.q}</p>
              <p className="text-sm text-muted-foreground">{item.a}</p>
            </div>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}
