"use client";

import { useState, useEffect, Suspense } from 'react';
import { notFound, useRouter } from 'next/navigation';
import Image from 'next/image';
import Link from 'next/link';
import { Loader2, Check, ShoppingCart, Heart, ArrowLeft, Truck, ShieldCheck, RefreshCw, ChevronLeft, ChevronRight, MessageCircle, X } from 'lucide-react';
import { useAuth } from '@/context/AuthContext';
import { useToast } from '@/components/Toast';
import ProductCard from '@/components/products/ProductCard';
import HorizontalCarousel from '@/components/HorizontalCarousel';
import '@/styles/Products.css';

interface Product {
    id: number;
    name: string;
    description: string;
    price: number;
    original_price?: number;
    images: string[];
    primary_image?: string;
    category_names: string[];
    stock_status: 'in_stock' | 'out_of_stock';
    stock: number;
    brand?: string;
    product_condition: string;
    material?: string;
    color?: string;
    width?: number;
    height?: number;
    depth?: number;
    badge_text?: string;
    badge_color?: string;
}

const CONDITION_MAP: Record<string, string> = {
    'New': 'Ny',
    'Excellent': 'Utmärkt',
    'Good': 'Bra',
    'Fair': 'Okej',
    'Poor': 'Sliten',
    'new': 'Ny',
    'excellent': 'Utmärkt',
    'good': 'Bra',
    'fair': 'Okej',
    'poor': 'Sliten'
};

// Consistent number formatting to avoid hydration mismatch
function formatPrice(num: number): string {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
}

interface PageProps {
    params: Promise<{ id: string }>;
}

