import React, { useState } from 'react';
import {
  Sparkles,
  Briefcase,
  Video,
  Rocket,
  ShoppingBag,
  Code,
  Building,
  Cpu,
  Gamepad2,
  Newspaper,
  GraduationCap,
  Award,
  Share2,
  MoreHorizontal,
  ChevronDown,
  Search,
  X
} from 'lucide-react';
import { useApp } from '../context/AppContext';
import { Category } from '../types';

// Dynamic Icon Resolver
export const getCategoryIcon = (iconName?: string) => {
  const iconClass = "w-3.5 h-3.5";
  switch (iconName?.toLowerCase()) {
    case 'briefcase': return <Briefcase className={iconClass} />;
    case 'video': return <Video className={iconClass} />;
    case 'sparkles': return <Sparkles className={iconClass} />;
    case 'rocket': return <Rocket className={iconClass} />;
    case 'shoppingbag':
    case 'shopping-bag': return <ShoppingBag className={iconClass} />;
    case 'code': return <Code className={iconClass} />;
    case 'building': return <Building className={iconClass} />;
    case 'cpu': return <Cpu className={iconClass} />;
    case 'gamepad2':
    case 'gaming': return <Gamepad2 className={iconClass} />;
    case 'newspaper':
    case 'media': return <Newspaper className={iconClass} />;
    case 'graduationcap':
    case 'education': return <GraduationCap className={iconClass} />;
    case 'award':
    case 'brand': return <Award className={iconClass} />;
    case 'share2':
    case 'social': return <Share2 className={iconClass} />;
    default: return <Sparkles className={iconClass} />;
  }
};

