"use client";
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { SearchBar } from '@/components/SearchBar';
import { LevelTabs } from '@/components/LevelTabs';
import { AlphabetFilter } from '@/components/AlphabetFilter';
import { WordCard } from '@/components/WordCard';
import Link from 'next/link';

export default function DashboardPage() {
  const [activeLevel, setActiveLevel] = useState('A1');
  const [searchQuery, setSearchQuery] = useState('');
  const [activeLetter, setActiveLetter] = useState('');
  
  const [vocabularies, setVocabularies] = useState<any[]>([]);
  const [progressData, setProgressData] = useState<any>({});
  
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [nextCursor, setNextCursor] = useState<number | null>(null);
  
  const [isPremium, setIsPremium] = useState(true); // Default to true, will update based on auth API or error
  const [totalWords, setTotalWords] = useState(0);
  
  const observerTarget = useRef(null);

  const [levelStats, setLevelStats] = useState<any>({});
  const [quote, setQuote] = useState({ text: '', author: '' });

  // Fetch Progress, Config & User Data
  useEffect(() => {
    const fetchDashboardData = async () => {
      try {
        const [progRes, confRes] = await Promise.all([
          fetch('/api/progress'),
          fetch('/api/config')
        ]);
        
        if (progRes.ok) {
          const data = await progRes.json();
          const progressMap: any = {};
          if (data.data) {
            data.data.forEach((id: number) => {
              progressMap[id] = true;
            });
          }
          setProgressData(progressMap);
          if (data.stats) {
            setLevelStats(data.stats);
          }
        }
        
        if (confRes.ok) {
           const confData = await confRes.json();
           if (confData.data) {
             setQuote({
               text: confData.data.quoteText,
               author: confData.data.quoteAuthor
             });
           }
        }
      } catch (e) {
        console.error(e);
      }
    };
    fetchDashboardData();
  }, []);

  // Fetch Vocabs Function
  const fetchVocabularies = async (level: string, query: string, letter: string) => {
    try {
      setLoading(true);

      const params = new URLSearchParams({
        level,
        search: query,
        letter,
        limit: '5000' // Load all at once
      });

      const res = await fetch(`/api/vocabulary?${params.toString()}`);
      
      if (res.status === 403 || res.status === 401) {
        // Locked or not logged in
        setIsPremium(false);
        setVocabularies([]);
        return;
      }
      
      if (res.ok) {
        const data = await res.json();
        setIsPremium(true);
        setVocabularies(data.data);
        // Set an arbitrary total for progress bar for now if not provided
        setTotalWords(level === 'A1' ? 1847 : 1000); 
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  // Reset and Fetch on Filter Change
  useEffect(() => {
    fetchVocabularies(activeLevel, searchQuery, activeLetter);
  }, [activeLevel, searchQuery, activeLetter]);

  // Handlers
  const handleToggleLearned = async (id: number, currentStatus: boolean) => {
    setProgressData((prev: any) => ({ ...prev, [id]: !currentStatus }));
    
    // Optimistic UI, fire API in background
    try {
      await fetch('/api/progress', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          vocabularyId: id,
          status: !currentStatus ? 'LEARNED' : 'NOT_LEARNED'
        })
      });
    } catch (e) {
      // Revert if failed
      setProgressData((prev: any) => ({ ...prev, [id]: currentStatus }));
    }
  };

  const handleSelectLevel = (lvl: string) => {
    setActiveLevel(lvl);
    setSearchQuery('');
    setActiveLetter('');
  };

  const levels = [
    { id: 'A1', isLocked: false, progress: levelStats['A1'] },
    { id: 'A2', isLocked: false, progress: levelStats['A2'] },
    { id: 'B1', isLocked: false, progress: levelStats['B1'] },
    { id: 'B2', isLocked: false, progress: levelStats['B2'] },
    { id: 'C1', isLocked: false, progress: levelStats['C1'] },
    { id: 'C2', isLocked: false, progress: levelStats['C2'] }
  ];

  // Calculate learned stats
  const learnedCount = vocabularies.filter(v => progressData[v.id]).length;
  // This is just a proxy for the demo, since we don't have absolute totals per level from API yet
  const totalDisplay = totalWords > 0 ? totalWords : vocabularies.length;
  const percent = totalDisplay > 0 ? Math.round((learnedCount / totalDisplay) * 100) : 0;

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      <SearchBar initialQuery={searchQuery} onSearch={setSearchQuery} />
      
      <main className="flex-1 w-full max-w-5xl mx-auto px-6 py-8">
        <LevelTabs levels={levels} activeLevel={activeLevel} onSelectLevel={handleSelectLevel} />
        <AlphabetFilter activeLetter={activeLetter} onSelectLetter={setActiveLetter} />

        {/* Quote of the Day */}
        {quote.text && (
          <div className="mb-6 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-2xl p-6 md:p-8 text-white shadow-lg relative overflow-hidden">
             <div className="absolute top-0 right-0 text-[120px] opacity-10 leading-none -mt-4 mr-2">"</div>
             <p className="text-xl md:text-2xl font-semibold italic mb-4 relative z-10 leading-relaxed">
               "{quote.text}"
             </p>
             <div className="text-blue-100 font-medium flex items-center gap-2">
                <span className="w-6 h-px bg-blue-200"></span>
                {quote.author}
             </div>
          </div>
        )}

        {/* Growth Hook CTA */}
        <div className="mb-8 flex justify-between items-center bg-white border border-gray-200 p-4 rounded-2xl shadow-sm">
          <div>
            <h4 className="font-bold text-gray-900 flex items-center gap-2">
              <span className="text-xl">✨</span> Coba mode Flashcard
            </h4>
            <p className="text-sm text-gray-600 mt-1">Hafal lebih cepat dengan mode kartu interaktif.</p>
          </div>
          <Link href="/flashcard" className="bg-gray-900 hover:bg-black text-white font-bold py-2 px-5 rounded-full text-sm transition-colors shadow-sm">
            Mulai Sesi
          </Link>
        </div>


            {/* Progress Bar (Absolute + Percentage) */}
            <div className="mb-8">
              <div className="flex justify-between items-end mb-2">
                <h2 className="text-2xl font-black text-gray-900 tracking-tight">Kosakata {activeLevel}</h2>
                <span className="text-sm font-bold text-gray-600">
                  {learnedCount} dari {totalDisplay} kata dihafal ({percent}%)
                </span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-3 overflow-hidden shadow-inner">
                <div className="bg-green-500 h-3 rounded-full transition-all duration-1000 ease-out" style={{ width: `${percent}%` }}></div>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {vocabularies.map((vocab) => (
                <WordCard 
                  key={vocab.id}
                  vocabulary={vocab}
                  isLocked={false}
                  isLearned={!!progressData[vocab.id]}
                  onToggleLearned={handleToggleLearned}
                />
              ))}
              
              {loading && vocabularies.length === 0 && Array.from({ length: 9 }).map((_, i) => (
                <div key={i} className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 h-[180px] animate-pulse">
                  <div className="flex justify-between items-start mb-3">
                    <div className="h-6 bg-gray-200 rounded w-2/3"></div>
                    <div className="h-4 bg-gray-200 rounded w-10"></div>
                  </div>
                  <div className="h-4 bg-gray-200 rounded w-1/2 mb-2"></div>
                  <div className="h-4 bg-gray-200 rounded w-1/3 mb-4"></div>
                  <div className="mt-auto pt-4 border-t border-gray-100 flex justify-between items-end">
                    <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                    <div className="h-10 w-10 bg-gray-200 rounded-full"></div>
                  </div>
                </div>
              ))}
            </div>

            {!loading && vocabularies.length === 0 && (
              <div className="text-center py-20">
                <div className="text-6xl mb-4 opacity-50">🔍</div>
                <h3 className="text-xl font-bold text-gray-700">Kata tidak ditemukan</h3>
                <p className="text-gray-500 mt-2">Coba gunakan kata kunci atau huruf lain.</p>
                <button 
                  onClick={() => { setSearchQuery(''); setActiveLetter(''); }}
                  className="mt-6 text-blue-600 font-bold hover:underline"
                >
                  Reset Pencarian
                </button>
              </div>
            )}

      </main>
    </div>
  );
}
