import { Button } from "@xtablo/ui/components/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@xtablo/ui/components/dialog";
import { AlertCircle, CheckCircle2, CreditCard, Loader2Icon, Sparkles } from "lucide-react";
import { useEffect, useState } from "react";
import { useOrganization } from "../hooks/organization";
import { useCreateCheckoutSession, useTrialExpiration } from "../hooks/stripe";
import { useMaybeUser } from "../providers/UserStoreProvider";

const MODAL_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes
const LAST_SHOWN_KEY = "trial-upsell-modal-last-shown";
const TRIAL_UPSELL_REMINDER_DAYS = 7;

export const shouldShowTrialUpsell = (input: {
  isTrialExpired: boolean;
  activeSubscriptionPlan: "solo" | "team" | "annual" | null;
  isTemporaryUser: boolean;
  daysRemaining: number | null;
}) => {
  const { isTrialExpired, activeSubscriptionPlan, isTemporaryUser, daysRemaining } = input;

  if (isTrialExpired || activeSubscriptionPlan || isTemporaryUser) {
    return false;
  }

  if (daysRemaining === null) {
    return false;
  }

  return daysRemaining > 0 && daysRemaining <= TRIAL_UPSELL_REMINDER_DAYS;
};

/**
 * Auto-opening modal that reminds users near trial expiration.
 */
export function TrialUpsellModal() {
  const [isOpen, setIsOpen] = useState(false);
  const { daysRemaining } = useTrialExpiration();
  const { data: organizationData } = useOrganization();
  const user = useMaybeUser();
  const { mutate: createCheckout, isPending: checkoutPending } = useCreateCheckoutSession();

  const shouldShowModal = Boolean(
    organizationData &&
      shouldShowTrialUpsell({
        isTrialExpired: organizationData.is_trial_expired,
        activeSubscriptionPlan: organizationData.active_subscription_plan,
        isTemporaryUser: Boolean(user?.is_temporary),
        daysRemaining,
      })
  );

  const requiredPlan = organizationData?.required_plan ?? "solo";
  const checkoutPlan = requiredPlan === "team" ? "team" : "solo";

  useEffect(() => {
    if (!shouldShowModal) return;

    const checkAndShowModal = () => {
      const lastShown = localStorage.getItem(LAST_SHOWN_KEY);
      const now = Date.now();

      if (!lastShown || now - Number.parseInt(lastShown, 10) >= MODAL_INTERVAL_MS) {
        setIsOpen(true);
        localStorage.setItem(LAST_SHOWN_KEY, now.toString());
      }
    };

    checkAndShowModal();

    const interval = setInterval(checkAndShowModal, MODAL_INTERVAL_MS);
    return () => clearInterval(interval);
  }, [shouldShowModal]);

  if (!shouldShowModal || daysRemaining === null) {
    return null;
  }

  const isUrgent = daysRemaining <= 3;

  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <div className="mx-auto w-12 h-12 bg-gradient-to-br from-purple-500 to-blue-500 rounded-full flex items-center justify-center mb-2">
            {isUrgent ? (
              <AlertCircle className="w-6 h-6 text-white" />
            ) : (
              <Sparkles className="w-6 h-6 text-white" />
            )}
          </div>
          <DialogTitle className="text-center">
            {isUrgent
              ? `Plus que ${daysRemaining} jour${daysRemaining > 1 ? "s" : ""} de période d'essai`
              : `${daysRemaining} jour${daysRemaining > 1 ? "s" : ""} restants dans votre période d'essai`}
          </DialogTitle>
          <DialogDescription className="text-center">
            {requiredPlan === "team"
              ? "Après l'essai, votre organisation passera sur Teams (facturation par siège)."
              : "Après l'essai, vous pourrez continuer avec Solo."}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-3 py-4">
          <p className="text-sm font-medium">
            {requiredPlan === "team"
              ? "Avec Teams, vous bénéficiez de :"
              : "Avec Solo, vous bénéficiez de :"}
          </p>
          <ul className="space-y-2">
            {(requiredPlan === "team"
              ? [
                  "Utilisateurs multiples (par siège)",
                  "Tablos illimités",
                  "Planification avancée",
                  "Chat en temps réel",
                  "Support prioritaire",
                ]
              : [
                  "1 utilisateur",
                  "10 tablos actifs",
                  "Planification avancée",
                  "Chat en temps réel",
                  "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>

        <DialogFooter className="flex flex-col sm:flex-row gap-2">
          <Button variant="outline" onClick={() => setIsOpen(false)} className="sm:flex-1">
            Plus tard
          </Button>
          <Button
            onClick={() => {
              createCheckout({
                plan: checkoutPlan,
                successUrl: `${window.location.origin}?upgraded=true`,
                cancelUrl: `${window.location.origin}?canceled=true`,
              });
              setIsOpen(false);
            }}
            disabled={checkoutPending}
            className="sm:flex-1 gap-2 bg-gradient-to-r from-purple-500 to-blue-500 hover:from-purple-600 hover:to-blue-600"
          >
            {checkoutPending ? (
              <>
                <Loader2Icon className="w-4 h-4 animate-spin" />
                Chargement...
              </>
            ) : (
              <>
                <CreditCard className="w-4 h-4" />
                Passer au plan {requiredPlan === "team" ? "Teams" : "Solo"}
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