export const CategoryNav: React.FC = () => {
  const {
    categories,
    listings,
    state,
    texts,
    t,
    tCategory,
    tNum,
    setSelectedCategory,
    openCategoryModal
  } = useApp();

  const scrollContainerRef = React.useRef<HTMLDivElement>(null);
  const [showLeftGradient, setShowLeftGradient] = useState(false);
  const [showRightGradient, setShowRightGradient] = useState(true);

  const activeCategories = categories
    .filter(c => c.is_active && c.slug !== 'all')
    .sort((a, b) => a.display_order - b.display_order);

  // Check scroll position to dynamically show/hide fade gradients
  const handleScroll = () => {
    if (!scrollContainerRef.current) return;
    const { scrollLeft, scrollWidth, clientWidth } = scrollContainerRef.current;
    setShowLeftGradient(scrollLeft > 10);
    setShowRightGradient(scrollLeft < scrollWidth - clientWidth - 10);
  };

  // Convert vertical mouse wheel to horizontal scrolling for desktop users
  const handleWheel = (e: React.WheelEvent<HTMLDivElement>) => {
    if (scrollContainerRef.current && Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
      scrollContainerRef.current.scrollLeft += e.deltaY;
    }
  };

  React.useEffect(() => {
    handleScroll();
  }, [activeCategories.length]);

  return (
    <div id="category-navigation-bar" className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 mt-2 mb-6">
      <div className="flex items-center gap-2 relative">
        {/* Horizontally Scrollable Category Container */}
        <div className="relative flex-1 min-w-0">
          {/* Left subtle fade mask */}
          {showLeftGradient && (
            <div
              className="pointer-events-none absolute left-0 top-0 bottom-0 w-6 sm:w-8 z-10 transition-opacity duration-200"
              style={{
                background: 'linear-gradient(to right, var(--bg-color, #0A0D0F), transparent)'
              }}
            />
          )}

          {/* Scrollable Pills Row */}
          <div
            ref={scrollContainerRef}
            onScroll={handleScroll}
            onWheel={handleWheel}
            className="flex items-center gap-1.5 overflow-x-auto no-scrollbar py-1.5 px-0.5 scroll-smooth select-none"
          >
            {/* "ALL" Category Pill */}
            <button
              id="cat-pill-all"
              onClick={() => setSelectedCategory('all')}
              className={`flex items-center gap-1.5 px-3 sm:px-3.5 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all shrink-0 cursor-pointer ${
                state.selectedCategory === 'all'
                  ? 'bg-emerald-600 text-white shadow-sm shadow-emerald-950/30'
                  : 'border hover:opacity-90'
              }`}
              style={
                state.selectedCategory === 'all'
                  ? {}
                  : {
                      backgroundColor: 'var(--sub-card-bg, #141A20)',
                      borderColor: 'var(--border-color, #222A33)',
                      color: 'var(--muted-text-color, #8A99A8)'
                    }
              }
            >
              <Sparkles className="w-3.5 h-3.5" />
              <span>{t('cat_all', undefined, texts.category_all || 'ALL')}</span>
              <span className="text-[10px] px-1.5 py-0.2 rounded-full bg-black/20 dark:bg-black/40 font-mono">
                {tNum(listings.filter(l => l.is_active).length)}
              </span>
            </button>

            {/* All Active Categories (User can scroll smoothly to explore all) */}
            {activeCategories.map(cat => {
              const isSelected = state.selectedCategory === cat.slug || state.selectedCategory === cat.id;
              const count = listings.filter(l => l.is_active && l.category_id === cat.id).length;
              const categoryName = tCategory(cat.slug || cat.id, cat.name);

              return (
                <button
                  key={cat.id}
                  id={`cat-pill-${cat.slug}`}
                  onClick={() => setSelectedCategory(cat.slug)}
                  className={`flex items-center gap-1.5 px-3 sm:px-3.5 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all shrink-0 cursor-pointer ${
                    isSelected
                      ? 'bg-emerald-600 text-white shadow-sm shadow-emerald-950/30'
                      : 'border hover:opacity-90'
                  }`}
                  style={
                    isSelected
                      ? {}
                      : {
                          backgroundColor: 'var(--sub-card-bg, #141A20)',
                          borderColor: 'var(--border-color, #222A33)',
                          color: 'var(--muted-text-color, #8A99A8)'
                        }
                  }
                >
                  {getCategoryIcon(cat.icon)}
                  <span>{categoryName}</span>
                  {count > 0 && (
                    <span className="text-[10px] px-1.5 py-0.2 rounded-full bg-black/20 dark:bg-black/40 font-mono">
                      {tNum(count)}
                    </span>
                  )}
                </button>
              );
            })}
          </div>

          {/* Right subtle fade mask */}
          {showRightGradient && (
            <div
              className="pointer-events-none absolute right-0 top-0 bottom-0 w-6 sm:w-8 z-10 transition-opacity duration-200"
              style={{
                background: 'linear-gradient(to left, var(--bg-color, #0A0D0F), transparent)'
              }}
            />
          )}
        </div>

        {/* Fixed "More v" Button on Right Side */}
        <div className="shrink-0 pl-1">
          <button
            id="btn-more-categories"
            onClick={openCategoryModal}
            className="flex items-center gap-1.5 px-3 sm:px-3.5 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap border hover:opacity-90 transition-all cursor-pointer shadow-sm"
            style={{
              backgroundColor: 'var(--sub-card-bg, #141A20)',
              borderColor: 'var(--border-color, #222A33)',
              color: 'var(--heading-color, #FFFFFF)'
            }}
          >
            <span>{t('cat_more', undefined, texts.category_more || 'More')}</span>
            <ChevronDown className="w-3.5 h-3.5 opacity-70" />
          </button>
        </div>
      </div>
    </div>
  );
};