export default function ProductDetailPage({ params }: PageProps) {
    const { user, isAuthenticated } = useAuth();
    const router = useRouter();
    const { showToast } = useToast();

    const [product, setProduct] = useState<Product | null>(null);
    const [loading, setLoading] = useState(true);
    const [activeImageIndex, setActiveImageIndex] = useState(0);
    const [id, setId] = useState<string>("");
    const [showContactModal, setShowContactModal] = useState(false);
    const [showLightbox, setShowLightbox] = useState(false);
    const [contactMessage, setContactMessage] = useState('');
    const [sending, setSending] = useState(false);

    useEffect(() => {
        params.then(p => setId(p.id));
    }, [params]);

    useEffect(() => {
        if (!id) return;

        const fetchProduct = async () => {
            try {
                const res = await fetch(`/api/products/${id}`);
                if (!res.ok) {
                    if (res.status === 404) notFound();
                    throw new Error('Failed to load product');
                }
                const data = await res.json();
                setProduct(data);
            } catch (error) {
                console.error(error);
            } finally {
                setLoading(false);
            }
        };

        fetchProduct();
    }, [id]);

    const handleContactClick = () => {
        if (!isAuthenticated) {
            showToast('info', 'Du måste logga in för att skicka meddelanden');
            router.push('/login');
            return;
        }
        setShowContactModal(true);
    };

    const handleSendContact = async () => {
        if (!contactMessage.trim()) {
            showToast('error', 'Skriv ett meddelande');
            return;
        }

        setSending(true);
        try {
            const token = localStorage.getItem('token') || sessionStorage.getItem('token');
            const res = await fetch('/api/conversations', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    product_id: product?.id,
                    subject: `Artikel #${product?.id}`,
                    message: contactMessage
                })
            });

            if (res.ok) {
                showToast('success', 'Meddelande skickat! Vi återkommer snart.');
                setShowContactModal(false);
                setContactMessage('');
            } else {
                const data = await res.json();
                showToast('error', data.error || 'Kunde inte skicka meddelande');
            }
        } catch (err) {
            showToast('error', 'Något gick fel');
        } finally {
            setSending(false);
        }
    };

    if (loading) return <div className="h-screen flex items-center justify-center"><Loader2 className="animate-spin" size={48} /></div>;
    if (!product) return <div className="p-10 text-center">Produkt hittades inte</div>;

    const hasDiscount = product.original_price && product.original_price > product.price;
    const discountPercentage = hasDiscount
        ? Math.round(((product.original_price! - product.price) / product.original_price!) * 100)
        : 0;

    return (
        <div className="product-detail-container">
            <Link href="/products" className="product-detail-back">
                <ArrowLeft size={14} /> Tillbaka till produkter
            </Link>

            <div className="product-detail-grid">
                {/* Left: Image Gallery */}
                <div className="space-y-4">
                    <div className="aspect-[4/3] relative rounded-2xl overflow-hidden bg-gray-100 dark:bg-gray-800 border border-[var(--border-color)] group cursor-zoom-in" onClick={() => setShowLightbox(true)}>
                        {product.images.length > 0 ? (
                            <Image
                                key={product.images[activeImageIndex]}
                                src={product.images[activeImageIndex]}
                                alt={product.name}
                                fill
                                className="object-cover transition-opacity duration-300"
                                sizes="(max-width: 768px) 100vw, 50vw"
                                priority
                                unoptimized={product.images[activeImageIndex].startsWith('http')}
                            />
                        ) : (
                            <div className="flex items-center justify-center h-full text-gray-400">Ingen bild</div>
                        )}

                        {product.badge_text && (
                            <div
                                className="absolute top-4 left-4 px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider text-white shadow-md z-10"
                                style={{ backgroundColor: product.badge_color || '#000' }}
                            >
                                {product.badge_text}
                            </div>
                        )}

                        {/* Navigation Arrows */}
                        {product.images.length > 1 && (
                            <div onClick={(e) => e.stopPropagation()}>
                                <button
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        setActiveImageIndex(prev => (prev === 0 ? product.images.length - 1 : prev - 1));
                                    }}
                                    className="absolute left-3 top-1/2 -translate-y-1/2 w-10 h-10 bg-white/80 dark:bg-black/50 rounded-full flex items-center justify-center transition-opacity z-20 hover:bg-white dark:hover:bg-black"
                                    aria-label="Previous image"
                                >
                                    <ChevronLeft size={24} className="text-gray-800 dark:text-white" />
                                </button>
                                <button
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        setActiveImageIndex(prev => (prev === product.images.length - 1 ? 0 : prev + 1));
                                    }}
                                    className="absolute right-3 top-1/2 -translate-y-1/2 w-10 h-10 bg-white/80 dark:bg-black/50 rounded-full flex items-center justify-center transition-opacity z-20 hover:bg-white dark:hover:bg-black"
                                    aria-label="Next image"
                                >
                                    <ChevronRight size={24} className="text-gray-800 dark:text-white" />
                                </button>
                            </div>
                        )}

                        {/* Dot Indicators */}
                        {product.images.length > 1 && (
                            <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2 z-20" onClick={(e) => e.stopPropagation()}>
                                {product.images.map((_, idx) => (
                                    <button
                                        key={idx}
                                        onClick={() => setActiveImageIndex(idx)}
                                        className={`w-2.5 h-2.5 rounded-full transition-all ${activeImageIndex === idx ? 'bg-white scale-125' : 'bg-white/50 hover:bg-white/80'}`}
                                        aria-label={`Go to image ${idx + 1}`}
                                    />
                                ))}
                            </div>
                        )}
                    </div>

                    {/* Thumbnail Strip */}
                    {product.images.length > 1 && (
                        <div className="flex gap-2 overflow-x-auto pb-2">
                            {product.images.map((img, idx) => (
                                <button
                                    key={idx}
                                    onClick={() => setActiveImageIndex(idx)}
                                    className={`flex-shrink-0 w-20 h-20 relative overflow-hidden border-2 transition-all ${activeImageIndex === idx ? 'border-[var(--text-color)]' : 'border-[var(--border-color)] hover:border-[var(--text-color)]'}`}
                                >
                                    <Image
                                        src={img}
                                        alt={`${product.name} thumbnail ${idx + 1}`}
                                        fill
                                        className="object-cover"
                                        sizes="80px"
                                        unoptimized={img.startsWith('http')}
                                    />
                                </button>
                            ))}
                        </div>
                    )}
                </div>

                {/* Right: Product Details */}
                <div className="flex flex-col">
                    <div className="mb-2 text-[var(--foreground)] opacity-80">
                        <span className="text-sm font-bold uppercase tracking-wide">
                            {product.brand || 'Okänt märke'}
                        </span>
                        <span className="mx-2 opacity-30">•</span>
                        <span className="text-sm font-medium uppercase">
                            {product.category_names.length > 0 ? product.category_names.join(', ') : 'OKÄND KATEGORI'}
                        </span>
                    </div>

                    <div className="flex items-center justify-between gap-4 mb-4">
                        <h1 className="text-3xl md:text-4xl font-bold">{product.name}</h1>
                    </div>

                    <div className="mb-6">
                        {hasDiscount && (
                            <div className="flex items-center gap-2 mb-1">
                                <span className="text-gray-500 line-through text-lg">
                                    {formatPrice(product.original_price!)} kr
                                </span>
                                <span className="text-red-600 text-sm font-bold">
                                    -{discountPercentage}%
                                </span>
                            </div>
                        )}
                        <div className="flex items-center gap-4">
                            <div className="text-4xl font-black text-[var(--foreground)]">
                                {formatPrice(product.price)} kr
                            </div>
                            <div className={`flex items-center gap-2 text-sm font-bold flex-shrink-0 ${product.stock_status === 'in_stock' ? 'text-green-600' : 'text-red-500'}`}>
                                <div className={`w-2 h-2 rounded-full ${product.stock_status === 'in_stock' ? 'bg-green-600' : 'bg-red-500'}`} />
                                {product.stock_status === 'in_stock' ? 'I lager' : 'Slutsåld'}
                            </div>
                        </div>
                    </div>

                    {/* Description Section */}
                    <div className="mb-8">
                        <h3 className="text-sm font-black uppercase tracking-wider text-[var(--foreground)] mb-3">Beskrivning</h3>
                        <p className="text-[var(--foreground)] opacity-90 leading-relaxed whitespace-pre-line text-sm md:text-base">
                            {product.description}
                        </p>
                    </div>

                    {/* Specs Grid */}
                    <div className="mb-8 p-0">
                        <h3 className="text-sm font-black uppercase tracking-wider text-[var(--foreground)] mb-3">Produktdetaljer</h3>
                        <div className="grid grid-cols-2 gap-x-6 gap-y-3 text-sm">
                            <div className="text-gray-500 uppercase text-[10px] font-black tracking-widest">Kategori</div>
                            <div className="font-bold text-[var(--foreground)] uppercase">{product.category_names.join(', ')}</div>

                            <div className="text-gray-500 uppercase text-[10px] font-black tracking-widest">Skick</div>
                            <div className="font-bold text-[var(--foreground)] uppercase">{CONDITION_MAP[product.product_condition] || product.product_condition}</div>

                            {product.material && (
                                <>
                                    <div className="text-gray-500 uppercase text-[10px] font-black tracking-widest">Material</div>
                                    <div className="font-bold text-[var(--foreground)] uppercase">{product.material}</div>
                                </>
                            )}
                            {product.color && (
                                <>
                                    <div className="text-gray-500 uppercase text-[10px] font-black tracking-widest">Färg</div>
                                    <div className="font-bold text-[var(--foreground)] uppercase">{product.color}</div>
                                </>
                            )}
                            {product.width && (
                                <>
                                    <div className="text-gray-500 uppercase text-[10px] font-black tracking-widest">Mått</div>
                                    <div className="font-bold text-[var(--foreground)] uppercase">{product.width}x{product.height}x{product.depth} cm</div>
                                </>
                            )}
                            <div className="text-gray-500 uppercase text-[10px] font-black tracking-widest">Lager</div>
                            <div className="font-bold text-[var(--foreground)] uppercase">{product.stock} st</div>
                        </div>
                    </div>

                    {/* Actions */}
                    <div className="mt-auto">
                        <button
                            onClick={handleContactClick}
                            style={{
                                width: '100%',
                                background: 'var(--card-bg)',
                                color: 'var(--text-color)',
                                border: '1px solid var(--border-color)',
                                padding: '1.25rem 1.5rem',
                                borderRadius: '4px',
                                cursor: 'pointer',
                                display: 'flex',
                                flexDirection: 'column',
                                alignItems: 'center',
                                justifyContent: 'center',
                                gap: '0.25rem',
                                transition: 'all 0.2s'
                            }}
                            onMouseEnter={(e) => {
                                e.currentTarget.style.borderColor = 'var(--text-color)';
                                e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.05)';
                            }}
                            onMouseLeave={(e) => {
                                e.currentTarget.style.borderColor = 'var(--border-color)';
                                e.currentTarget.style.boxShadow = 'none';
                            }}
                        >
                            <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
                                <MessageCircle size={20} />
                                <span style={{ fontWeight: 700, fontSize: '0.85rem', textTransform: 'uppercase', letterSpacing: '1.5px' }}>Chatta Med Oss</span>
                            </div>
                            <span style={{ fontSize: '0.75rem', color: 'var(--text-secondary)', fontWeight: 500 }}>Svarstid 10-15 minuter</span>
                        </button>
                    </div>
                </div>
            </div>

            {/* Contact Modal */}
            {showContactModal && (
                <div style={{
                    position: 'fixed',
                    inset: 0,
                    background: 'rgba(0,0,0,0.6)',
                    backdropFilter: 'blur(4px)',
                    zIndex: 9999,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    padding: '1rem'
                }}>
                    <div style={{
                        background: 'var(--card-bg)',
                        border: '1px solid var(--border-color)',
                        padding: '2rem',
                        maxWidth: '450px',
                        width: '100%'
                    }}>
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
                            <h3 style={{ fontSize: '1rem', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '0.1em', margin: 0 }}>Skicka förfrågan</h3>
                            <button onClick={() => setShowContactModal(false)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '0.25rem' }}>
                                <X size={20} />
                            </button>
                        </div>

                        <div style={{ marginBottom: '1rem', padding: '1rem', background: 'var(--input-bg)', border: '1px solid var(--border-color)' }}>
                            <p style={{ fontSize: '0.65rem', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '1px', color: 'var(--text-secondary)', marginBottom: '0.25rem' }}>Ämne</p>
                            <p style={{ fontWeight: 700, margin: 0 }}>Artikel #{product.id}</p>
                        </div>

                        <div style={{ marginBottom: '1rem' }}>
                            <label style={{ display: 'block', fontSize: '0.65rem', fontWeight: 900, textTransform: 'uppercase', letterSpacing: '1px', color: 'var(--text-secondary)', marginBottom: '0.5rem' }}>Ditt meddelande</label>
                            <textarea
                                value={contactMessage}
                                onChange={(e) => setContactMessage(e.target.value)}
                                placeholder="Jag är intresserad av denna produkt..."
                                style={{
                                    width: '100%',
                                    padding: '1rem',
                                    border: '1px solid var(--border-color)',
                                    background: 'var(--input-bg)',
                                    color: 'var(--text-color)',
                                    fontSize: '0.9rem',
                                    minHeight: '120px',
                                    resize: 'vertical',
                                    outline: 'none',
                                    boxSizing: 'border-box'
                                }}
                            />
                        </div>

                        <button
                            onClick={handleSendContact}
                            disabled={sending}
                            style={{
                                width: '100%',
                                background: 'var(--text-color)',
                                color: 'var(--background)',
                                border: '1px solid var(--text-color)',
                                padding: '1.1rem',
                                borderRadius: '4px',
                                fontWeight: 700,
                                fontSize: '0.85rem',
                                cursor: sending ? 'not-allowed' : 'pointer',
                                textTransform: 'uppercase',
                                letterSpacing: '1.5px',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                gap: '0.75rem',
                                opacity: sending ? 0.4 : 1
                            }}
                        >
                            {sending ? <Loader2 className="animate-spin" size={18} /> : <MessageCircle size={18} />}
                            {sending ? 'Skickar...' : 'Skicka meddelande'}
                        </button>
                    </div>
                </div>
            )}

            {/* Highlights - Centralized below the product section */}
            <div className="mt-16 py-12 border-t border-[var(--border-color)]">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-8 max-w-4xl mx-auto text-center">
                    <div className="flex flex-col items-center">
                        <div className="w-12 h-12 bg-blue-50 dark:bg-blue-900/20 rounded-full flex items-center justify-center text-blue-600 mb-4">
                            <Truck size={24} />
                        </div>
                        <h4 className="font-bold text-lg">Snabb leverans</h4>
                        <p className="text-sm text-gray-500">2-4 arbetsdagar</p>
                    </div>
                    <div className="flex flex-col items-center">
                        <div className="w-12 h-12 bg-green-50 dark:bg-green-900/20 rounded-full flex items-center justify-center text-green-600 mb-4">
                            <ShieldCheck size={24} />
                        </div>
                        <h4 className="font-bold text-lg">Kvalitetskontrollerad</h4>
                        <p className="text-sm text-gray-500">Testad & rensad</p>
                    </div>
                    <div className="flex flex-col items-center">
                        <div className="w-12 h-12 bg-purple-50 dark:bg-purple-900/20 rounded-full flex items-center justify-center text-purple-600 mb-4">
                            <RefreshCw size={24} />
                        </div>
                        <h4 className="font-bold text-lg">Trygg e-handel</h4>
                        <p className="text-sm text-gray-500">14 dagars ångerrätt</p>
                    </div>
                </div>
            </div>

            {/* Lightbox Modal */}
            {showLightbox && product && (
                <div className="fixed inset-0 z-[100] bg-black/95 flex items-center justify-center p-4" onClick={() => setShowLightbox(false)}>
                    <button
                        className="absolute top-4 right-4 text-white/50 hover:text-white transition-colors"
                        onClick={() => setShowLightbox(false)}
                    >
                        <X size={32} />
                    </button>

                    <div className="relative w-full max-w-5xl h-[80vh]" onClick={e => e.stopPropagation()}>
                        <Image
                            src={product.images[activeImageIndex]}
                            alt={product.name}
                            fill
                            className="object-contain"
                            sizes="100vw"
                            priority
                            unoptimized={product.images[activeImageIndex].startsWith('http')}
                        />

                        {product.images.length > 1 && (
                            <>
                                <button
                                    onClick={() => setActiveImageIndex(prev => (prev === 0 ? product.images.length - 1 : prev - 1))}
                                    className="absolute left-4 top-1/2 -translate-y-1/2 w-12 h-12 bg-black/50 text-white rounded-full flex items-center justify-center hover:bg-black/80 transition-colors"
                                >
                                    <ChevronLeft size={32} />
                                </button>
                                <button
                                    onClick={() => setActiveImageIndex(prev => (prev === product.images.length - 1 ? 0 : prev + 1))}
                                    className="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 bg-black/50 text-white rounded-full flex items-center justify-center hover:bg-black/80 transition-colors"
                                >
                                    <ChevronRight size={32} />
                                </button>

                                <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2">
                                    {product.images.map((_, idx) => (
                                        <button
                                            key={idx}
                                            onClick={() => setActiveImageIndex(idx)}
                                            className={`w-3 h-3 rounded-full transition-all ${activeImageIndex === idx ? 'bg-white' : 'bg-white/30 hover:bg-white/50'}`}
                                        />
                                    ))}
                                </div>
                            </>
                        )}
                    </div>
                </div>
            )}

            {/* Similar Products Section */}
            <SimilarProducts currentProductId={product.id} />
        </div>
    );
}

// Import at the top will be handled separately if needed, but assuming I can't double-tool properly.
// Wait, I need to add import.

function SimilarProducts({ currentProductId }: { currentProductId: number }) {
    const [products, setProducts] = useState<Product[]>([]);

    useEffect(() => {
        // Fetch random products as "similar" for now to simulate recommendation
        // In a real app, pass category IDs or tags
        const fetchSimilar = async () => {
            try {
                // Limit doubled to 8 per user request
                const res = await fetch(`/api/products?limit=8&page=1&sort=random`);
                if (res.ok) {
                    const data = await res.json();
                    setProducts(data.products.filter((p: Product) => p.id !== currentProductId).slice(0, 8));
                }
            } catch (err) {
                console.error(err);
            }
        };
        fetchSimilar();
    }, [currentProductId]);

    if (products.length === 0) return null;

    return (
        <div className="similar-products">
            <h2>Liknande produkter</h2>
            {/* Horizontal Scroll Layout - Centered if possible */}
            <HorizontalCarousel>
                {products.map(product => (
                    <div key={product.id} className="flex-shrink-0 w-64 md:w-72 lg:w-80 snap-start">
                        <ProductCard product={product} />
                    </div>
                ))}
            </HorizontalCarousel>
        </div>
    );
}
