'use client'

import { Card, CardHeader, CardContent, CardTitle, CardDescription, CardFooter } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import {
    Check, Loader2, Globe, Database, Cpu, HardDrive, Server, Wifi, Cloud, Shield, Lock, Mail,
    Clock, RefreshCw, Headphones, Star, Gauge, Rocket, Zap, Settings, Users, FileText,
    Activity, Award, DollarSign, ShieldCheck, Boxes, ChevronRight, Sparkles, Building2,
    Code2, Layers, ExternalLink, type LucideIcon
} from 'lucide-react'
import { useCurrency } from '@/context/currency-context'
import { SectionWrapper } from '@/components/shared/section-wrapper'
import { useScrollAnimation, fadeInUpClass, staggerDelay } from '@/hooks/use-scroll-animation'
import { usePricing } from '@/hooks/use-pricing'
import type { AppProduct } from '@/lib/whmcs/types'
import type { SectionStyles } from '@/lib/home-config'

/* ----------------------------------------------------------------
 *  Static PlanCard (used by both static pages and WHMCS-powered)
 * ---------------------------------------------------------------- */

/* ─── Feature icon mapping (shared with admin editor) ─── */
const FEATURE_ICON_MAP: Record<string, LucideIcon> = {
    'check': Check, 'globe': Globe, 'database': Database, 'cpu': Cpu, 'hard-drive': HardDrive,
    'server': Server, 'wifi': Wifi, 'cloud': Cloud, 'shield': Shield, 'lock': Lock, 'mail': Mail,
    'clock': Clock, 'refresh-cw': RefreshCw, 'headphones': Headphones, 'star': Star, 'gauge': Gauge,
    'rocket': Rocket, 'zap': Zap, 'settings': Settings, 'users': Users, 'file-text': FileText,
    'activity': Activity, 'award': Award, 'dollar-sign': DollarSign, 'shield-check': ShieldCheck,
    'boxes': Boxes, 'chevron-right': ChevronRight, 'sparkles': Sparkles, 'building-2': Building2,
    'code-2': Code2, 'layers': Layers, 'external-link': ExternalLink,
}

type PlanFeature = string | { text: string; icon: string }

function normalizeFeature(f: PlanFeature): { text: string; icon: string } {
    if (typeof f === 'string') return { text: f, icon: 'check' }
    return { text: f.text, icon: f.icon || 'check' }
}

function getFeatureIcon(name: string): LucideIcon {
    return FEATURE_ICON_MAP[name] ?? Check
}

interface StaticPlan {
    id: string
    name: string
    prices: Record<string, number>
    period: string
    description?: string
    features: PlanFeature[]
    link: string
    badge?: string | null
    popular?: boolean
}

export function PlanCard({ plan, formatPrice }: { plan: StaticPlan; formatPrice: (p: number) => string }) {
    const isPopular = plan.popular

    return (
        <div className={`group relative ${isPopular ? 'md:-mt-4 md:mb-4' : ''}`}>
            {/* Glow effect behind popular card */}
            {isPopular && (
                <div className="absolute -inset-1 bg-gradient-to-r from-brand-orange via-brand-purple to-brand-orange rounded-2xl blur-lg opacity-30 group-hover:opacity-50 transition-opacity" />
            )}

            <Card className={`relative h-full rounded-2xl overflow-hidden transition-all duration-500 hover:shadow-2xl hover:-translate-y-1 ${isPopular
                ? 'bg-navy border-0 shadow-xl shadow-brand-orange/10'
                : 'bg-white border border-slate-200/80 hover:border-brand-orange/40'
                }`}>
                {/* Top gradient bar */}
                <div className={`h-1 w-full ${isPopular ? 'bg-gradient-to-r from-brand-orange to-yellow-400' : 'bg-gradient-to-r from-slate-200 to-slate-300 group-hover:from-brand-orange group-hover:to-brand-purple transition-all duration-500'}`} />

                {plan.badge && (
                    <div className="absolute top-4 right-4 bg-gradient-to-r from-brand-orange to-yellow-500 text-white text-[10px] font-bold px-3 py-1 rounded-full uppercase tracking-wider shadow-lg shadow-brand-orange/20">
                        {plan.badge}
                    </div>
                )}
                {isPopular && (
                    <div className="absolute top-4 left-4 bg-white/10 backdrop-blur-sm text-white text-[10px] font-bold px-3 py-1 rounded-full uppercase tracking-wider border border-white/20">
                        ★ Most Popular
                    </div>
                )}

                <CardHeader className="text-center pt-10 pb-4">
                    <CardTitle className={`text-lg font-semibold tracking-wide uppercase ${isPopular ? 'text-slate-300' : 'text-slate-500'}`}>
                        {plan.name}
                    </CardTitle>
                    {plan.description && (
                        <CardDescription className={`text-sm mt-1 ${isPopular ? 'text-slate-400' : ''}`}>
                            {plan.description}
                        </CardDescription>
                    )}
                    <div className="mt-6 mb-2">
                        <span className={`text-5xl font-extrabold tracking-tight ${isPopular ? 'text-white' : 'text-navy'}`}>
                            {formatPrice(Object.values(plan.prices)[0] ?? 0)}
                        </span>
                        <span className={`text-sm font-medium ml-1 ${isPopular ? 'text-slate-400' : 'text-slate-500'}`}>
                            /{plan.period}
                        </span>
                    </div>
                </CardHeader>

                <CardContent className="pt-0 px-8">
                    <div className={`w-full h-px mb-6 ${isPopular ? 'bg-white/10' : 'bg-slate-100'}`} />
                    <ul className="space-y-3.5">
                        {plan.features.map((feature, i) => {
                            const f = normalizeFeature(feature)
                            const FIcon = getFeatureIcon(f.icon)
                            return (
                                <li key={i} className={`flex items-start gap-3 text-sm ${isPopular ? 'text-slate-300' : 'text-slate-600'}`}>
                                    <div className={`mt-0.5 p-0.5 rounded ${isPopular ? 'text-brand-orange' : 'text-emerald-500'}`}>
                                        <FIcon className="h-4 w-4" />
                                    </div>
                                    <span className="font-medium">{f.text}</span>
                                </li>
                            )
                        })}
                    </ul>
                </CardContent>

                <CardFooter className="pt-6 pb-8 px-8">
                    <Button
                        className={`w-full rounded-xl h-12 text-sm font-bold tracking-wide transition-all duration-300 ${isPopular
                            ? 'bg-gradient-to-r from-brand-orange to-yellow-500 hover:from-brand-orange hover:to-yellow-400 text-white shadow-lg shadow-brand-orange/25 hover:shadow-brand-orange/40 hover:scale-[1.02]'
                            : 'bg-navy hover:bg-navy/90 text-white hover:shadow-lg'
                            }`}
                        asChild
                    >
                        <a href={plan.link}>
                            Get Started
                            <ChevronRight className="ml-1 h-4 w-4" />
                        </a>
                    </Button>
                </CardFooter>
            </Card>
        </div>
    )
}