// Modal for "More Categories" popup inspired by outbid.lol
export const CategoryModal: React.FC = () => {
  const {
    state,
    categories,
    listings,
    t,
    tCategory,
    tNum,
    setSelectedCategory,
    closeCategoryModal
  } = useApp();

  const [search, setSearch] = useState('');

  if (!state.isCategoryModalOpen) return null;

  const activeCategories = categories
    .filter(c => c.is_active && c.slug !== 'all')
    .sort((a, b) => a.display_order - b.display_order);

  const filtered = activeCategories.filter(c => {
    const localized = tCategory(c.slug || c.id, c.name).toLowerCase();
    const original = c.name.toLowerCase();
    const q = search.toLowerCase();
    return localized.includes(q) || original.includes(q);
  });

  return (
    <div
      className="fixed inset-0 z-50 overflow-y-auto bg-black/80 backdrop-blur-sm animate-in fade-in duration-150"
      onClick={closeCategoryModal}
    >
      <div className="flex min-h-full items-center justify-center p-3 sm:p-4 md:p-6 text-center">
        <div
          onClick={(e) => e.stopPropagation()}
          className="w-full max-w-lg rounded-2xl border p-4 sm:p-5 shadow-2xl space-y-4 my-auto text-left align-middle relative transform transition-all max-h-[92vh] sm:max-h-[90vh] md:max-h-[86vh] flex flex-col"
          style={{
            backgroundColor: 'var(--card-color, #13181D)',
            borderColor: 'var(--border-color, #2A3440)'
          }}
        >
        <div className="flex items-center justify-between">
          <h3
            className="font-bold text-base"
            style={{ color: 'var(--heading-color, #FFFFFF)' }}
          >
            {t('all_categories_modal_title', undefined, 'All Categories')}
          </h3>
          <button
            onClick={closeCategoryModal}
            className="p-1.5 rounded-lg text-slate-400 hover:text-slate-200 dark:hover:text-white cursor-pointer"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* Search Bar */}
        <div className="relative">
          <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
          <input
            type="text"
            placeholder={t('search_categories_placeholder', undefined, 'Search categories...')}
            value={search}
            onChange={e => setSearch(e.target.value)}
            className="w-full pl-9 pr-4 py-2 border rounded-xl text-sm placeholder-slate-500 focus:outline-none focus:border-emerald-500 transition-colors"
            style={{
              backgroundColor: 'var(--input-bg, #0A0D0F)',
              borderColor: 'var(--border-color, #222A33)',
              color: 'var(--text-color, #FFFFFF)'
            }}
          />
        </div>

        {/* Category Grid */}
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 max-h-72 overflow-y-auto pr-1">
          <button
            onClick={() => {
              setSelectedCategory('all');
              closeCategoryModal();
            }}
            className={`flex items-center justify-between p-2.5 rounded-xl border text-xs font-semibold transition-all cursor-pointer ${
              state.selectedCategory === 'all'
                ? 'bg-emerald-600 text-white border-emerald-500'
                : 'hover:opacity-90'
            }`}
            style={
              state.selectedCategory === 'all'
                ? {}
                : {
                    backgroundColor: 'var(--sub-card-bg, #141A20)',
                    borderColor: 'var(--border-color, #222A33)',
                    color: 'var(--text-color, #F0F4F8)'
                  }
            }
          >
            <div className="flex items-center gap-2">
              <Sparkles className="w-3.5 h-3.5" />
              <span>{t('cat_name_all', undefined, 'All Categories')}</span>
            </div>
            <span className="text-[10px] opacity-70 font-mono">
              {tNum(listings.filter(l => l.is_active).length)}
            </span>
          </button>

          {filtered.map(cat => {
            const isSelected = state.selectedCategory === cat.slug || state.selectedCategory === cat.id;
            const count = listings.filter(l => l.is_active && l.category_id === cat.id).length;
            const localizedCatName = tCategory(cat.slug || cat.id, cat.name);

            return (
              <button
                key={cat.id}
                onClick={() => {
                  setSelectedCategory(cat.slug);
                  closeCategoryModal();
                }}
                className={`flex items-center justify-between p-2.5 rounded-xl border text-xs font-semibold transition-all text-left cursor-pointer ${
                  isSelected
                    ? 'bg-emerald-600 text-white border-emerald-500'
                    : 'hover:opacity-90'
                }`}
                style={
                  isSelected
                    ? {}
                    : {
                        backgroundColor: 'var(--sub-card-bg, #141A20)',
                        borderColor: 'var(--border-color, #222A33)',
                        color: 'var(--text-color, #F0F4F8)'
                      }
                }
              >
                <div className="flex items-center gap-2 truncate">
                  {getCategoryIcon(cat.icon)}
                  <span className="truncate">{localizedCatName}</span>
                </div>
                <span className="text-[10px] opacity-70 font-mono ml-1">
                  {tNum(count)}
                </span>
              </button>
            );
          })}
        </div>
        </div>
      </div>
    </div>
  );
};
