import { Button } from "@xtablo/ui/components/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@xtablo/ui/components/card";
import { Text } from "@xtablo/ui/components/typography";
import { AlertCircle, CheckCircle2, CreditCard, Loader2Icon, Sparkles } from "lucide-react";
import { useUpgradeBlock } from "../contexts/UpgradeBlockContext";
import { useLogout } from "../hooks/auth";
import { useOrganization } from "../hooks/organization";
import { useCreateCheckoutSession } from "../hooks/stripe";

/**
 * Blocking upgrade panel that appears when users are past their trial period
 * Prevents access to the app until they upgrade to a paid plan
 */
export function UpgradePanel() {
  const { isBlocked } = useUpgradeBlock();
  const { mutate: createCheckout, isPending: checkoutPending } = useCreateCheckoutSession();
  const { mutate: signOut } = useLogout();
  const { data: organizationData } = useOrganization();

  if (!isBlocked) {
    return null;
  }

  const requiredPlan = organizationData?.required_plan ?? "solo";
  const isBillingOwner = organizationData?.is_billing_owner ?? false;
  const requiredTeamQuantity = organizationData?.required_team_quantity ?? 1;
  const checkoutPlan = requiredPlan === "team" ? "team" : "solo";

  const checkoutLabel =
    checkoutPlan === "team"
      ? `Passer au plan Teams (${requiredTeamQuantity} siège${requiredTeamQuantity > 1 ? "s" : ""})`
      : "Passer au plan Solo";

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/95 backdrop-blur-sm">
      <div className="w-full max-w-lg mx-4">
        <Card className="shadow-2xl border-2">
          <CardHeader className="text-center space-y-2">
            <div className="mx-auto w-16 h-16 bg-gradient-to-br from-purple-500 to-blue-500 rounded-full flex items-center justify-center mb-2">
              <Sparkles className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl">Votre période d'essai est terminée</CardTitle>
            <CardDescription className="text-base">
              Pour continuer à utiliser XTablo, activez votre abonnement{" "}
              {requiredPlan === "team" ? "Teams" : "Solo"}.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-3">
              <Text className="text-sm font-medium">
                {requiredPlan === "team"
                  ? "Ce que vous obtenez avec Teams :"
                  : "Ce que vous obtenez avec Solo :"}
              </Text>
              <ul className="space-y-2">
                {(requiredPlan === "team"
                  ? [
                      "Utilisateurs multiples (facturation par siège)",
                      "Tablos illimités",
                      "Chat en temps réel",
                      "Stockage de fichiers",
                      "Support prioritaire",
                    ]
                  : [
                      "1 utilisateur",
                      "10 tablos actifs",
                      "Chat en temps réel",
                      "Stockage de fichiers",
                      "Support prioritaire",
                    ]
                ).map((feature) => (
                  <li key={feature} className="flex items-center gap-2 text-sm">
                    <CheckCircle2 className="w-4 h-4 text-green-600 dark:text-green-400 shrink-0" />
                    <span>{feature}</span>
                  </li>
                ))}
              </ul>
            </div>

            <div className="space-y-3">
              <Button
                onClick={() =>
                  createCheckout({
                    plan: checkoutPlan,
                    successUrl: `${window.location.origin}?upgraded=true`,
                    cancelUrl: `${window.location.origin}?canceled=true`,
                  })
                }
                disabled={checkoutPending || !isBillingOwner}
                className="w-full gap-2 bg-gradient-to-r from-purple-500 to-blue-500 hover:from-purple-600 hover:to-blue-600 h-12 text-base"
              >
                {checkoutPending ? (
                  <>
                    <Loader2Icon className="w-5 h-5 animate-spin" />
                    Chargement...
                  </>
                ) : (
                  <>
                    <CreditCard className="w-5 h-5" />
                    {checkoutLabel}
                  </>
                )}
              </Button>

              <Button
                variant="outline"
                onClick={() =>
                  createCheckout({
                    plan: "founder",
                    successUrl: `${window.location.origin}?upgraded=true`,
                    cancelUrl: `${window.location.origin}?canceled=true`,
                  })
                }
                disabled={checkoutPending || !isBillingOwner}
                className="w-full"
              >
                Devenir Founder (99€/an)
              </Button>

              {!isBillingOwner && (
                <div className="flex items-center gap-2 p-3 bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-800 rounded-lg">
                  <AlertCircle className="w-4 h-4 text-red-600 dark:text-red-400 shrink-0" />
                  <Text className="text-xs text-red-600 dark:text-red-400">
                    Seul le propriétaire de facturation de l'organisation peut modifier
                    l'abonnement.
                  </Text>
                </div>
              )}
            </div>

            <div className="text-center pt-2 border-t">
              <Text className="text-xs text-muted-foreground">
                Des questions ?{" "}
                <a
                  href="mailto:support@xtablo.com"
                  className="text-primary hover:underline font-medium"
                >
                  Contactez-nous
                </a>
                {" | "}
                <a
                  onClick={() => signOut()}
                  className="text-primary hover:underline cursor-pointer font-medium"
                >
                  Se déconnecter
                </a>
              </Text>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