/* ----------------------------------------------------------------
 *  WHMCS-powered pricing card
 * ---------------------------------------------------------------- */

export function WhmcsPlanCard({ product }: { product: AppProduct }) {
    const { formatRawPrice } = useCurrency()

    return (
        <div className="group">
            <Card className={`relative h-full border-2 transition-all duration-300 hover:shadow-xl hover:-translate-y-1 border-slate-200 hover:border-brand-orange/50`}>
                <CardHeader className="text-center pt-8 pb-2">
                    <CardTitle className="text-xl font-bold text-navy">{product.name}</CardTitle>
                    <div className="mt-4">
                        {product.pricing.monthly > 0 ? (
                            <>
                                <span className="text-4xl font-extrabold text-navy">{formatRawPrice(product.pricing.monthly)}</span>
                                <span className="text-slate-500 text-sm">/mo</span>
                            </>
                        ) : (
                            <span className="text-2xl font-bold text-navy">Contact Us</span>
                        )}
                    </div>
                </CardHeader>
                <CardContent className="pt-2">
                    <ul className="space-y-2.5">
                        {product.features.slice(0, 8).map((feature, i) => (
                            <li key={i} className={`flex items-start gap-2 text-sm ${feature.included ? 'text-slate-700' : 'text-slate-400 line-through'}`}>
                                <Check className={`h-4 w-4 shrink-0 mt-0.5 ${feature.included ? 'text-emerald-500' : 'text-slate-300'}`} />
                                {feature.text}
                            </li>
                        ))}
                    </ul>
                </CardContent>
                <CardFooter className="pt-2 pb-6">
                    <Button className="w-full rounded-xl h-11 bg-navy hover:bg-navy/90" asChild>
                        <a href={product.orderUrl}>Get Started</a>
                    </Button>
                </CardFooter>
            </Card>
        </div>
    )
}

/* ----------------------------------------------------------------
 *  Homepage PricingCards — multi-currency aware
 * ---------------------------------------------------------------- */

interface PricingCardsProps {
    config?: {
        heading: string
        description: string
        plans: {
            id: string
            name: string
            prices: Record<string, number>
            period: string
            features: PlanFeature[]
            link: string
            badge: string | null
            popular: boolean
        }[]
        styles?: SectionStyles
    }
}

