import React, { useState, useEffect, useRef } from 'react';
import { Link } from '@inertiajs/react';
import { Dialog, DialogContent, DialogTitle } from "@/Components/ui/dialog";
import { ChevronRight, ChevronLeft, X, LayoutGrid } from "lucide-react";
import { VisuallyHidden } from '@radix-ui/react-visually-hidden';
import { useTranslation } from '@/hooks/useTranslation';

export default function CategoryModal({ isOpen, onClose, categories, initialCategoryId = null }) {
    const { t } = useTranslation();
    const [activeId, setActiveId] = useState(null);

    const scrollRef = useRef(null);
    const [showLeftArrow, setShowLeftArrow] = useState(false);
    const [showRightArrow, setShowRightArrow] = useState(true);

    const checkScroll = () => {
        if (scrollRef.current) {
            const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
            setShowLeftArrow(scrollLeft > 0);
            setShowRightArrow(Math.ceil(scrollLeft + clientWidth) < scrollWidth - 5);
        }
    };

    useEffect(() => {
        if (isOpen) {
            if (initialCategoryId) {
                setActiveId(initialCategoryId);
            } else if (categories && categories.length > 0) {
                setActiveId(categories[0].id);
            }
            setTimeout(checkScroll, 100);
        }
    }, [isOpen, initialCategoryId, categories]);

    useEffect(() => {
        window.addEventListener('resize', checkScroll);
        return () => window.removeEventListener('resize', checkScroll);
    }, []);

    const scroll = (direction) => {
        if (scrollRef.current) {
            const offset = direction === 'left' ? -200 : 200;
            scrollRef.current.scrollBy({ left: offset, behavior: 'smooth' });
            setTimeout(checkScroll, 300);
        }
    };

    const activeCategory = categories?.find(c => c.id === activeId) || categories?.[0];

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className="!max-w-[1200px] xl:!max-w-[1400px] !w-[95vw] p-0 overflow-hidden h-[90vh] sm:h-[85vh] flex flex-col sm:flex-row rounded-2xl bg-card border-none shadow-2xl gap-0 [&>button]:hidden">
                
                <VisuallyHidden>
                    <DialogTitle>{t('All Categories')}</DialogTitle>
                </VisuallyHidden>

                <div className="sm:hidden relative w-full border-b border-border/50 bg-card shrink-0">
                    {showLeftArrow && (
                        <button 
                            onClick={() => scroll('left')}
                            className="absolute left-0 top-0 bottom-0 z-10 w-10 bg-gradient-to-r from-card via-card to-transparent flex items-center justify-start pl-1 text-primary"
                        >
                            <ChevronLeft className="w-6 h-6 animate-pulse" />
                        </button>
                    )}

                    <div 
                        ref={scrollRef}
                        onScroll={checkScroll}
                        className="flex overflow-x-auto no-scrollbar px-2 py-3 snap-x scroll-smooth"
                    >
                        <div className="flex w-max gap-2 px-2">
                            {categories?.map((cat) => {
                                const isActive = activeId === cat.id;
                                return (
                                    <button
                                        key={cat.id}
                                        onClick={() => setActiveId(cat.id)}
                                        className={`px-4 py-2 rounded-full whitespace-nowrap text-sm font-bold transition-all snap-center shrink-0 border ${
                                            isActive 
                                                ? 'bg-primary text-primary-foreground border-primary shadow-md' 
                                                : 'bg-muted/50 text-muted-foreground border-transparent hover:bg-muted'
                                        }`}
                                    >
                                        {t(cat.name)}
                                    </button>
                                );
                            })}
                        </div>
                    </div>

                    {showRightArrow && (
                        <button 
                            onClick={() => scroll('right')}
                            className="absolute right-0 top-0 bottom-0 z-10 w-10 bg-gradient-to-l from-card via-card to-transparent flex items-center justify-end pr-1 text-primary"
                        >
                            <ChevronRight className="w-6 h-6 animate-pulse" />
                        </button>
                    )}
                </div>

                <div className="hidden sm:flex flex-col w-72 lg:w-80 bg-muted/20 border-r border-border/50 h-full overflow-hidden shrink-0">
                    <div className="p-6 pb-2 shrink-0">
                        <h3 className="font-black text-xl text-foreground">{t('Categories')}</h3>
                    </div>
                    <div className="flex-1 overflow-y-auto no-scrollbar p-4 pt-0">
                        <div className="flex flex-col gap-1">
                            {categories?.map((cat) => {
                                const isActive = activeId === cat.id;
                                return (
                                    <button
                                        key={cat.id}
                                        onClick={() => setActiveId(cat.id)}
                                        className={`flex items-center justify-between w-full py-3.5 px-4 rounded-xl transition-all text-sm group outline-none ${
                                            isActive 
                                                ? 'bg-background dark:bg-zinc-900 font-bold text-primary shadow-sm border border-border/50' 
                                                : 'text-muted-foreground hover:bg-muted/50 hover:text-foreground border border-transparent'
                                        }`}
                                    >
                                        <span className="flex items-center gap-3">
                                            {cat.image_path ? (
                                                <img 
                                                    src={`/storage/${cat.image_path}`} 
                                                    className={`w-6 h-6 object-contain transition-all ${isActive ? 'grayscale-0 opacity-100' : 'grayscale opacity-60 group-hover:grayscale-0 group-hover:opacity-100'}`} 
                                                    alt="" 
                                                />
                                            ) : (
                                                <LayoutGrid className={`w-5 h-5 transition-all ${isActive ? 'text-primary' : 'opacity-60 group-hover:opacity-100'}`} />
                                            )}
                                            <span className="truncate text-left">{t(cat.name)}</span>
                                        </span>
                                        <ChevronRight className={`w-4 h-4 shrink-0 transition-all ${isActive ? 'opacity-100 translate-x-1' : 'opacity-0 -translate-x-2 group-hover:opacity-50 group-hover:translate-x-0'}`} />
                                    </button>
                                );
                            })}
                        </div>
                    </div>
                </div>

                <div className="flex-1 h-full overflow-y-auto bg-background relative flex flex-col">
                    <button 
                        onClick={onClose}
                        className="absolute top-4 right-4 sm:top-6 sm:right-6 z-20 w-10 h-10 rounded-full bg-muted/50 hover:bg-muted flex items-center justify-center transition-colors"
                    >
                        <X className="w-5 h-5 text-foreground/70 hover:text-foreground" />
                    </button>

                    <div className="p-4 sm:p-8 lg:p-12 flex-1">
                        <div className="flex flex-col sm:flex-row sm:items-end justify-between mb-8 sm:pr-12 gap-2 border-b sm:border-none pb-4 sm:pb-0">
                            <h2 className="text-xl sm:text-3xl font-black text-foreground tracking-tight">
                                {t(activeCategory?.name)}
                            </h2>
                            <Link 
                                href={route('search.index', { q: activeCategory?.name })} 
                                onClick={onClose}
                                className="text-sm font-bold text-primary hover:underline flex items-center gap-1"
                            >
                                {t('Browse featured selections')} <ChevronRight className="w-4 h-4" />
                            </Link>
                        </div>

                        {activeCategory?.subcategories?.length > 0 ? (
                            <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 lg:grid-cols-6 xl:grid-cols-7 gap-x-4 gap-y-8">
                                {activeCategory.subcategories.map(sub => (
                                    <Link 
                                        key={sub.id} 
                                        href={route('category.show', sub.slug)}
                                        onClick={onClose}
                                        className="flex flex-col items-center gap-3 group text-center"
                                    >
                                        <div className="w-20 h-20 sm:w-24 sm:h-24 rounded-full bg-muted/10 border border-border/50 flex items-center justify-center overflow-hidden group-hover:border-primary group-hover:shadow-lg transition-all p-3">
                                            {sub.image_path ? (
                                                <img 
                                                    src={`/storage/${sub.image_path}`} 
                                                    alt={sub.name} 
                                                    className="w-full h-full object-contain group-hover:scale-110 transition-transform duration-500" 
                                                />
                                            ) : (
                                                <LayoutGrid className="w-8 h-8 text-muted-foreground/30" />
                                            )}
                                        </div>
                                        <span className="text-xs sm:text-sm font-bold text-foreground/80 group-hover:text-primary line-clamp-2 px-1 leading-snug">
                                            {t(sub.name)}
                                        </span>
                                    </Link>
                                ))}
                            </div>
                        ) : (
                            <div className="flex flex-col items-center justify-center h-64 text-muted-foreground border-2 border-dashed rounded-3xl bg-muted/10">
                                <LayoutGrid className="w-12 h-12 opacity-20 mb-3" />
                                <p className="text-base font-bold text-foreground/60">{t('No subcategories found.')}</p>
                                <p className="text-sm mt-1">{t('Try browsing the parent category directly.')}</p>
                            </div>
                        )}
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    );
}