'use client';

import React, { useState, useEffect, Suspense } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { apiRequest } from '@/lib/api';
import { useAuth } from '@/context/auth-context';
import { CreditCard, Check, ShieldAlert, ArrowRight, ShieldCheck } from 'lucide-react';

function BillingPageContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const { user, updateUser } = useAuth();
  
  const [plan, setPlan] = useState('starter');
  const [cycle, setCycle] = useState<'monthly' | 'semi' | 'annual'>('annual');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [loadingTrial, setLoadingTrial] = useState(false);
  const [trialMessage, setTrialMessage] = useState<string | null>(null);
  
  const [selectedMethod, setSelectedMethod] = useState('EcoCash');
  const [subStatus, setSubStatus] = useState<any>(null);

  useEffect(() => {
    const qPlan = searchParams.get('plan');
    const qCycle = searchParams.get('cycle');
    const storedPlan = user?.selectedPlan || user?.subscriptionPlan || (typeof window !== 'undefined' ? localStorage.getItem('selectedPlan') : null);
    const storedCycle = typeof window !== 'undefined' ? localStorage.getItem('selectedBillingCycle') : null;

    if (qPlan) {
      setPlan(qPlan.toLowerCase());
    } else if (storedPlan) {
      setPlan(storedPlan.toLowerCase());
    }

    if (qCycle) {
      setCycle(qCycle.toLowerCase() as any);
    } else if (storedCycle) {
      setCycle(storedCycle.toLowerCase() as any);
    }

    // Fetch subscription status
    apiRequest('api/subscription/status')
      .then((data) => setSubStatus(data))
      .catch((err) => console.error('Failed to load subscription status:', err));
  }, [searchParams, user]);

  const planPricing: Record<string, { name: string; pricing: { monthly: number; semi: number; annual: number }; features: string[] }> = {
    starter: {
      name: 'Starter',
      pricing: { monthly: 29, semi: 24, annual: 19 },
      features: [
        '1 WhatsApp Business Account',
        'Up to 100 Deliveries per month',
        'Up to 500 Customers tracking',
        'EcoCash & Paynow Integration',
        'Meta Catalog Sync (up to 150 items)',
        'Standard Email Support',
      ],
    },
    professional: {
      name: 'Professional',
      pricing: { monthly: 69, semi: 55, annual: 45 },
      features: [
        '3 WhatsApp Business Accounts',
        'Up to 1,000 Deliveries per month',
        'Up to 5,000 Customers tracking',
        'WooCommerce Sync & Integration',
        'EcoCash, Paynow & Visa/Mastercard',
        '24/7 AI Sales & Support Automation',
        'Advanced Reporting & Analytics',
        'Multi-agent Inbox (up to 5 users)',
      ],
    },
    enterprise: {
      name: 'Enterprise',
      pricing: { monthly: 149, semi: 125, annual: 99 },
      features: [
        'Unlimited WhatsApp Accounts',
        'Unlimited Deliveries & Customers',
        'Custom Domain & API Access',
        'Dedicated AI Model Fine-tuning',
        'High-Throughput Webhook Event Pipeline',
        'Dedicated SLA Uptime Guarantee',
        'Multi-user Access (Unlimited)',
        '24/7 Priority Support',
      ],
    },
  };

  const selectedPlanConfig = planPricing[plan] || planPricing.starter;
  const rate = selectedPlanConfig.pricing[cycle] || selectedPlanConfig.pricing.annual;
  const months = cycle === 'monthly' ? 1 : cycle === 'semi' ? 6 : 12;
  const totalAmount = rate * months;

  const handlePay = async () => {
    setError(null);
    setSubmitting(true);
    try {
      const data = await apiRequest('api/subscription/initiate-payment', 'POST', {
        plan: plan,
        cycle: cycle,
      });

      if (data.success && data.paymentLink) {
        window.location.href = data.paymentLink; // Redirect to PesePay page
      } else {
        throw new Error('Failed to obtain payment checkout link.');
      }
    } catch (err: any) {
      setError(err.message || 'Payment initiation failed. Please try again.');
      setSubmitting(false);
    }
  };

  const handleActivateTrial = async () => {
    setError(null);
    setLoadingTrial(true);
    try {
      const data = await apiRequest('api/subscription/activate-trial', 'POST');
      if (data.success) {
        setTrialMessage('14-day free trial has been successfully activated!');
        // Refresh local user state
        if (user) {
          const updatedUser = { ...user, subscriptionStatus: 'TRIAL', subscriptionPlan: 'FREE_TRIAL', onboardingStep: 'ONBOARDING_COMPLETED' };
          updateUser(updatedUser);
        }
        setTimeout(() => {
          router.push('/dashboard');
        }, 1500);
      }
    } catch (err: any) {
      setError(err.message || 'Failed to activate trial.');
    } finally {
      setLoadingTrial(false);
    }
  };

  // Determine if eligible for free trial
  const isTrialEligible = (subStatus?.status === 'UNSUBSCRIBED' || user?.subscriptionStatus === 'UNSUBSCRIBED') && (!subStatus?.trialEnd && !user?.trialEnd);

  return (
    <div className="max-w-4xl mx-auto space-y-8 font-sans">
      
      {/* Expiry Banner warning */}
      {subStatus?.status === 'EXPIRED' && (
        <div className="bg-red-500/10 border border-red-500/30 rounded-2xl p-4 flex gap-3 text-red-500 text-sm font-medium">
          <ShieldAlert className="w-5 h-5 shrink-0 mt-0.5" />
          <div>
            <span className="font-bold">Subscription Expired:</span> Your store is currently in Read-Only mode. Customer orders, product modifications, and auto-sync features are paused. Please complete a payment to unlock premium access.
          </div>
        </div>
      )}

      {trialMessage && (
        <div className="bg-emerald-500/10 border border-emerald-500/30 rounded-2xl p-4 flex gap-3 text-emerald-500 text-sm font-medium">
          <ShieldCheck className="w-5 h-5 shrink-0 mt-0.5" />
          <div>
            <span className="font-bold">Success!</span> {trialMessage} Redirecting you to the dashboard...
          </div>
        </div>
      )}

      {error && (
        <div className="bg-red-500/10 border border-red-500/30 rounded-2xl p-4 flex gap-3 text-red-500 text-sm font-medium">
          <ShieldAlert className="w-5 h-5 shrink-0 mt-0.5" />
          <div>
            <span className="font-bold">Error:</span> {error}
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
        
        {/* Left column: Selected Plan Details */}
        <div className="lg:col-span-7 glass-panel bg-white dark:bg-[#0e0f14]/80 border border-slate-300 dark:border-white/5 rounded-3xl p-6 lg:p-8 space-y-6 shadow-sm">
          <div>
            <h2 className="text-xs uppercase tracking-widest text-emerald-700 dark:text-emerald-400 font-black mb-1">SELECTED PLAN</h2>
            <h1 className="text-3xl font-black text-slate-950 dark:text-white font-sans">{selectedPlanConfig.name} Plan</h1>
            <p className="text-xs text-slate-950 dark:text-gray-200 mt-1 font-bold">Billed {cycle}. Cancel or change plans anytime.</p>
          </div>

          <div className="space-y-3.5">
            <h3 className="text-xs uppercase tracking-wider text-slate-950 dark:text-gray-200 font-black">What&apos;s Included</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              {selectedPlanConfig.features.map((feat, index) => (
                <div key={index} className="flex items-center gap-2 text-xs text-slate-950 dark:text-white font-extrabold">
                  <Check className="w-4 h-4 text-emerald-600 dark:text-emerald-400 shrink-0 stroke-[3]" />
                  <span>{feat}</span>
                </div>
              ))}
            </div>
          </div>

          {isTrialEligible && (
            <div className="bg-slate-100 dark:bg-white/5 border border-slate-300 dark:border-white/10 rounded-2xl p-4 space-y-2">
              <h4 className="text-xs font-black text-slate-950 dark:text-white">Eligible for Free Trial</h4>
              <p className="text-xs text-slate-950 dark:text-gray-200 font-bold leading-relaxed">
                You can try our platform first! If you cancel or close the payment flow, your 14-day free trial will automatically activate.
              </p>
              <button 
                onClick={handleActivateTrial}
                disabled={loadingTrial}
                className="text-xs font-black text-emerald-700 dark:text-emerald-400 hover:text-emerald-800 dark:hover:text-emerald-300 flex items-center gap-1 cursor-pointer bg-transparent border-0 outline-none"
              >
                {loadingTrial ? 'Activating trial...' : 'Skip for now & start 14-day Free Trial'}
                <ArrowRight className="w-3.5 h-3.5 stroke-[3]" />
              </button>
            </div>
          )}
        </div>

        {/* Right column: Summary & PesePay payment */}
        <div className="lg:col-span-5 glass-panel bg-white dark:bg-[#0e0f14]/80 border border-slate-300 dark:border-white/5 rounded-3xl p-6 lg:p-8 space-y-6 shadow-sm">
          <h2 className="text-xs uppercase tracking-widest text-slate-950 dark:text-gray-200 font-black">BILLING SUMMARY</h2>
          
          <div className="space-y-4">
            <div className="flex justify-between items-center text-xs">
              <span className="text-slate-950 dark:text-gray-200 font-extrabold">{selectedPlanConfig.name} Subscription ({cycle})</span>
              <span className="font-black text-slate-950 dark:text-white font-mono">${rate.toFixed(2)}/mo</span>
            </div>
            
            <div className="flex justify-between items-center text-xs">
              <span className="text-slate-950 dark:text-gray-200 font-extrabold">Billing Period ({months} Months)</span>
              <span className="text-slate-950 dark:text-white font-mono font-black">{months} months</span>
            </div>

            <div className="border-t border-slate-300 dark:border-white/10 pt-4 flex justify-between items-center">
              <span className="text-base text-slate-950 dark:text-white font-black">Total Amount Due</span>
              <span className="text-3xl font-black text-emerald-600 dark:text-emerald-400 font-mono">${totalAmount.toFixed(2)}</span>
            </div>
          </div>

          <div className="space-y-1.5 pt-2">
            <h3 className="text-xs uppercase tracking-wider text-slate-950 dark:text-gray-200 font-black flex items-center gap-1.5">
              <CreditCard className="w-4 h-4 text-emerald-600 dark:text-emerald-400" /> Secure Checkout via PesePay
            </h3>
            <p className="text-xs text-slate-950 dark:text-gray-200 font-extrabold">
              Supports EcoCash, ZIPIT, Visa, Mastercard, InnBucks & Omari.
            </p>
          </div>

          <button
            onClick={handlePay}
            disabled={submitting}
            className="confirm-pay-btn w-full bg-[#008069] hover:bg-[#006e5a] text-[#efeae2] font-black text-sm uppercase tracking-wider py-4 rounded-xl transition-all shadow-md flex items-center justify-center gap-2 cursor-pointer disabled:opacity-50"
            style={{ backgroundColor: '#008069', color: '#efeae2' }}
          >
            {submitting ? (
              <>
                <div className="h-4 w-4 border-2 border-[#efeae2] border-t-transparent rounded-full animate-spin"></div>
                <span className="text-[#efeae2]" style={{ color: '#efeae2' }}>Initiating Checkout...</span>
              </>
            ) : (
              <>
                <span className="text-[#efeae2] font-black" style={{ color: '#efeae2' }}>Confirm & Pay Now</span>
                <ArrowRight className="w-4 h-4 stroke-[3] text-[#efeae2]" style={{ color: '#efeae2', stroke: '#efeae2' }} />
              </>
            )}
          </button>
        </div>

      </div>
    </div>
  );
}

export default function BillingPage() {
  return (
    <Suspense fallback={<div className="min-h-screen flex items-center justify-center bg-[#0d0f14] text-white">Loading Billing Details...</div>}>
      <BillingPageContent />
    </Suspense>
  );
}