export function PricingCards({ config }: PricingCardsProps) {
    const { currency, formatRawPrice } = useCurrency()
    const { ref, isVisible } = useScrollAnimation()

    const heading = config?.heading ?? 'Choose hosting plan for your needs'
    const description = config?.description ?? 'From personal to enterprise, we have a plan that fits your budget and performance requirements.'
    const plans: StaticPlan[] = config?.plans ?? [
        {
            id: 'web-starter',
            name: 'Web Hosting',
            prices: { USD: 3.90, BDT: 450 },
            period: 'mo',
            features: ['1 Website', '50 GB NVMe Storage', 'Unmetered Bandwidth', 'Free SSL Certificate', 'Daily Backups'],
            link: '/web-hosting',
            badge: 'SAVE 50%',
            popular: false
        },
        {
            id: 'vps-starter',
            name: 'VPS Server',
            prices: { USD: 9.99, BDT: 1100 },
            period: 'mo',
            features: ['2 vCPU Cores', '4 GB RAM', '60 GB NVMe Storage', '1 TB Bandwidth', 'Full Root Access'],
            link: '/vps',
            badge: null,
            popular: false
        },
        {
            id: 'dedi-starter',
            name: 'Dedicated Server',
            prices: { USD: 59.99, BDT: 6600 },
            period: 'mo',
            features: ['Intel Xeon E5', '32 GB DDR4 RAM', '2x 480GB SSD', '10 TB Bandwidth', 'DDoS Protection'],
            link: '/dedicated-server',
            badge: null,
            popular: false
        }
    ]

    /* Resolve price per currency: selected → USD → first available */
    const getPlanPrice = (plan: StaticPlan): string => {
        const prices = plan.prices ?? {}
        const price = prices[currency] ?? prices['USD'] ?? Object.values(prices)[0] ?? 0
        return formatRawPrice(price)
    }

    const s = config?.styles ?? {}

    return (
        <SectionWrapper bg="white" id="pricing" customBg={s.bg_color}>
            <div ref={ref} className={`text-center mb-12 ${fadeInUpClass(isVisible)}`}>
                <h2 className="text-3xl md:text-4xl font-bold text-navy mb-4" style={s.heading_color ? { color: s.heading_color } : undefined}>{heading}</h2>
                <p className="text-slate-600 max-w-2xl mx-auto" style={s.text_color ? { color: s.text_color } : undefined}>{description}</p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto">
                {plans.map((plan) => (
                    <PlanCard key={plan.id} plan={plan} formatPrice={() => getPlanPrice(plan)} />
                ))}
            </div>
        </SectionWrapper>
    )
}

/* ----------------------------------------------------------------
 *  WhmcsPricingCards — Used by service pages (web-hosting, vps, etc.)
 *  Fetches live WHMCS products, falls back to static plans
 * ---------------------------------------------------------------- */

interface FallbackPlan {
    id: string
    name: string
    price: number
    period: string
    description?: string
    features: PlanFeature[]
    link: string
    badge?: string
    popular?: boolean
}

interface WhmcsPricingCardsProps {
    gid?: number
    title?: string
    description?: string
    fallbackPlans?: FallbackPlan[]
    popularIndex?: number
}

export function WhmcsPricingCards({ gid, title, description, fallbackPlans = [], popularIndex }: WhmcsPricingCardsProps) {
    const { products, isLoading } = usePricing({ gid })
    const { formatPrice, formatRawPrice, currency } = useCurrency()
    const { ref, isVisible } = useScrollAnimation()

    // Convert old fallback plans to StaticPlan format (add `prices` from `price`/USD)
    const staticFallbacks: StaticPlan[] = fallbackPlans.map((p, i) => ({
        id: p.id,
        name: p.name,
        prices: { USD: p.price },
        period: p.period,
        description: p.description,
        features: p.features,
        link: p.link,
        badge: p.badge ?? null,
        popular: p.popular ?? i === popularIndex,
    }))

    const heading = title ?? 'Choose Your Plan'
    const desc = description ?? 'Select the package that best fits your needs.'

    // Show WHMCS products if available, otherwise fallback
    const showWhmcs = !isLoading && products.length > 0

    return (
        <SectionWrapper bg="white" id="pricing">
            <div ref={ref} className={`text-center mb-12 ${fadeInUpClass(isVisible)}`}>
                <h2 className="text-3xl md:text-4xl font-bold text-navy mb-4">{heading}</h2>
                <p className="text-slate-600 max-w-2xl mx-auto">{desc}</p>
            </div>

            {isLoading && (
                <div className="flex items-center justify-center py-12">
                    <Loader2 className="h-8 w-8 animate-spin text-slate-400" />
                </div>
            )}

            {!isLoading && (
                <div className={`grid grid-cols-1 gap-8 max-w-6xl mx-auto ${showWhmcs ? (products.length <= 3 ? 'md:grid-cols-3' : 'md:grid-cols-2 lg:grid-cols-4') : (staticFallbacks.length <= 3 ? 'md:grid-cols-3' : 'md:grid-cols-2 lg:grid-cols-4')}`}>
                    {showWhmcs
                        ? products.map(product => <WhmcsPlanCard key={product.id} product={product} />)
                        : staticFallbacks.map(plan => (
                            <PlanCard
                                key={plan.id}
                                plan={plan}
                                formatPrice={() => {
                                    const price = plan.prices[currency] ?? plan.prices['USD'] ?? Object.values(plan.prices)[0] ?? 0
                                    return formatRawPrice(price)
                                }}
                            />
                        ))
                    }
                </div>
            )}
        </SectionWrapper>
    )
}
