'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/context/auth-context';
import { Check, Sparkles, Zap } from 'lucide-react';

export default function PricingSection() {
  const [billingCycle, setBillingCycle] = useState<'monthly' | 'semi' | 'annual'>('annual');
  const { user } = useAuth();
  const router = useRouter();

  const handlePlanClick = (planName: string) => {
    const uppercasePlan = planName.toUpperCase();
    localStorage.setItem('selectedPlan', uppercasePlan);
    localStorage.setItem('selectedBillingCycle', billingCycle);

    const targetPlan = planName.toLowerCase();
    if (user) {
      router.push(`/dashboard/billing?plan=${targetPlan}&cycle=${billingCycle}`);
    } else {
      router.push(`/register?plan=${targetPlan}&cycle=${billingCycle}`);
    }
  };

  const plans = [
    {
      name: 'Starter',
      tagline: 'Ideal for solopreneurs & small businesses launching on WhatsApp.',
      monthlyPrice: 29,
      semiPrice: 24,
      annualPrice: 19,
      popular: false,
      features: [
        '1 WhatsApp Business Account',
        'Up to 100 Deliveries / month',
        'Up to 500 Customers tracking',
        'EcoCash & Paynow Payment Gateway Integration',
        'Meta Catalog Sync (up to 150 items)',
        'Standard Email Support',
      ],
      buttonText: 'Get Starter Plan',
    },
    {
      name: 'Professional',
      tagline: 'Recommended for growing merchants needing advanced integrations & automation.',
      monthlyPrice: 69,
      semiPrice: 55,
      annualPrice: 45,
      popular: true,
      badge: 'MOST POPULAR',
      features: [
        '3 WhatsApp Business Accounts',
        'Up to 1,000 Deliveries / 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)',
      ],
      buttonText: 'Start 14-Day Free Trial',
    },
    {
      name: 'Enterprise',
      tagline: 'Built for high-volume brands requiring custom SLAs, webhooks & limits.',
      monthlyPrice: 149,
      semiPrice: 125,
      annualPrice: 99,
      popular: false,
      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',
      ],
      buttonText: 'Contact Sales Team',
    },
  ];

  const getPrice = (plan: typeof plans[0]) => {
    if (billingCycle === 'monthly') return plan.monthlyPrice;
    if (billingCycle === 'semi') return plan.semiPrice;
    return plan.annualPrice;
  };

  const getBillingNote = (plan: typeof plans[0]) => {
    if (billingCycle === 'monthly') return 'Billed monthly';
    if (billingCycle === 'semi') return `$${plan.semiPrice * 6} billed semi-annually`;
    return `$${plan.annualPrice * 12} billed annually`;
  };

  return (
    <section id="pricing" className="bg-[#FAF9F6] py-20 lg:py-28 border-b border-slate-200/60 font-sans">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        
        {/* Section Header */}
        <div className="text-center max-w-3xl mx-auto mb-14 space-y-3">

          <h2 className="text-3xl sm:text-5xl font-black text-slate-900 tracking-tight">
            Choose the Right Plan for Your Store
          </h2>
          <p className="text-slate-600 text-sm sm:text-base">
            Every plan starts with a 14-day free trial. No credit card required.
          </p>

          {/* Billing Cycle Switcher */}
          <div className="pt-4 flex justify-center">
            <div className="inline-flex items-center bg-white p-1.5 sm:p-2 rounded-full border border-slate-200/90 shadow-sm gap-1 max-w-full">
              <button
                onClick={() => setBillingCycle('monthly')}
                className={`px-3.5 sm:px-5 py-2 text-xs sm:text-sm font-extrabold rounded-full transition-all whitespace-nowrap ${
                  billingCycle === 'monthly'
                    ? 'bg-slate-900 !text-white shadow-sm'
                    : 'text-slate-600 hover:text-slate-900'
                }`}
                style={{ color: billingCycle === 'monthly' ? '#ffffff' : '#475569' }}
              >
                <span style={{ color: billingCycle === 'monthly' ? '#ffffff' : '#475569' }}>Monthly</span>
              </button>
              <button
                onClick={() => setBillingCycle('semi')}
                className={`px-3.5 sm:px-5 py-2 text-xs sm:text-sm font-extrabold rounded-full transition-all flex items-center gap-1.5 whitespace-nowrap ${
                  billingCycle === 'semi'
                    ? 'bg-slate-900 !text-white shadow-sm'
                    : 'text-slate-600 hover:text-slate-900'
                }`}
                style={{ color: billingCycle === 'semi' ? '#ffffff' : '#475569' }}
              >
                <span style={{ color: billingCycle === 'semi' ? '#ffffff' : '#475569' }}>Semi-Annual</span>
                <span 
                  className="text-[10px] sm:text-[11px] font-black px-2 py-0.5 rounded-full"
                  style={{ backgroundColor: '#d1fae5', color: '#065f46' }}
                >
                  15% OFF
                </span>
              </button>
              <button
                onClick={() => setBillingCycle('annual')}
                className={`px-3.5 sm:px-5 py-2 text-xs sm:text-sm font-extrabold rounded-full transition-all flex items-center gap-1.5 whitespace-nowrap ${
                  billingCycle === 'annual'
                    ? 'bg-[#008069] !text-white shadow-sm'
                    : 'text-slate-600 hover:text-slate-900'
                }`}
                style={{ color: billingCycle === 'annual' ? '#ffffff' : '#475569' }}
              >
                <span style={{ color: billingCycle === 'annual' ? '#ffffff' : '#475569' }}>Annual</span>
                <span 
                  className="text-[10px] sm:text-[11px] font-black px-2 py-0.5 rounded-full"
                  style={{ backgroundColor: '#a7f3d0', color: '#022c22' }}
                >
                  SAVE 35%
                </span>
              </button>
            </div>
          </div>
        </div>

        {/* Pricing Cards Grid */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-8 items-stretch max-w-6xl mx-auto">
          {plans.map((plan, idx) => {
            const price = getPrice(plan);
            return (
              <div 
                key={idx}
                className={`rounded-3xl p-8 flex flex-col justify-between relative transition-all duration-300 ${
                  plan.popular 
                    ? 'bg-slate-900 text-white border-2 border-emerald-500 shadow-2xl shadow-slate-900/20 md:-translate-y-3' 
                    : 'bg-white text-slate-900 border border-slate-200/90 shadow-sm hover:shadow-md'
                }`}
              >
                {/* Popular Badge */}
                {plan.badge && (
                  <div className="absolute -top-4 left-1/2 -translate-x-1/2 bg-gradient-to-r from-emerald-500 to-teal-500 text-white font-black text-[10px] uppercase tracking-widest px-5 py-1.5 rounded-full shadow-md flex items-center gap-1">
                    <span>{plan.badge}</span>
                  </div>
                )}

                <div>
                  {/* Card Title */}
                  <h3 
                    className="font-black text-2xl tracking-tight mb-2"
                    style={{ color: plan.popular ? '#ffffff' : '#0f172a' }}
                  >
                    <span className="font-black" style={{ color: plan.popular ? '#ffffff' : '#0f172a' }}>
                      {plan.name}
                    </span>
                  </h3>

                  {/* Tagline */}
                  <p 
                    className="text-xs mb-6 leading-relaxed"
                    style={{ color: plan.popular ? '#cbd5e1' : '#64748b' }}
                  >
                    {plan.tagline}
                  </p>

                  {/* Pricing Display */}
                  <div className="mb-6 pb-6 border-b border-slate-200/20">
                    <div className="flex items-baseline gap-1">
                      <span 
                        className="text-4xl sm:text-5xl font-black font-sans tracking-tight"
                        style={{ color: plan.popular ? '#ffffff' : '#0f172a' }}
                      >
                        ${price}
                      </span>
                      <span 
                        className="text-xs font-semibold"
                        style={{ color: plan.popular ? '#94a3b8' : '#64748b' }}
                      >
                        / month
                      </span>
                    </div>
                    <p 
                      className="text-xs mt-1.5 font-bold"
                      style={{ color: plan.popular ? '#34d399' : '#64748b' }}
                    >
                      {getBillingNote(plan)}
                    </p>
                  </div>

                  {/* Features List */}
                  <div className="space-y-3 mb-8">
                    <p 
                      className="text-[11px] font-black uppercase tracking-wider"
                      style={{ color: plan.popular ? '#34d399' : '#94a3b8' }}
                    >
                      What&apos;s included:
                    </p>
                    {plan.features.map((feat, fIdx) => (
                      <div key={fIdx} className="flex items-start gap-2.5 text-xs font-medium">
                        <div className={`w-4 h-4 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5 ${
                          plan.popular ? 'bg-emerald-500/20 text-emerald-400' : 'bg-emerald-100 text-emerald-700'
                        }`}>
                          <Check className="w-3 h-3 stroke-[3]" />
                        </div>
                        <span style={{ color: plan.popular ? '#e2e8f0' : '#334155' }}>
                          {feat}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>

                {/* CTA Button */}
                <div>
                  <button
                    onClick={() => handlePlanClick(plan.name)}
                    className={`w-full block text-center font-black text-xs uppercase tracking-wider py-4 rounded-xl transition-all shadow-md cursor-pointer ${
                      plan.popular
                        ? 'bg-emerald-500 hover:bg-emerald-400 !text-slate-950 shadow-emerald-500/20'
                        : 'bg-slate-900 hover:bg-slate-800 !text-white'
                    }`}
                    style={{ color: plan.popular ? '#020617' : '#ffffff' }}
                  >
                    <span 
                      className="font-black"
                      style={{ color: plan.popular ? '#020617' : '#ffffff' }}
                    >
                      {plan.buttonText}
                    </span>
                  </button>
                </div>

              </div>
            );
          })}
        </div>

      </div>
    </section>
  );
}
