import AltivateLayout from '@/Layouts/AltivateLayout';
import { Link, useForm, usePage } from '@inertiajs/react';
import { ArrowLeft, Check, Download, FileText, Package, Loader2, PlayCircle, Video, ChevronDown, ChevronUp, BookOpen, Clock, Users } from "lucide-react";
import { useState } from 'react';
import SEO from '@/Components/SEO';

interface Product {
    id: number;
    name: string;
    slug: string;
    description: string;
    price: number;
    currency: string;
    type: string;
    features: string[] | null;
    modules?: Array<{
        id: number;
        title: string;
        description: string | null;
        lessons: Array<{
            id: number;
            title: string;
            type: string;
        }>;
    }>;
}

interface Props {
    product: Product;
}

export default function StoreShow({ product }: Props) {
    const { auth, app_url } = usePage<any>().props;
    const [expandedModules, setExpandedModules] = useState<number[]>([product.modules?.[0]?.id || 0]);

    const toggleModule = (id: number) => {
        setExpandedModules((prev: number[]) => 
            prev.includes(id) ? prev.filter((m: number) => m !== id) : [...prev, id]
        );
    };
    
    const productSchema = {
        "@context": "https://schema.org/",
        "@type": "Product",
        "name": product.name,
        "description": product.description,
        "image": `${app_url}/og-image.png`,
        "offers": {
            "@type": "Offer",
            "url": typeof window !== 'undefined' ? window.location.href : `${app_url}/store/${product.slug}`,
            "priceCurrency": product.currency,
            "price": product.price,
            "availability": "https://schema.org/InStock"
        }
    };

    const { data, setData, post, processing, errors } = useForm({
        name: '',
        email: '',
    });

    const handleCheckout = (e: React.FormEvent) => {
        e.preventDefault();
        post(route('store.checkout', product.id));
    };

    return (
        <AltivateLayout>
            <SEO 
                title={product.name}
                description={product.description}
                type="product"
                schema={productSchema}
            />
            <div className="min-h-screen">
                <section className="container-x pt-32 pb-12 md:pt-40 md:pb-20">
                    <Link 
                        href={route('store.index')} 
                        className="inline-flex items-center gap-2 text-sm text-muted-foreground transition-colors hover:text-accent"
                    >
                        <ArrowLeft className="h-4 w-4" /> Back to store
                    </Link>

                    <div className="mt-12 grid gap-12 lg:grid-cols-12">
                        {/* LEFT: Info */}
                        <div className="lg:col-span-7">
                            <div>
                                <div className="flex items-center gap-3">
                                    <div className={`flex h-8 w-8 items-center justify-center rounded-lg bg-secondary ${product.type === 'Course' ? 'text-primary' : 'text-accent'}`}>
                                        {product.type === 'Course' ? <BookOpen className="h-4 w-4" /> : <Package className="h-4 w-4" />}
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <p className={`eyebrow !mb-0 ${product.type === 'Course' ? '!text-primary' : '!text-accent'}`}>{product.type}</p>
                                        {product.type === 'Course' && (
                                            <span className="flex items-center gap-1 text-[10px] font-bold text-[#8C92AC] uppercase tracking-wider">
                                                <Clock className="h-3 w-3" /> Self-paced
                                            </span>
                                        )}
                                    </div>
                                </div>
                                <h1 className="font-display mt-4 text-4xl md:text-5xl leading-tight">{product.name}</h1>
                            </div>

                            <div className="mt-10 space-y-6 text-lg text-muted-foreground leading-relaxed">
                                <p>{product.description}</p>
                            </div>

                            {product.features && product.features.length > 0 && (
                                <div className="mt-16">
                                    <h3 className="font-display text-2xl">What's included</h3>
                                    <ul className="mt-6 grid gap-4 sm:grid-cols-2">
                                        {product.features.map((item, i) => (
                                            <li key={i} className="flex items-start gap-3 rounded-2xl border border-border bg-card p-4 hover:border-primary/20 transition-colors">
                                                <div className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-full ${product.type === 'Course' ? 'bg-primary/10 text-primary' : 'bg-accent/10 text-accent'}`}>
                                                    <Check className="h-3.5 w-3.5" />
                                                </div>
                                                <span className="text-sm font-medium">{item}</span>
                                            </li>
                                        ))}
                                    </ul>
                                </div>
                            )}

                            {product.type === 'Course' && product.modules && product.modules.length > 0 && (
                                <div className="mt-16">
                                    <div className="flex items-center justify-between mb-8">
                                        <div>
                                            <h3 className="font-display text-2xl">Curriculum</h3>
                                            <p className="text-sm text-muted-foreground mt-1">
                                                {product.modules.length} Modules • {product.modules.reduce((sum, m) => sum + m.lessons.length, 0)} Lessons
                                            </p>
                                        </div>
                                    </div>

                                    <div className="space-y-4">
                                        {product.modules.map((module, idx) => (
                                            <div key={module.id} className="rounded-2xl border border-border overflow-hidden bg-card">
                                                <button 
                                                    onClick={() => toggleModule(module.id)}
                                                    className="w-full flex items-center justify-between p-5 text-left hover:bg-secondary/30 transition-colors"
                                                >
                                                    <div className="flex items-center gap-4">
                                                        <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-secondary text-[11px] font-bold text-ink">
                                                            {idx + 1}
                                                        </span>
                                                        <span className="font-bold text-ink">{module.title}</span>
                                                    </div>
                                                    {expandedModules.includes(module.id) ? <ChevronUp className="h-4 w-4 text-[#8C92AC]" /> : <ChevronDown className="h-4 w-4 text-[#8C92AC]" />}
                                                </button>
                                                
                                                {expandedModules.includes(module.id) && (
                                                    <div className="px-5 pb-5 space-y-1">
                                                        {module.lessons.map((lesson, lIdx) => (
                                                            <div key={lesson.id} className="flex items-center justify-between py-3 px-4 rounded-xl hover:bg-secondary/20 transition-colors">
                                                                <div className="flex items-center gap-3">
                                                                    {lesson.type === 'Video' ? <PlayCircle className="h-4 w-4 text-[#8C92AC]" /> : <FileText className="h-4 w-4 text-[#8C92AC]" />}
                                                                    <span className="text-sm font-medium text-ink/80">{lesson.title}</span>
                                                                </div>
                                                                <span className="text-[10px] font-bold text-[#C0BDBA] uppercase tracking-widest">{lesson.type}</span>
                                                            </div>
                                                        ))}
                                                    </div>
                                                )}
                                            </div>
                                        ))}
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* RIGHT: Checkout Sidebar */}
                        <div className="lg:col-span-5 lg:pl-8">
                            <div className="sticky top-32 rounded-3xl border border-border bg-card p-8 shadow-2xl shadow-accent/5">
                                <p className="eyebrow">Instant Access</p>
                                <div className="mt-6 flex items-baseline gap-3">
                                    <span className="font-display text-5xl">{product.currency} {parseFloat(product.price.toString()).toLocaleString()}</span>
                                </div>
                                <p className="mt-4 text-sm text-muted-foreground">
                                    Get immediate access to this {product.type.toLowerCase()}. One-time payment.
                                </p>

                                <form id="checkout-form" onSubmit={handleCheckout} className="mt-8 space-y-4">
                                    {!auth.user && (
                                        <div className="space-y-4">
                                            <div>
                                                <label className="text-[10px] uppercase tracking-widest font-bold text-muted-foreground mb-1.5 block">Full Name</label>
                                                <input
                                                    type="text"
                                                    required
                                                    value={data.name}
                                                    onChange={e => setData('name', e.target.value)}
                                                    placeholder="John Doe"
                                                    className="w-full bg-secondary/30 border-border rounded-xl px-4 py-3 text-sm focus:ring-accent focus:border-accent"
                                                />
                                                {errors.name && <p className="text-destructive text-[10px] mt-1 font-medium">{errors.name}</p>}
                                            </div>
                                            <div>
                                                <label className="text-[10px] uppercase tracking-widest font-bold text-muted-foreground mb-1.5 block">Email Address</label>
                                                <input
                                                    type="email"
                                                    required
                                                    value={data.email}
                                                    onChange={e => setData('email', e.target.value)}
                                                    placeholder="john@example.com"
                                                    className="w-full bg-secondary/30 border-border rounded-xl px-4 py-3 text-sm focus:ring-accent focus:border-accent"
                                                />
                                                {errors.email && <p className="text-destructive text-[10px] mt-1 font-medium">{errors.email}</p>}
                                            </div>
                                        </div>
                                    )}
                                    
                                    <button 
                                        type="submit"
                                        disabled={processing}
                                        className="flex w-full items-center justify-center gap-3 rounded-full bg-primary py-4 font-medium text-primary-foreground transition-all hover:-translate-y-1 active:scale-95 disabled:opacity-70 disabled:hover:translate-y-0"
                                    >
                                        {processing ? (
                                            <>
                                                <Loader2 className="h-4 w-4 animate-spin" /> Processing...
                                            </>
                                        ) : (
                                            <>
                                                Purchase Now <Download className="h-4 w-4" />
                                            </>
                                        )}
                                    </button>
                                    <p className="text-center text-[10px] uppercase tracking-widest text-muted-foreground">
                                        Deliverables sent to {auth.user ? 'your account email' : 'the email provided above'}
                                    </p>
                                </form>

                                <div className="mt-10 border-t border-border pt-8">
                                    <p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">Category</p>
                                    <div className="mt-4 flex flex-wrap gap-2">
                                        <div className="flex items-center gap-2 rounded-lg bg-secondary px-3 py-1.5 text-xs font-medium">
                                            <FileText className="h-3.5 w-3.5" /> {product.type}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>

                <section className="border-t border-border bg-secondary/20">
                    <div className="container-x py-24 text-center">
                        <p className="eyebrow">Success Support</p>
                        <h2 className="font-display mt-6 text-3xl md:text-4xl">Need help implementing this system?</h2>
                        <p className="mx-auto mt-6 max-w-xl text-muted-foreground text-sm">
                            Purchase this resource and get 20% off a 1-on-1 strategy implementation call. We'll help you customise these templates for your specific business goals.
                        </p>
                        <button className="mt-10 inline-flex h-12 items-center gap-2 rounded-full bg-accent px-8 text-sm font-medium text-accent-foreground transition-transform hover:-translate-y-0.5">
                            Claim my 20% discount
                        </button>
                    </div>
                </section>
            </div>
            {/* Sticky Mobile Purchase Bar */}
            <div className="lg:hidden fixed bottom-0 left-0 right-0 z-[100] bg-white/95 backdrop-blur-xl border-t border-border p-4 pb-safe-area-inset-bottom flex items-center justify-between gap-4 shadow-[0_-10px_30px_-15px_rgba(0,0,0,0.2)]">
                <div className="flex-1 min-w-0">
                    <p className="text-[10px] uppercase tracking-widest font-bold text-muted-foreground">Price</p>
                    <p className="text-lg font-display font-bold truncate">
                        {product.currency} {parseFloat(product.price.toString()).toLocaleString()}
                    </p>
                </div>
                <button 
                    onClick={() => {
                        const form = document.getElementById('checkout-form');
                        if (form) {
                            form.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }
                    }}
                    className="px-8 h-12 bg-primary text-primary-foreground rounded-full font-bold text-sm transition-transform active:scale-95"
                >
                    Purchase Now
                </button>
            </div>
        </AltivateLayout>
    );
}
