import React, { useState, useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { motion } from 'motion/react';
import { CheckCircle2, ArrowRight, ArrowLeft, Sparkles, AlertCircle } from 'lucide-react';
import { CompanyForm } from '../components/checkout/CompanyForm';
import { OrderSummary } from '../components/checkout/OrderSummary';
import axios from 'axios';
import { useAuth } from '../contexts/AuthContext';
import { PLANS, calcPricing } from '../config/plans';
import { SubscribeButton } from '../components/SubscribeButton';

export const Checkout = () => {
  const [searchParams] = useSearchParams();
  const planTitle = searchParams.get('plan');
  const annualParam = searchParams.get('annual') === 'true';
  const navigate = useNavigate();
  const { currentUser, userProfile, loading } = useAuth();
  const selectedPlan = PLANS.find(p => p.title === planTitle);

  const urlStep = parseInt(searchParams.get('step') || '1', 10);
  const initialStep = (urlStep === 2) ? 2 : 1;
  const [step, setStep] = useState(initialStep);
  const [formData, setFormData] = useState({ 
    companyName: '', 
    addressLine1: '',
    addressLine2: '',
    city: '',
    state: '',
    postcode: '',
    country: '',
    billingSameAsCompany: true,
    billingAddressLine1: '',
    billingAddressLine2: '',
    billingCity: '',
    billingState: '',
    billingPostcode: '',
    billingCountry: '',
  });
  
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isAnnual, setIsAnnual] = useState(annualParam);
  const [isPaymentLoading, setIsPaymentLoading] = useState(false);

  // Guard: plan must exist
  useEffect(() => {
    if (!selectedPlan) {
      navigate('/tarifs');
    }
  }, [selectedPlan, navigate]);

  // Guard: user must be logged in
  useEffect(() => {
    if (!loading && !currentUser) {
      navigate(`/register?redirect=${encodeURIComponent(`/checkout?plan=${planTitle || ''}&annual=${annualParam}`)}`);
    }
  }, [loading, currentUser, navigate, planTitle, annualParam]);

  // Sync step to URL
  useEffect(() => {
    if (urlStep !== step) {
      navigate(`/checkout?step=${step}&plan=${encodeURIComponent(planTitle || '')}&annual=${annualParam}`, { replace: true });
    }
  }, [step, urlStep, navigate, planTitle, annualParam]);

  // Guard: already a paying customer
  useEffect(() => {
    if (!loading && userProfile && userProfile.plan && userProfile.plan !== 'Gratuit') {
      navigate('/client', { state: { message: "Vous êtes déjà client. Vous pouvez gérer ou mettre à niveau votre abonnement ici." } });
    }
  }, [loading, userProfile, navigate]);

  if (!selectedPlan) return null;

  const isCustomPlan = selectedPlan.monthlyPrice === "Sur Mesure";
  const { subtotal, discount, total: totalDue, priceId: activePriceId } = calcPricing(selectedPlan, isAnnual);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const target = e.target as HTMLInputElement;
    const { name, value, type, checked } = target;
    const finalValue = type === 'checkbox' ? checked : value;
    
    setFormData(prev => ({ ...prev, [name]: finalValue }));
    if (errors[name]) {
      setErrors(prev => {
        const next = { ...prev };
        delete next[name];
        return next;
      });
    }
  };

  const validateStep1 = () => {
    const newErrors: Record<string, string> = {};
    if (!formData.companyName.trim()) newErrors.companyName = "Requis";
    if (!formData.addressLine1.trim()) newErrors.addressLine1 = "Requis";
    if (!formData.city.trim()) newErrors.city = "Requis";
    if (!formData.country.trim()) newErrors.country = "Requis";

    if (!formData.billingSameAsCompany) {
      if (!formData.billingAddressLine1.trim()) newErrors.billingAddressLine1 = "Requis";
      if (!formData.billingCity.trim()) newErrors.billingCity = "Requis";
      if (!formData.billingCountry.trim()) newErrors.billingCountry = "Requis";
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const nextStep = () => {
    if (step === 1 && !validateStep1()) return;
    setStep(prev => prev + 1);
    window.scrollTo(0, 0);
  };

  const prevStep = () => {
    setStep(prev => prev - 1);
    window.scrollTo(0, 0);
  };

  const submitCustomPlan = async () => {
    if (!validateStep1()) return;
    setIsSubmitting(true);
    try {
      if (!currentUser) throw new Error("Vous devez être connecté.");

      await axios.post('/api/db', {
        collection: 'demo_requests',
        data: {
          firstName: userProfile?.firstName || '',
          lastName: userProfile?.lastName || '',
          email: currentUser.email,
          plan: selectedPlan.title,
          userId: currentUser.email, // use email as consistent key
          status: 'pending',
          createdAt: new Date().toISOString()
        }
      });
      
      import('react-ga4').then(ReactGA => {
        if (ReactGA.default.isInitialized) {
          ReactGA.default.event({
            category: 'Checkout',
            action: 'Complete Demo Request',
            label: selectedPlan.title
          });
        }
      });
      
      setIsSubmitted(true);
      setIsSubmitting(false);
    } catch (err: any) {
      console.error('Erreur:', err);
      setErrors({ submit: "Une erreur est survenue. Veuillez réessayer." });
      setIsSubmitting(false);
    }
  };

  // ── Success Screen ────────────────────────────────────────────────────────
  if (isSubmitted) {
    return (
      <div className="pt-32 pb-20 min-h-screen bg-slate-50 dark:bg-slate-950 flex flex-col items-center justify-center p-4">
        <motion.div 
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ type: 'spring', stiffness: 200, damping: 20 }}
          className="max-w-xl w-full p-12 bg-white dark:bg-slate-900 rounded-[3rem] border border-slate-100 dark:border-slate-800 text-center shadow-2xl"
        >
          <motion.div
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            transition={{ delay: 0.2, type: 'spring', stiffness: 260, damping: 20 }}
            className="w-24 h-24 bg-green-50 dark:bg-green-900/20 rounded-full flex items-center justify-center mx-auto mb-6"
          >
            <CheckCircle2 className="text-green-500 dark:text-green-400 w-12 h-12" />
          </motion.div>
          <h3 className="text-3xl font-black text-slate-900 dark:text-white mb-3">
            {isCustomPlan ? "Demande Bien Reçue !" : "Paiement Réussi !"}
          </h3>
          <p className="text-lg text-slate-500 dark:text-slate-400 font-medium leading-relaxed mb-8">
            {isCustomPlan
              ? "Un expert Agendivo vous contactera sous 24h pour configurer votre espace."
              : "Bienvenue à bord ! Votre compte est activé et prêt à l'emploi."}
          </p>
          <button 
            onClick={() => navigate('/client', { replace: true })}
            className="px-8 py-4 bg-blue-600 text-white rounded-2xl font-bold hover:bg-blue-700 transition-colors w-full flex items-center justify-center gap-2 text-lg shadow-lg shadow-blue-500/20"
          >
            Accéder à mon espace <ArrowRight className="w-5 h-5" />
          </button>
        </motion.div>
      </div>
    );
  }

  // ── Main Checkout Flow ────────────────────────────────────────────────────
  return (
    <div className="pt-32 pb-20 min-h-screen bg-slate-50 dark:bg-slate-950 px-4 sm:px-6">
      <div className="max-w-4xl mx-auto">
        {/* Step indicator */}
        <div className="mb-8">
          <div className="flex items-center gap-2 text-sm font-bold text-slate-500 mb-8 overflow-hidden rounded-full bg-white dark:bg-slate-900 border border-slate-100 dark:border-slate-800 p-2 shadow-sm">
            {[1, 2].map((s) => (
               <div
                 key={s}
                 className={`flex-1 flex items-center justify-center py-2.5 px-4 rounded-full transition-all duration-300 ${
                   step === s
                     ? 'bg-blue-600 text-white shadow-md'
                     : step > s
                     ? 'bg-blue-50 dark:bg-slate-800 text-blue-600 dark:text-blue-400 cursor-pointer hover:bg-blue-100 dark:hover:bg-slate-700'
                     : 'text-slate-400'
                 }`}
                 onClick={() => step > s && setStep(s)}
               >
                 <span className="inline-flex items-center gap-2">
                   {step > s
                     ? <CheckCircle2 className="w-4 h-4" />
                     : <span className="w-5 h-5 rounded-full border-2 border-current flex items-center justify-center text-xs">{s}</span>
                   }
                   {s === 1 && "Entreprise"}
                   {s === 2 && "Paiement"}
                 </span>
               </div>
            ))}
          </div>
        </div>

        <motion.div 
          key={step}
          initial={{ opacity: 0, x: 20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.25 }}
          className="bg-white dark:bg-slate-900 rounded-[3rem] border border-slate-100 dark:border-slate-800 shadow-2xl p-8 lg:p-12"
        >
          {/* Step 1: Company Details */}
          {step === 1 && (
            <CompanyForm 
              formData={formData} 
              handleChange={handleChange} 
              errors={errors} 
              prevStep={() => navigate('/tarifs')} 
              nextStep={nextStep} 
            />
          )}

          {/* Step 2: Payment */}
          {step === 2 && (
            <div className="space-y-8">
              <div className="text-center mb-8">
                <h2 className="text-3xl font-black text-slate-900 dark:text-white">Paiement sécurisé</h2>
                <p className="text-slate-500 mt-2 font-medium">Dernière étape pour finaliser votre commande</p>
              </div>
              
              <div className="grid md:grid-cols-2 gap-12">
                {/* Payment Section */}
                <div className="order-2 md:order-1 border-t md:border-t-0 pt-8 md:pt-0 border-slate-100 dark:border-slate-800 md:border-r md:pr-12">
                  <h3 className="text-xl font-bold mb-6 text-slate-800 dark:text-slate-200">Réglez de façon sécurisée</h3>
                  
                  {isCustomPlan ? (
                    // Custom plan — no payment, just send request
                    <div className="text-center p-8 bg-blue-50 dark:bg-blue-900/20 rounded-2xl border border-blue-100 dark:border-blue-800">
                      <Sparkles className="w-10 h-10 text-blue-600 mx-auto mb-4" />
                      <p className="text-slate-700 dark:text-slate-300 font-medium mb-6">
                        Ce pack nécessite une validation par nos experts. Envoyez votre demande sans paiement.
                      </p>
                      <button 
                        onClick={submitCustomPlan}
                        disabled={isSubmitting}
                        className="w-full py-4 bg-blue-600 text-white rounded-2xl font-black shadow-lg hover:bg-blue-700 transition-colors flex justify-center items-center gap-2"
                      >
                        {isSubmitting
                          ? <><div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" /> Envoi en cours...</>
                          : 'Envoyer la demande'
                        }
                      </button>
                    </div>
                  ) : (
                    // Standard paid plan
                    <div className="min-h-[200px] relative">
                      {isPaymentLoading && (
                        <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-4" />
                          <p className="font-bold text-slate-700 dark:text-slate-300">Finalisation de la commande...</p>
                        </div>
                      )}
                      <SubscribeButton
                        priceId={activePriceId || ''}
                        disabled={isPaymentLoading}
                        customData={{ email: currentUser?.email?.toLowerCase() || '' }}
                        className="w-full py-5 bg-blue-600 text-white rounded-2xl font-black text-xl hover:bg-blue-700 transition-all shadow-xl shadow-blue-500/20 hover:-translate-y-1"
                        onSuccess={async (data) => {
                          setIsPaymentLoading(true);
                          setErrors({});
                          try {
                            // Use email as the consistent user key (DB PK)
                            const userEmail = currentUser?.email;
                            if (!userEmail) {
                              throw new Error("Erreur d'identification utilisateur. Vous devez être connecté.");
                            }

                            // 1. Update user profile with company details + plan
                            await axios.patch('/api/db', {
                              collection: 'users',
                              id: userEmail,
                              data: {
                                ...formData,
                                plan: selectedPlan.title,
                                isAnnual,
                                status: 'active',
                              }
                            });

                            // 2. Create Invoice (now persists plan, paymentMethod, transactionId)
                            const invoiceDate = new Date();
                            const invoiceNum = 'INV-'
                              + invoiceDate.getFullYear() + '-'
                              + String(invoiceDate.getMonth() + 1).padStart(2, '0') + '-'
                              + String(invoiceDate.getDate()).padStart(2, '0');

                            await axios.post('/api/db', {
                              collection: 'invoices',
                              data: {
                                number: invoiceNum,
                                paymentMethod: 'paddle_subscription',
                                plan: selectedPlan.title,
                                amount: String(totalDue.toFixed(2)),
                                status: 'Payée',
                                transactionId: String(data.transaction_id || data.id || ''),
                                userId: userEmail,
                                date: new Date().toISOString(),
                              }
                            });

                            // 3. Create Service document using plan's canonical service defaults
                            const serviceDefaults = selectedPlan.serviceDefaults;
                            await axios.post('/api/db', {
                              collection: 'services',
                              data: {
                                userId: userEmail,
                                instance_link: '',
                                plan: selectedPlan.title,
                                status: 'pending',
                                ...serviceDefaults,
                              }
                            });

                            // 4. Analytics
                            import('react-ga4').then(ReactGA => {
                              if (ReactGA.default.isInitialized) {
                                ReactGA.default.event({
                                  category: 'Checkout',
                                  action: 'Complete Payment',
                                  label: selectedPlan.title,
                                  value: Number(totalDue.toFixed(2))
                                });
                              }
                            });

                            // 5. Trigger plan-changed email notification (non-blocking)
                            try {
                              await axios.post('/api/notifications/plan-changed', { newPlanTitle: selectedPlan.title });
                            } catch (e) {
                              console.error("Failed to send plan changed notification:", e);
                            }

                            // 6. Show success screen
                            setIsPaymentLoading(false);
                            setIsSubmitted(true);
                          } catch (err: any) {
                            console.error("Critical error during checkout finalization:", err);
                            setIsPaymentLoading(false);
                            setErrors({ submit: `Erreur lors de la finalisation: ${err.message || 'Veuillez réessayer.'}` });
                          }
                        }}
                        onCancel={() => setIsPaymentLoading(false)}
                      >
                        Payer et Activer mon Compte
                      </SubscribeButton>

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

                  {/* Trust badges */}
                  <div className="mt-6 flex items-center justify-center gap-4 text-xs text-slate-400 font-medium">
                    <span>🔒 Paiement sécurisé SSL</span>
                    <span>•</span>
                    <span>Propulsé par Paddle</span>
                  </div>
                </div>

                {/* Order Summary */}
                <OrderSummary 
                  selectedPlan={selectedPlan}
                  isCustomPlan={isCustomPlan}
                  isAnnual={isAnnual}
                  setIsAnnual={setIsAnnual}
                  subtotal={subtotal}
                  discount={discount}
                  totalDue={totalDue}
                />
              </div>

              <div className="pt-6 border-t border-slate-100 dark:border-slate-800 flex justify-start">
                <button onClick={prevStep} className="px-6 py-3 font-bold text-slate-500 hover:text-slate-800 dark:hover:text-white transition-colors flex items-center gap-2">
                  <ArrowLeft className="w-4 h-4" /> Retour
                </button>
              </div>
            </div>
          )}

        </motion.div>
      </div>
    </div>
  );
};
