import React, { useState, useEffect } from 'react';
import { motion } from 'motion/react';
import { Check, AlertCircle, ArrowRight, TrendingDown, TrendingUp } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import useSWR from 'swr';
import axios from 'axios';
import { postFetcher } from '../../lib/fetcher';
import { PLANS, type PlanConfig as Plan } from '../../config/plans';
import { SubscribeButton } from '../../components/SubscribeButton';

const planLevels: Record<string, number> = {
  'Starter': 0,
  'Professionnel': 1,
  'Entreprise': 2
};

/** Generate the invoice number string INV-YYYY-MM-DD */
function makeInvoiceNumber(): string {
  const d = new Date();
  return `INV-${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

export const Upgrades = () => {
  const { currentUser } = useAuth();
  const navigate = useNavigate();
  const [subscription, setSubscription] = useState<any>(null);
  const [selectedUpgradePlan, setSelectedUpgradePlan] = useState<Plan | null>(null);
  const [isProcessingUpgrade, setIsProcessingUpgrade] = useState(false);
  const [upgradeError, setUpgradeError] = useState<string | null>(null);

  const { data: services, mutate: mutateServices } = useSWR(
    currentUser ? ['/api/db/query', { collection: 'services', conditions: [{ field: 'userId', op: '==', value: currentUser.email }] }] : null,
    postFetcher
  );

  useEffect(() => {
    if (services && services.length > 0) {
      setSubscription(services[0]);
    }
  }, [services]);

  const isUpdatableStatus = subscription ? ['active', 'past_due'].includes(subscription.status) : false;

  const currentLevel = subscription?.plan && planLevels[subscription.plan] !== undefined && isUpdatableStatus
    ? planLevels[subscription.plan]
    : -1;

  const isSelectedUpgrade = selectedUpgradePlan
    ? (planLevels[selectedUpgradePlan.title] ?? 0) > currentLevel
    : false;

  // ── Shared: trigger email notification and redirect ───────────────────────
  const handleSuccess = async (planTitle: string) => {
    try {
      await axios.post('/api/notifications/plan-changed', { newPlanTitle: planTitle });
    } catch (e) {
      console.error("Failed to send plan changed notification:", e);
    }
    navigate('/client', { state: { message: "Votre abonnement a été mis à jour avec succès." } });
  };

  // ── Handle both Upgrade and Downgrade via Paddle API ───────────────────
  const handleChangePlan = async () => {
    if (!selectedUpgradePlan || !currentUser) return;
    setIsProcessingUpgrade(true);
    setUpgradeError(null);
    try {
      if (!subscription?.paddleSubscriptionId) {
        setUpgradeError('Aucun abonnement actif trouvé. Veuillez souscrire à un forfait depuis la page de tarification.');
        return;
      }

      // Only send priceId — server validates everything else
      await axios.post('/api/billing/upgrade', {
        priceId: selectedUpgradePlan.monthlyPriceId
      });

      mutateServices();
      await handleSuccess(selectedUpgradePlan.title);
    } catch (err: any) {
      console.error('Error changing plan:', err);
      setUpgradeError(err.response?.data?.error || 'Une erreur est survenue lors de la mise à jour de votre abonnement.');
    } finally {
      setIsProcessingUpgrade(false);
    }
  };

  // ─────────────────────────────────────────────────────────────────────────
  return (
    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} className="space-y-6">
      {/* Header banner */}
      <div className="bg-gradient-to-br from-blue-600 to-indigo-700 p-8 rounded-3xl text-white shadow-xl">
        <h2 className="text-2xl font-black mb-2">Gérer votre abonnement</h2>
        <p className="text-blue-100 font-medium max-w-2xl">
          Votre instance est actuellement en{' '}
          <strong>{subscription?.plan === 'Starter' ? 'version Démo / Starter' : `version ${subscription?.plan || 'Gratuite'}`}</strong>.{' '}
          Mettez à niveau ou adaptez votre forfait pour débloquer de nouvelles limites.
        </p>
      </div>

      {/* Plan grid — always shows all plans, current one highlighted */}
      {selectedUpgradePlan ? (
        <div className="bg-white dark:bg-slate-900 p-8 rounded-3xl border-2 border-blue-500 shadow-xl max-w-2xl mx-auto">
          <div className="flex items-center justify-center gap-3 mb-6">
            {isSelectedUpgrade
              ? <TrendingUp className="w-7 h-7 text-blue-600" />
              : <TrendingDown className="w-7 h-7 text-slate-400" />
            }
            <h3 className="text-2xl font-black text-slate-900 dark:text-white text-center">
              {isSelectedUpgrade
                ? `Passer au ${selectedUpgradePlan.title}`
                : `Déclasser vers ${selectedUpgradePlan.title}`}
            </h3>
          </div>

          <div className="mb-8 p-5 bg-slate-50 dark:bg-slate-800 rounded-2xl space-y-3">
            <p className="text-slate-600 dark:text-slate-300 text-sm leading-relaxed">
              {isSelectedUpgrade
                ? "Votre nouvelle formule entrera en vigueur immédiatement. Le montant complet du nouveau forfait sera facturé aujourd'hui."
                : "Le déclassement prendra effet à la fin de votre période de facturation actuelle. Vous conservez votre forfait actuel jusqu'à cette date."}
            </p>
            <div className="flex justify-between items-center font-black text-lg text-slate-900 dark:text-white pt-2 border-t border-slate-200 dark:border-slate-700">
              <span>Nouveau tarif</span>
              <span className="text-blue-600">{selectedUpgradePlan.monthlyPrice}<span className="text-sm font-medium text-slate-500"> / mois</span></span>
            </div>
          </div>

          {upgradeError && (
            <div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 rounded-2xl text-center text-sm font-bold border border-red-200 dark:border-red-900/50">
              <AlertCircle className="w-5 h-5 mx-auto mb-1" />
              <p>{upgradeError}</p>
            </div>
          )}

          <div className="relative">
            {isProcessingUpgrade && (
              <div className="absolute inset-0 bg-white/80 dark:bg-slate-900/80 z-10 flex flex-col items-center justify-center backdrop-blur-sm rounded-2xl">
                <div className="w-10 h-10 border-4 border-blue-600/30 border-t-blue-600 rounded-full animate-spin mb-3" />
                <p className="font-bold text-slate-700 dark:text-slate-300">Traitement en cours...</p>
              </div>
            )}

            {isSelectedUpgrade ? (
              selectedUpgradePlan.monthlyPriceId ? (
                subscription?.paddleSubscriptionId && isUpdatableStatus ? (
                  // Path A: existing Paddle subscription → use Paddle API to update
                  <button
                    onClick={handleChangePlan}
                    disabled={isProcessingUpgrade}
                    className="w-full py-4 rounded-2xl bg-blue-600 text-white font-bold hover:bg-blue-700 transition-all shadow-lg shadow-blue-600/20 flex items-center justify-center gap-2"
                  >
                    Confirmer la mise à niveau <ArrowRight className="w-4 h-4" />
                  </button>
                ) : (
                  // Path B: no subscription yet → open Paddle checkout overlay
                  <SubscribeButton
                    priceId={selectedUpgradePlan.monthlyPriceId}
                    customData={{ email: currentUser?.email?.toLowerCase() || '' }}
                    className="w-full py-4 rounded-2xl bg-blue-600 text-white font-bold hover:bg-blue-700 transition-all shadow-lg shadow-blue-600/20"
                    onSuccess={async (data) => {
                      setIsProcessingUpgrade(true);
                      setUpgradeError(null);
                      try {
                        if (subscription?.id) {
                          // Note: Webhook will handle this anyway, but SubscribeButton creates a new subscription checkout
                          // If there's no existing subscription, Paddle checkout creates one and triggers subscription.created
                          // We don't need manual DB updates here either since webhook handles subscription.created.
                        }
                        await handleSuccess(selectedUpgradePlan.title);
                      } catch (err: any) {
                        console.error('Error upgrading:', err);
                        setUpgradeError('Une erreur est survenue lors de la mise à jour de votre abonnement.');
                      } finally {
                        setIsProcessingUpgrade(false);
                      }
                    }}
                    onCancel={() => setIsProcessingUpgrade(false)}
                  >
                    Confirmer la mise à niveau
                  </SubscribeButton>
                )
              ) : (
                <div className="text-center p-4 bg-yellow-50 dark:bg-yellow-900/20 text-yellow-800 dark:text-yellow-300 rounded-xl border border-yellow-200 dark:border-yellow-900/50 text-sm font-bold">
                  Configuration de paiement manquante pour ce plan.
                </div>
              )
            ) : (
              // Downgrade path
              <button
                onClick={handleChangePlan}
                disabled={isProcessingUpgrade}
                className="w-full py-4 rounded-2xl bg-slate-700 dark:bg-slate-600 text-white font-bold hover:bg-slate-800 dark:hover:bg-slate-500 transition-all flex items-center justify-center gap-2"
              >
                Confirmer le déclassement <ArrowRight className="w-4 h-4" />
              </button>
            )}

            <div className="mt-4 text-center">
              <button
                onClick={() => setSelectedUpgradePlan(null)}
                disabled={isProcessingUpgrade}
                className="text-slate-400 hover:text-slate-700 dark:hover:text-slate-200 font-bold text-sm transition-colors"
              >
                ← Retour aux plans
              </button>
            </div>
          </div>
        </div>
      ) : (
        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {PLANS.map((plan: Plan) => {
            const isCurrent = plan.title === subscription?.plan && isUpdatableStatus;
            const isPlanUpgrade = (planLevels[plan.title] ?? 0) > currentLevel;

            if (isCurrent) {
              // ── Current plan card (non-interactive, highlighted) ──────────
              return (
                <div
                  key={plan.title}
                  className="relative bg-gradient-to-br from-blue-600 to-indigo-700 p-8 rounded-3xl border-2 border-blue-500 shadow-xl flex flex-col justify-between"
                >
                  {/* "Votre forfait actuel" badge */}
                  <div className="absolute -top-3.5 left-1/2 -translate-x-1/2 whitespace-nowrap">
                    <span className="inline-flex items-center gap-1.5 bg-green-500 text-white text-[10px] font-black px-3.5 py-1.5 rounded-full uppercase tracking-wider shadow-lg">
                      <Check className="w-3 h-3" /> Votre forfait actuel
                    </span>
                  </div>
                  <div>
                    <div className="flex justify-between items-start mb-3 mt-2">
                      <h3 className="text-2xl font-black text-white">{plan.title}</h3>
                    </div>
                    <p className="text-4xl font-black text-white mb-5">
                      {plan.monthlyPrice}
                      <span className="text-base text-blue-200 font-medium"> / mois</span>
                    </p>
                    <ul className="space-y-2.5 mb-8">
                      {(plan.features || []).filter((f: any) => f.included).slice(0, 4).map((feature: any, idx: number) => (
                        <li key={idx} className="flex items-center gap-3 text-sm">
                          <Check className="text-blue-200 w-4 h-4 flex-shrink-0" />
                          <span className="font-medium text-blue-100">{feature.text}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                  <div className="w-full py-3.5 rounded-2xl font-bold text-center bg-white/20 text-white border border-white/30 cursor-default select-none">
                    Abonnement actif
                  </div>
                </div>
              );
            }

            // ── Other plan card (clickable) ───────────────────────────────
            return (
              <div
                key={plan.title}
                className={`bg-white dark:bg-slate-900 p-8 rounded-3xl border-2 transition-all duration-200 flex flex-col justify-between group cursor-pointer hover:shadow-xl ${isPlanUpgrade
                    ? 'border-blue-200 dark:border-blue-800 hover:border-blue-500'
                    : 'border-slate-100 dark:border-slate-800 hover:border-slate-300 dark:hover:border-slate-600'
                  }`}
                onClick={() => setSelectedUpgradePlan(plan)}
              >
                <div>
                  <div className="flex justify-between items-start mb-3">
                    <h3 className="text-2xl font-black text-slate-900 dark:text-white">{plan.title}</h3>
                    {isPlanUpgrade ? (
                      <span className="inline-flex items-center gap-1 text-[10px] font-black px-2.5 py-1 rounded-full bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 uppercase tracking-wider">
                        <TrendingUp className="w-3 h-3" /> Upgrade
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1 text-[10px] font-black px-2.5 py-1 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-500 uppercase tracking-wider">
                        <TrendingDown className="w-3 h-3" /> Downgrade
                      </span>
                    )}
                  </div>
                  <p className="text-4xl font-black text-slate-900 dark:text-white mb-5">
                    {plan.monthlyPrice}
                    <span className="text-base text-slate-400 font-medium"> / mois</span>
                  </p>
                  <ul className="space-y-2.5 mb-8">
                    {(plan.features || []).filter((f: any) => f.included).slice(0, 4).map((feature: any, idx: number) => (
                      <li key={idx} className="flex items-center gap-3 text-sm">
                        <Check className="text-green-500 w-4 h-4 flex-shrink-0" />
                        <span className="font-medium text-slate-700 dark:text-slate-300">{feature.text}</span>
                      </li>
                    ))}
                  </ul>
                </div>
                <button
                  className={`w-full py-3.5 rounded-2xl font-bold transition-all group-hover:scale-[1.02] ${isPlanUpgrade
                      ? 'bg-blue-600 text-white shadow-md shadow-blue-500/20 hover:bg-blue-700'
                      : 'bg-slate-100 dark:bg-slate-800 text-slate-700 dark:text-slate-300 border border-slate-200 dark:border-slate-700'
                    }`}
                >
                  {isPlanUpgrade ? `Passer au ${plan.title}` : `Déclasser vers ${plan.title}`}
                </button>
              </div>
            );
          })}
        </div>
      )}
    </motion.div>
  );
};
