import { useState, useEffect } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Book, ChevronRight, FileText, Settings, Layers, Puzzle, Menu, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import DocContent from './DocContent';
import type { DocSection } from './types';

const iconMap: Record<string, React.ReactNode> = {
    'book-open': <Book className="w-4 h-4" />,
    'file-text': <FileText className="w-4 h-4" />,
    'settings': <Settings className="w-4 h-4" />,
    'layers': <Layers className="w-4 h-4" />,
    'puzzle': <Puzzle className="w-4 h-4" />,
};

export default function Help() {
    const [searchParams, setSearchParams] = useSearchParams();
    const [sections, setSections] = useState<DocSection[]>([]);
    const [loading, setLoading] = useState(true);
    const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({});
    const [sidebarOpen, setSidebarOpen] = useState(false);

    const currentSlug = searchParams.get('doc') || 'getting-started';

    // Fetch documentation registry
    useEffect(() => {
        const fetchDocs = async () => {
            try {
                const nonce = (window as any).WNW_CONFIG?.nonce || (window as any).wpApiSettings?.nonce || '';
                const response = await fetch('/wp-json/woonoow/v1/docs', {
                    credentials: 'include',
                    headers: {
                        'X-WP-Nonce': nonce,
                    },
                });
                const data = await response.json();

                if (data.success) {
                    setSections(data.sections);
                    const expanded: Record<string, boolean> = {};
                    data.sections.forEach((section: DocSection) => {
                        expanded[section.key] = true;
                    });
                    setExpandedSections(expanded);
                }
            } catch (error) {
                console.error('Failed to fetch docs:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchDocs();
    }, []);

    const toggleSection = (key: string) => {
        setExpandedSections(prev => ({
            ...prev,
            [key]: !prev[key],
        }));
    };

    const selectDoc = (slug: string) => {
        setSearchParams({ doc: slug });
        setSidebarOpen(false);
    };

    const isActive = (slug: string) => slug === currentSlug;

    return (
        <>
            {/* Mobile menu button */}
            <Button
                variant="ghost"
                size="icon"
                className="lg:hidden fixed bottom-20 right-4 z-50 bg-primary text-primary-foreground shadow-lg rounded-full w-12 h-12"
                onClick={() => setSidebarOpen(!sidebarOpen)}
            >
                {sidebarOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
            </Button>

            {/* Backdrop for mobile sidebar */}
            {sidebarOpen && (
                <div
                    className="fixed inset-0 bg-black/50 z-30 lg:hidden"
                    onClick={() => setSidebarOpen(false)}
                />
            )}

            {/* Mobile sidebar - fixed overlay */}
            <aside
                className={cn(
                    "lg:hidden fixed left-0 top-0 bottom-0 z-40 w-72 bg-background border-r overflow-y-auto",
                    sidebarOpen ? "block" : "hidden"
                )}
            >
                <SidebarContent
                    loading={loading}
                    sections={sections}
                    expandedSections={expandedSections}
                    toggleSection={toggleSection}
                    selectDoc={selectDoc}
                    isActive={isActive}
                />
            </aside>

            {/* Desktop layout - simple flexbox, no sticky */}
            <div className="hidden lg:flex gap-0">
                {/* Desktop sidebar - flex-shrink-0 keeps it visible */}
                <aside className="w-72 flex-shrink-0 border-r bg-muted/30 min-h-[600px]">
                    <SidebarContent
                        loading={loading}
                        sections={sections}
                        expandedSections={expandedSections}
                        toggleSection={toggleSection}
                        selectDoc={selectDoc}
                        isActive={isActive}
                    />
                </aside>

                {/* Desktop content */}
                <main className="flex-1 min-w-0">
                    <div className="max-w-4xl mx-auto py-6 px-10">
                        <DocContent slug={currentSlug} />
                    </div>
                </main>
            </div>

            {/* Mobile content - shown when sidebar is hidden */}
            <div className="lg:hidden">
                <div className="max-w-4xl mx-auto py-6 px-6">
                    <DocContent slug={currentSlug} />
                </div>
            </div>
        </>
    );
}

// Extracted sidebar content to avoid duplication
function SidebarContent({
    loading,
    sections,
    expandedSections,
    toggleSection,
    selectDoc,
    isActive,
}: {
    loading: boolean;
    sections: DocSection[];
    expandedSections: Record<string, boolean>;
    toggleSection: (key: string) => void;
    selectDoc: (slug: string) => void;
    isActive: (slug: string) => boolean;
}) {
    return (
        <>
            <div className="p-4 border-b bg-muted/30">
                <h2 className="text-lg font-semibold flex items-center gap-2">
                    <Book className="w-5 h-5" />
                    Documentation
                </h2>
                <p className="text-sm text-muted-foreground">Help & Guides</p>
            </div>

            <nav className="p-2">
                {loading ? (
                    <div className="p-4 text-sm text-muted-foreground">Loading...</div>
                ) : sections.length === 0 ? (
                    <div className="p-4 text-sm text-muted-foreground">No documentation available</div>
                ) : (
                    sections.map((section) => (
                        <div key={section.key} className="mb-2">
                            <button
                                onClick={() => toggleSection(section.key)}
                                className="w-full flex items-center gap-2 px-3 py-2 text-sm font-medium text-foreground hover:bg-muted rounded-md"
                            >
                                {iconMap[section.icon] || <FileText className="w-4 h-4" />}
                                <span className="flex-1 text-left">{section.label}</span>
                                <ChevronRight
                                    className={cn(
                                        "w-4 h-4 transition-transform",
                                        expandedSections[section.key] && "rotate-90"
                                    )}
                                />
                            </button>

                            {expandedSections[section.key] && (
                                <div className="ml-4 mt-1 space-y-1">
                                    {section.items.map((item) => (
                                        <button
                                            key={item.slug}
                                            onClick={() => selectDoc(item.slug)}
                                            className={cn(
                                                "w-full text-left px-3 py-1.5 text-sm rounded-md transition-colors",
                                                isActive(item.slug)
                                                    ? "bg-primary text-primary-foreground"
                                                    : "text-muted-foreground hover:bg-muted hover:text-foreground"
                                            )}
                                        >
                                            {item.title}
                                        </button>
                                    ))}
                                </div>
                            )}
                        </div>
                    ))
                )}
            </nav>
        </>
    );
}
