import { useState, useMemo } from 'react';
import { Filter, ChevronDown, Search, X } from 'lucide-react';
import { type Achievement } from '../data';
import { useData } from '../context/DataContext';
import AchievementCard from './AchievementCard';
import AchievementModal from './AchievementModal';
import { useLang } from '../context/LanguageContext';

const INITIAL_COUNT = 3;
const LOAD_MORE_COUNT = 3;

export default function AchievementGrid() {
  const { t } = useLang();
  const { achievements, loading, error, refetch } = useData();
  const [searchQuery, setSearchQuery] = useState('');
  const [filterLevel, setFilterLevel] = useState('');
  const [filterCategory, setFilterCategory] = useState('');
  const [filterYear, setFilterYear] = useState('');
  const [visibleCount, setVisibleCount] = useState(INITIAL_COUNT);
  const [selectedAchievement, setSelectedAchievement] = useState<Achievement | null>(null);

  // Derive unique categories and years from data
  const categories = useMemo(
    () => [...new Set(achievements.map((a) => a.category))].sort(),
    [achievements]
  );
  const years = useMemo(
    () => [...new Set(achievements.map((a) => a.year))].sort((a: number, b: number) => b - a),
    [achievements]
  );

  // Filter + search logic
  const filtered = useMemo(() => {
    const q = searchQuery.toLowerCase().trim();
    return achievements.filter((a) => {
      const matchSearch =
        !q ||
        a.title.toLowerCase().includes(q) ||
        a.team.toLowerCase().includes(q) ||
        a.category.toLowerCase().includes(q) ||
        a.competition.toLowerCase().includes(q);
      const matchLevel = !filterLevel || a.level === filterLevel;
      const matchCategory = !filterCategory || a.category === filterCategory;
      const matchYear = !filterYear || String(a.year) === filterYear;
      return matchSearch && matchLevel && matchCategory && matchYear;
    });
  }, [searchQuery, filterLevel, filterCategory, filterYear, achievements]);

  const visible = filtered.slice(0, visibleCount);
  const hasMore = visibleCount < filtered.length;
  const isFiltered = searchQuery || filterLevel || filterCategory || filterYear;

  const resetFilters = () => {
    setSearchQuery('');
    setFilterLevel('');
    setFilterCategory('');
    setFilterYear('');
    setVisibleCount(INITIAL_COUNT);
  };

  const handleFilterChange = (setter: (v: string) => void) => (v: string) => {
    setter(v);
    setVisibleCount(INITIAL_COUNT);
  };

  const handleLoadMore = () => setVisibleCount((prev) => prev + LOAD_MORE_COUNT);

  const handleShowLess = () => {
    setVisibleCount(INITIAL_COUNT);
    document.getElementById('achievement-grid-section')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <>
      {/* Achievement Modal */}
      <AchievementModal achievement={selectedAchievement} onClose={() => setSelectedAchievement(null)} />

      <section id="achievement-grid-section" className="py-8 bg-white">
        {/* Section header */}
        <div className="max-w-7xl mx-auto px-4 lg:px-8 mb-8">
          <h2 className="text-3xl md:text-4xl font-black font-display text-primary-navy mb-2">
            {t.achievement.sectionTitle}
          </h2>
          <p className="text-slate-500 text-base max-w-2xl">
            {t.achievement.sectionDesc}
          </p>
        </div>

        <div className="max-w-7xl mx-auto px-4 lg:px-8">
          {/* Filter + Search Section */}
          <div className="bg-white/80 backdrop-blur-md p-4 rounded-lg shadow-sm border-t-4 border-primary-gold mb-8 space-y-3">
            {/* Row 1: Label + Reset */}
            <div className="flex items-center justify-between">
              <div className="text-base font-bold font-display text-primary-navy flex items-center gap-2">
                <Filter className="text-primary-navy" size={18} />
                {t.achievement.filterTitle}
              </div>
              {isFiltered && (
                <button
                  onClick={resetFilters}
                  className="flex items-center gap-1 text-xs font-bold text-slate-500 hover:text-primary-navy transition-colors"
                >
                  <X size={13} />
                  {t.achievement.resetFilter}
                </button>
              )}
            </div>

            {/* Row 2: Search bar */}
            <div className="relative">
              <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
              <input
                id="search-achievement"
                type="text"
                value={searchQuery}
                onChange={(e) => { setSearchQuery(e.target.value); setVisibleCount(INITIAL_COUNT); }}
                placeholder={t.achievement.searchPlaceholder}
                className="w-full bg-slate-50 text-slate-700 text-sm rounded py-2 pl-9 pr-4 border border-slate-200 focus:outline-none focus:ring-2 focus:ring-primary-gold"
              />
              {searchQuery && (
                <button
                  onClick={() => { setSearchQuery(''); setVisibleCount(INITIAL_COUNT); }}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
                  aria-label="Hapus pencarian"
                >
                  <X size={14} />
                </button>
              )}
            </div>

            {/* Row 3: Dropdowns */}
            <div className="flex flex-wrap gap-3">
              {/* Level Filter */}
              <div className="relative flex-1 min-w-[130px]">
                <select
                  id="filter-level"
                  value={filterLevel}
                  onChange={(e) => handleFilterChange(setFilterLevel)(e.target.value)}
                  className="w-full bg-slate-50 text-slate-700 font-bold text-sm rounded py-2 pl-4 pr-9 shadow-sm focus:ring-2 focus:ring-primary-gold appearance-none cursor-pointer border border-slate-200"
                >
                  <option value="">{t.achievement.allLevel}</option>
                  <option value="Internasional">Internasional</option>
                  <option value="Nasional">Nasional</option>
                  <option value="Regional">Regional</option>
                </select>
                <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
              </div>

              {/* Category Filter */}
              <div className="relative flex-1 min-w-[130px]">
                <select
                  id="filter-category"
                  value={filterCategory}
                  onChange={(e) => handleFilterChange(setFilterCategory)(e.target.value)}
                  className="w-full bg-slate-50 text-slate-700 font-bold text-sm rounded py-2 pl-4 pr-9 shadow-sm focus:ring-2 focus:ring-primary-gold appearance-none cursor-pointer border border-slate-200"
                >
                  <option value="">{t.achievement.allField}</option>
                  {categories.map((cat) => (
                    <option key={cat} value={cat}>{cat}</option>
                  ))}
                </select>
                <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
              </div>

              {/* Year Filter */}
              <div className="relative flex-1 min-w-[100px]">
                <select
                  id="filter-year"
                  value={filterYear}
                  onChange={(e) => handleFilterChange(setFilterYear)(e.target.value)}
                  className="w-full bg-slate-50 text-slate-700 font-bold text-sm rounded py-2 pl-4 pr-9 shadow-sm focus:ring-2 focus:ring-primary-gold appearance-none cursor-pointer border border-slate-200"
                >
                  <option value="">{t.achievement.allYear}</option>
                  {years.map((yr) => (
                    <option key={yr} value={String(yr)}>{yr}</option>
                  ))}
                </select>
                <ChevronDown size={14} className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
              </div>
            </div>
          </div>

          {/* Results count */}
          {isFiltered && (
            <p className="text-sm text-slate-500 font-medium mb-6">
              {t.achievement.showing}{' '}
              <span className="font-bold text-primary-navy">{filtered.length}</span>{' '}
              {t.achievement.matching}
            </p>
          )}

          {/* Grid */}
          {loading ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10">
              {[1, 2, 3].map((n) => (
                <div key={n} className="bg-white rounded-lg border border-slate-200 overflow-hidden shadow-sm animate-pulse">
                  <div className="h-52 bg-slate-200 w-full" />
                  <div className="p-6 space-y-4">
                    <div className="h-4 bg-slate-200 rounded w-1/4" />
                    <div className="h-6 bg-slate-200 rounded w-3/4" />
                    <div className="h-4 bg-slate-200 rounded w-5/6" />
                    <div className="h-4 bg-slate-200 rounded w-2/3" />
                    <div className="h-10 bg-slate-200 rounded w-1/3 mt-4" />
                  </div>
                </div>
              ))}
            </div>
          ) : error ? (
            <div className="text-center py-20 text-red-500">
              <p className="text-lg font-semibold">Gagal memuat data</p>
              <p className="text-sm mt-1">{error}</p>
              <button
                onClick={refetch}
                className="mt-4 px-4 py-2 bg-primary-navy text-white font-bold rounded hover:bg-opacity-95 transition-all text-sm"
              >
                Coba Lagi
              </button>
            </div>
          ) : visible.length === 0 ? (
            <div className="text-center py-20 text-slate-400">
              <p className="text-lg font-semibold">{t.achievement.noData}</p>
              <p className="text-sm mt-1">{t.achievement.noDataSub}</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10">
              {visible.map((achievement) => (
                <div key={achievement.id} className="animate-fade-in">
                  <AchievementCard
                    achievement={achievement}
                    onReadMore={(a) => setSelectedAchievement(a)}
                  />
                </div>
              ))}
            </div>
          )}

          {/* Load More / Show Less */}
          <div className="mt-20 flex flex-wrap items-center justify-center gap-6">
            {hasMore && (
              <button
                id="load-more-achievement"
                onClick={handleLoadMore}
                className="text-primary-navy font-black text-lg underline underline-offset-[12px] decoration-primary-gold decoration-4 hover:text-primary-gold transition-colors flex items-center gap-2"
              >
                {t.achievement.loadMore}
                <ChevronDown size={20} />
              </button>
            )}

            {!hasMore && visible.length > 0 && filtered.length > INITIAL_COUNT && (
              <p className="text-slate-400 text-sm font-medium">
                {t.achievement.showing} {filtered.length} {t.achievement.allShown}
              </p>
            )}

            {visibleCount > INITIAL_COUNT && visible.length > 0 && (
              <button
                onClick={handleShowLess}
                className="text-slate-400 font-bold text-sm underline underline-offset-4 decoration-slate-300 decoration-2 hover:text-slate-600 transition-colors flex items-center gap-1.5"
              >
                <ChevronDown size={16} className="rotate-180" />
                {t.achievement.showLess}
              </button>
            )}
          </div>
        </div>
      </section>
    </>
  );
}
