import { cn } from '@/lib/utils';
import { Download, Package, Server } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';

function useScrollAnimation(options?: { threshold?: number; delay?: number }) {
    const ref = useRef<HTMLDivElement>(null);
    const [isVisible, setIsVisible] = useState(false);

    useEffect(() => {
        const el = ref.current;
        if (!el) return;

        const observer = new IntersectionObserver(
            ([entry]) => {
                if (entry.isIntersecting) {
                    if (options?.delay) {
                        setTimeout(() => setIsVisible(true), options.delay);
                    } else {
                        setIsVisible(true);
                    }
                    observer.unobserve(el);
                }
            },
            { threshold: options?.threshold ?? 0.15 },
        );

        observer.observe(el);
        return () => observer.disconnect();
    }, [options?.threshold, options?.delay]);

    return { ref, isVisible };
}

interface DownloadItem {
    id: number;
    name: string;
    description: string;
    size: string;
    url: string;
    icon_name: string;
    mirror_url?: string;
    mirror_icon?: string;
    sort_order: number;
    is_active: boolean;
}

interface DownloadSectionProps {
    downloadItems?: DownloadItem[];
    downloadBackgroundUrl?: string | null;
}

const iconImages: Record<string, string> = {
    gdrive: '/img/download/gdrive.webp',
    mediafire: '/img/download/mediafire.webp',
    mega: '/img/download/mega.webp',
};

const tabs = [
    { id: 'system', label: 'System', icon: <Server className="h-5 w-5" /> },
    { id: 'files', label: 'Files', icon: <Package className="h-5 w-5" /> },
];

const systemRequirements = [
    { label: 'OS', value: 'Windows 7/8/10/11' },
    { label: 'CPU', value: 'Intel Core i3 or AMD equivalent' },
    { label: 'RAM', value: '4 GB minimum' },
    { label: 'GPU', value: 'NVIDIA GTX 460 / AMD HD 5750' },
    { label: 'Storage', value: '20 GB available space' },
    { label: 'Network', value: 'Broadband Internet' },
];

export function DownloadSection({ downloadItems = [], downloadBackgroundUrl }: DownloadSectionProps) {
    const [activeTab, setActiveTab] = useState('system');
    const [_isMobile, setIsMobile] = useState(false);

    useEffect(() => {
        const checkMobile = () => setIsMobile(window.innerWidth < 768);
        checkMobile();
        window.addEventListener('resize', checkMobile);
        return () => window.removeEventListener('resize', checkMobile);
    }, []);

    const headerAnim = useScrollAnimation();
    const tabsAnim = useScrollAnimation({ delay: 100 });
    const contentAnim = useScrollAnimation({ delay: 200 });

    const files = downloadItems.filter((item) => item.is_active);

    const handleDownload = (url: string) => {
        window.open(url, '_blank');
    };

    // Check if parent already has background (downloadBackgroundUrl is passed from parent)
    const hasParentBackground = !!downloadBackgroundUrl;

    const renderDownloadItem = (item: DownloadItem) => (
        <div
            key={item.id}
            className="group flex flex-col items-center gap-4 rounded-lg border p-4 transition-all duration-300 hover:-translate-y-0.5 sm:flex-row"
            style={{
                background: hasParentBackground ? 'rgba(15,5,34,0.86)' : 'rgba(15,5,34,0.82)',
                borderColor: 'rgba(168,85,247,0.28)',
            }}
        >
            <div
                className="flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-lg border"
                style={{ background: 'rgba(168,85,247,0.12)', borderColor: 'rgba(168,85,247,0.24)' }}
            >
                <img
                    src={iconImages[item.icon_name] || iconImages.gdrive}
                    alt=""
                    className="h-8 w-8 object-contain"
                    onError={(e) => (e.currentTarget.style.display = 'none')}
                />
            </div>
            <div className="min-w-0 flex-1 text-center sm:text-left">
                <h4 className="mb-1 truncate font-bold" style={{ color: '#f5d0fe', fontFamily: 'Cinzel, serif' }}>
                    {item.name}
                </h4>
                <p className="mb-1 truncate text-sm" style={{ color: '#a78bfa' }}>
                    {item.description}
                </p>
                <span className="rounded px-2 py-0.5 text-xs" style={{ background: 'rgba(168,85,247,0.18)', color: '#d8b4fe' }}>
                    {item.size}
                </span>
            </div>
            <div className="flex flex-shrink-0 flex-wrap justify-center gap-2">
                <button
                    onClick={() => handleDownload(item.url)}
                    className="flex items-center gap-2 rounded px-4 py-2 text-sm font-semibold transition-all hover:brightness-110"
                    style={{
                        background: 'linear-gradient(135deg, #7e22ce 0%, #d946ef 50%, #a855f7 100%)',
                        color: '#ffffff',
                        fontFamily: 'Rajdhani, sans-serif',
                        boxShadow: '0 2px 18px rgba(168,85,247,0.45)',
                    }}
                >
                    <Download className="h-4 w-4" />
                    Download
                </button>
                {item.mirror_url && (
                    <button
                        onClick={() => handleDownload(item.mirror_url!)}
                        className="flex items-center gap-2 rounded border px-4 py-2 text-sm font-semibold transition-all hover:bg-[rgba(168,85,247,0.1)]"
                        style={{
                            color: '#d8b4fe',
                            borderColor: 'rgba(168,85,247,0.38)',
                            fontFamily: 'Rajdhani, sans-serif',
                        }}
                    >
                        Mirror
                    </button>
                )}
            </div>
        </div>
    );

    const renderContent = () => {
        switch (activeTab) {
            case 'system':
                return (
                    <div className="space-y-4">
                        <div className="mb-4">
                            <h3 className="mb-1 text-lg font-semibold" style={{ color: '#f5d0fe', fontFamily: 'Cinzel, serif' }}>
                                <Server className="mr-2 inline h-5 w-5" />
                                System Requirements
                            </h3>
                            <p className="text-sm" style={{ color: '#a78bfa' }}>
                                Minimum requirements to run the game smoothly.
                            </p>
                        </div>
                        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                            {systemRequirements.map((req, index) => (
                                <div
                                    key={index}
                                    className="flex items-center justify-between rounded-lg border p-3"
                                    style={{
                                        background: hasParentBackground ? 'rgba(15,5,34,0.76)' : 'rgba(15,5,34,0.62)',
                                        borderColor: 'rgba(168,85,247,0.18)',
                                    }}
                                >
                                    <span className="font-semibold" style={{ color: '#d8b4fe' }}>
                                        {req.label}
                                    </span>
                                    <span style={{ color: '#ddd6fe' }}>{req.value}</span>
                                </div>
                            ))}
                        </div>
                    </div>
                );
            case 'files':
                return (
                    <div className="space-y-4">
                        <div className="mb-4">
                            <h3 className="mb-1 text-lg font-semibold" style={{ color: '#f5d0fe', fontFamily: 'Cinzel, serif' }}>
                                <Package className="mr-2 inline h-5 w-5" />
                                Files
                            </h3>
                            <p className="text-sm" style={{ color: '#a78bfa' }}>
                                Download client and tools to start your adventure.
                            </p>
                        </div>
                        {files.length > 0 ? (
                            <div className="space-y-3">{files.map(renderDownloadItem)}</div>
                        ) : (
                            <div className="py-8 text-center" style={{ color: '#a78bfa' }}>
                                <Package className="mx-auto mb-3 h-12 w-12 opacity-50" />
                                <p>No files available at the moment.</p>
                            </div>
                        )}
                    </div>
                );
            default:
                return null;
        }
    };

    // Background is now handled by parent section in index.tsx
    // downloadBackgroundUrl prop indicates if parent has a background image

    return (
        <section className="relative" style={{ minHeight: 'auto' }}>
            <div className="relative z-10 mx-auto w-full max-w-[1600px] py-12">
                {/* Section Header - with animation */}
                <div
                    ref={headerAnim.ref}
                    className="mb-10 px-4 text-center"
                    style={{
                        opacity: headerAnim.isVisible ? 1 : 0,
                        transform: headerAnim.isVisible ? 'translateY(0)' : 'translateY(30px)',
                        transition: 'opacity 0.8s ease, transform 0.8s ease',
                    }}
                >
                    <div className="mb-3 text-sm tracking-[0.35em] uppercase" style={{ color: '#d946ef', fontFamily: 'Rajdhani, sans-serif' }}>
                        Get Started
                    </div>
                    <h2
                        className="mb-4 text-3xl font-bold md:text-4xl"
                        style={{
                            color: '#f5d0fe',
                            fontFamily: 'Cinzel Decorative, serif',
                            textShadow: '0 0 30px rgba(168,85,247,.45)',
                        }}
                    >
                        Download
                    </h2>
                    <div className="mx-auto flex max-w-xl items-center justify-center gap-3">
                        <div className="h-px flex-1 bg-gradient-to-r from-transparent to-[#7e22ce]" />
                        <span className="text-sm text-[#d946ef]">✦</span>
                        <div className="h-px flex-1 bg-gradient-to-l from-transparent to-[#7e22ce]" />
                    </div>
                </div>

                {/* Content */}
                <div className="mx-auto max-w-6xl px-4">
                    <div className="grid grid-cols-1 gap-6 lg:grid-cols-12">
                        <div
                            ref={tabsAnim.ref}
                            className="lg:col-span-3"
                            style={{
                                opacity: tabsAnim.isVisible ? 1 : 0,
                                transform: tabsAnim.isVisible ? 'translateX(0)' : 'translateX(-30px)',
                                transition: 'opacity 0.8s ease, transform 0.8s ease',
                            }}
                        >
                            {/* Mobile Tabs */}
                            <div
                                className="flex overflow-hidden rounded-lg border lg:hidden"
                                style={{
                                    borderColor: 'rgba(168,85,247,0.3)',
                                    background: hasParentBackground ? 'rgba(15,5,34,0.92)' : 'rgba(15,5,34,0.9)',
                                }}
                            >
                                {tabs.map((tab) => (
                                    <button
                                        key={tab.id}
                                        onClick={() => setActiveTab(tab.id)}
                                        className={cn(
                                            'relative flex flex-1 items-center justify-center gap-2 px-4 py-3 text-center transition-all duration-300',
                                            activeTab === tab.id ? 'bg-[rgba(168,85,247,0.16)]' : 'hover:bg-[rgba(168,85,247,0.08)]',
                                        )}
                                    >
                                        <span className={cn('transition-colors', activeTab === tab.id ? 'text-[#d8b4fe]' : 'text-[#a78bfa]')}>
                                            {tab.icon}
                                        </span>
                                        <span
                                            className={cn(
                                                'text-sm font-medium tracking-wider uppercase',
                                                activeTab === tab.id ? 'text-[#d8b4fe]' : 'text-[#a78bfa]',
                                            )}
                                            style={{ fontFamily: 'Rajdhani, sans-serif' }}
                                        >
                                            {tab.label}
                                        </span>
                                        {activeTab === tab.id && <div className="absolute right-2 bottom-0 left-2 h-0.5 rounded-full bg-[#d946ef]" />}
                                    </button>
                                ))}
                            </div>

                            {/* Desktop Tabs */}
                            <div className="hidden flex-col space-y-1 lg:flex">
                                {tabs.map((tab) => (
                                    <button
                                        key={tab.id}
                                        onClick={() => setActiveTab(tab.id)}
                                        className={cn(
                                            'relative flex w-full items-center gap-3 overflow-hidden rounded-lg px-4 py-3 text-left transition-all duration-300',
                                            activeTab === tab.id
                                                ? 'border-l-2 border-[#d946ef] bg-[rgba(168,85,247,0.18)]'
                                                : `border-l-2 border-transparent hover:bg-[rgba(168,85,247,${hasParentBackground ? '0.1' : '0.08'})]`,
                                        )}
                                    >
                                        <span className={cn('transition-colors', activeTab === tab.id ? 'text-[#d8b4fe]' : 'text-[#a78bfa]')}>
                                            {tab.icon}
                                        </span>
                                        <span
                                            className={cn(
                                                'text-sm font-medium tracking-wider uppercase',
                                                activeTab === tab.id ? 'text-[#d8b4fe]' : 'text-[#a78bfa]',
                                            )}
                                            style={{ fontFamily: 'Rajdhani, sans-serif' }}
                                        >
                                            {tab.label}
                                        </span>
                                        {activeTab === tab.id && <div className="absolute right-2 h-1.5 w-1.5 rounded-full bg-[#d946ef]" />}
                                    </button>
                                ))}
                            </div>
                        </div>

                        <div
                            ref={contentAnim.ref}
                            className="lg:col-span-9"
                            style={{
                                opacity: contentAnim.isVisible ? 1 : 0,
                                transform: contentAnim.isVisible ? 'translateX(0)' : 'translateX(30px)',
                                transition: 'opacity 0.8s ease, transform 0.8s ease',
                            }}
                        >
                            <div
                                className="min-h-[400px] rounded-xl border p-6"
                                style={{
                                    background: hasParentBackground ? 'rgba(15,5,34,0.92)' : 'rgba(15,5,34,0.9)',
                                    borderColor: 'rgba(168,85,247,0.3)',
                                }}
                            >
                                {renderContent()}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    );
}
