"use client";
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Link from 'next/link';

export default function FlashcardSession() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const source = searchParams.get('source') || 'unlearned';

  const [cards, setCards] = useState<any[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [loading, setLoading] = useState(true);
  const [flipped, setFlipped] = useState(false);
  const [animatingOut, setAnimatingOut] = useState<'left' | 'right' | null>(null);
  
  // Stats for summary
  const [learnedCount, setLearnedCount] = useState(0);
  const [unlearnedCount, setUnlearnedCount] = useState(0);

  // Swipe/Drag state
  const [dragOffset, setDragOffset] = useState(0);
  const touchStartRef = useRef<number | null>(null);
  const [hasStarted, setHasStarted] = useState(false);

  useEffect(() => {
    const fetchSession = async () => {
      try {
        const res = await fetch(`/api/flashcard/session?source=${source}`);
        if (res.status === 403) {
          router.push('/flashcard');
          return;
        }
        if (res.ok) {
          const data = await res.json();
          setCards(data.data);
        }
      } catch (e) {
        console.error(e);
      } finally {
        setLoading(false);
      }
    };
    fetchSession();
  }, [source, router]);

  // Autoplay audio when card appears, ONLY if session has started
  useEffect(() => {
    if (hasStarted && cards.length > 0 && currentIndex < cards.length) {
      const card = cards[currentIndex];
      if (card.audioUs) {
        const proxyUrl = `/api/audio?word=${encodeURIComponent(card.word)}&type=us`;
        const audio = new Audio(proxyUrl);
        audio.play().catch(err => console.error("Autoplay prevented:", err));
      }
    }
  }, [currentIndex, cards, hasStarted]);

  const handleAction = useCallback(async (isLearned: boolean) => {
    if (animatingOut || currentIndex >= cards.length) return;
    
    setAnimatingOut(isLearned ? 'right' : 'left');
    if (isLearned) setLearnedCount(c => c + 1);
    else setUnlearnedCount(c => c + 1);
    
    // API Call to save progress if LEARNED
    if (isLearned && cards[currentIndex]) {
      try {
        fetch('/api/progress', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            vocabularyId: cards[currentIndex].id,
            status: 'LEARNED'
          })
        }).catch(e => console.error("Gagal menyimpan progres"));
      } catch (e) {
        // Ignore
      }
    }

    setTimeout(() => {
      setFlipped(false);
      setCurrentIndex(prev => prev + 1);
      setAnimatingOut(null);
      setDragOffset(0);
    }, 250); // Wait for slide out animation
  }, [animatingOut, currentIndex, cards]);

  // Keyboard Navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (currentIndex >= cards.length || animatingOut) return;
      
      if (!hasStarted && e.code === 'Enter') {
        e.preventDefault();
        setHasStarted(true);
        return;
      }

      if (!hasStarted) return;

      if (!flipped) {
        if (e.code === 'Space' || e.code === 'ArrowUp' || e.code === 'Enter') {
          e.preventDefault();
          setFlipped(true);
        }
        return;
      }

      if (e.code === 'ArrowLeft') {
        e.preventDefault();
        handleAction(false);
      } else if (e.code === 'ArrowRight') {
        e.preventDefault();
        handleAction(true);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [flipped, currentIndex, cards.length, animatingOut, handleAction, hasStarted]);

  const playAudio = (e: React.MouseEvent, type: 'us' | 'uk', word: string, audioUrl: string | undefined) => {
    e.stopPropagation();
    const proxyUrl = `/api/audio?word=${encodeURIComponent(word)}&type=${type}`;
    const audio = new Audio(proxyUrl);
    audio.play().catch(err => console.error("Error playing audio", err));
  };

  // Touch Handlers for Swipe
  const handleTouchStart = (e: React.TouchEvent | React.MouseEvent) => {
    if (!flipped || animatingOut) return;
    const clientX = 'touches' in e ? e.touches[0].clientX : (e as React.MouseEvent).clientX;
    touchStartRef.current = clientX;
  };

  const handleTouchMove = (e: React.TouchEvent | React.MouseEvent) => {
    if (!flipped || animatingOut || touchStartRef.current === null) return;
    const clientX = 'touches' in e ? e.touches[0].clientX : (e as React.MouseEvent).clientX;
    const diff = clientX - touchStartRef.current;
    setDragOffset(diff);
  };

  const handleTouchEnd = () => {
    if (!flipped || touchStartRef.current === null) return;
    touchStartRef.current = null;
    
    // Threshold for swipe action (e.g. 100px)
    if (dragOffset > 100) {
      handleAction(true); // Swiped right
    } else if (dragOffset < -100) {
      handleAction(false); // Swiped left
    } else {
      setDragOffset(0); // Snap back
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="animate-spin h-10 w-10 border-4 border-blue-600 border-t-transparent rounded-full"></div>
      </div>
    );
  }

  if (!hasStarted && cards.length > 0) {
    return (
      <div className="min-h-[calc(100vh-73px)] bg-gray-50 flex items-center justify-center p-6">
        <div className="bg-white rounded-3xl shadow-xl border border-gray-100 p-10 text-center max-w-sm w-full">
          <div className="text-6xl mb-6 animate-bounce">🎧</div>
          <h2 className="text-2xl font-black text-gray-900 mb-2">Siap Belajar?</h2>
          <p className="text-gray-500 mb-8">Pastikan volume suara Anda aktif karena kosa kata akan diputar secara otomatis.</p>
          <button 
            onClick={() => setHasStarted(true)}
            className="w-full py-4 bg-blue-600 hover:bg-blue-700 text-white font-black rounded-xl shadow-lg transition-all transform hover:scale-105 active:scale-95"
          >
            Mulai Sesi
          </button>
        </div>
      </div>
    );
  }

  if (cards.length === 0 || currentIndex >= cards.length) {
    return (
      <div className="min-h-screen bg-gray-50 flex flex-col items-center justify-center p-6 text-center">
        <div className="text-7xl mb-6">🎉</div>
        <h1 className="text-3xl font-black text-gray-900 mb-2">Sesi Selesai!</h1>
        <p className="text-gray-500 mb-8 max-w-sm">Kerja bagus! Berikut adalah ringkasan hasil belajar Anda hari ini.</p>
        
        <div className="grid grid-cols-2 gap-4 w-full max-w-sm mb-10">
          <div className="bg-green-50 border border-green-200 rounded-2xl p-6 shadow-sm">
            <div className="text-4xl font-extrabold text-green-600 mb-1">{learnedCount}</div>
            <div className="text-sm font-bold text-green-800">Sudah Hafal</div>
          </div>
          <div className="bg-rose-50 border border-rose-200 rounded-2xl p-6 shadow-sm">
            <div className="text-4xl font-extrabold text-rose-600 mb-1">{unlearnedCount}</div>
            <div className="text-sm font-bold text-rose-800">Belum Hafal</div>
          </div>
        </div>

        <div className="flex gap-4 w-full max-w-sm">
          <Link href="/flashcard" className="flex-1 bg-white border border-gray-200 hover:bg-gray-50 text-gray-700 font-bold py-3.5 px-6 rounded-xl transition-colors shadow-sm">
            Sesi Baru
          </Link>
          <Link href="/dashboard" className="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 px-6 rounded-xl transition-colors shadow-md">
            Ruang Belajar
          </Link>
        </div>
      </div>
    );
  }

  const card = cards[currentIndex];
  
  // Calculate drag transform
  const dragTransform = `translateX(${dragOffset}px) rotate(${dragOffset * 0.05}deg)`;

  return (
    <div 
      className="bg-gray-50 flex flex-col p-4 md:p-6 overflow-hidden w-full"
      style={{ height: 'calc(100vh - 74px)' }}
    >
      {/* Header */}
      <div className="flex justify-between items-center mb-3 max-w-lg mx-auto w-full shrink-0">
        <Link href="/flashcard" className="text-gray-400 hover:text-gray-900 transition-colors p-2">
          <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" /></svg>
        </Link>
        <div className="text-gray-500 font-bold tracking-widest text-sm">
          {currentIndex + 1} / {cards.length}
        </div>
        <div className="w-10"></div> {/* Spacer */}
      </div>

      {/* Progress Bar */}
      <div className="w-full max-w-lg mx-auto bg-gray-200 rounded-full h-1.5 mb-4 overflow-hidden shrink-0">
        <div 
          className="bg-blue-600 h-1.5 transition-all duration-300 ease-out" 
          style={{ width: `${((currentIndex + 1) / cards.length) * 100}%` }}
        ></div>
      </div>

      {/* Flashcard Area */}
      <div className="flex-1 flex flex-col items-center justify-center relative w-full min-h-0">
        
        {/* Next Card Preview (stacked behind) */}
        {currentIndex + 1 < cards.length && (
          <div className="absolute h-full max-h-[500px] aspect-[3/4] max-w-full bg-white border border-gray-100 rounded-2xl opacity-50 scale-95 translate-y-6 shadow-sm z-0 pointer-events-none"></div>
        )}

        {/* Current Active Card */}
        <div 
          className={`relative h-full max-h-[500px] aspect-[3/4] max-w-full cursor-pointer transition-all duration-200 ease-out z-10 
            ${animatingOut === 'left' ? '-translate-x-full rotate-[-15deg] opacity-0' : ''}
            ${animatingOut === 'right' ? 'translate-x-full rotate-[15deg] opacity-0' : ''}
          `}
          style={{ 
            transform: dragOffset !== 0 ? dragTransform : undefined,
            transition: dragOffset !== 0 ? 'none' : 'all 0.2s ease-out'
          }}
          onClick={() => {
             if (!flipped) setFlipped(true);
          }}
          onTouchStart={handleTouchStart}
          onTouchMove={handleTouchMove}
          onTouchEnd={handleTouchEnd}
          onMouseDown={handleTouchStart}
          onMouseMove={handleTouchMove}
          onMouseUp={handleTouchEnd}
          onMouseLeave={handleTouchEnd}
        >
          {/* Base Card Frame */}
          <div className="absolute inset-0 bg-white border border-gray-100 rounded-[16px] shadow-xl overflow-hidden flex flex-col">
            
            {/* Front Side */}
            <div className={`absolute inset-0 py-6 px-6 flex flex-col items-center transition-opacity duration-250 ease-in-out ${flipped ? 'opacity-0 pointer-events-none' : 'opacity-100'}`}>
              <div className="w-full flex justify-center shrink-0">
                <span className="px-3 py-1 bg-blue-50 text-blue-700 text-[11px] font-extrabold uppercase tracking-widest rounded-full">
                  {card.partOfSpeechShort}
                </span>
              </div>
              
              <div className="flex-1 flex flex-col items-center justify-center w-full min-h-0">
                <h2 className="text-4xl sm:text-5xl font-black text-gray-900 text-center mb-6 break-words px-2 leading-tight">
                  {card.word}
                </h2>
                {card.audioUs && (
                  <button 
                    onClick={(e) => playAudio(e, 'us', card.word, card.audioUs)}
                    className="p-3 bg-gray-50 hover:bg-gray-100 text-gray-600 rounded-full transition-colors shrink-0"
                  >
                    <svg className="w-6 h-6" fill="currentColor" viewBox="0 0 20 20"><path fillRule="evenodd" d="M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM14.657 2.929a1 1 0 011.414 0A9.972 9.972 0 0119 10a9.972 9.972 0 01-2.929 7.071 1 1 0 01-1.414-1.414A7.971 7.971 0 0017 10c0-2.21-.894-4.208-2.343-5.657a1 1 0 010-1.414zm-2.829 2.828a1 1 0 011.415 0A5.983 5.983 0 0115 10a5.984 5.984 0 01-1.757 4.243 1 1 0 01-1.415-1.415A3.984 3.984 0 0013 10a3.983 3.983 0 00-1.172-2.828 1 1 0 010-1.415z" clipRule="evenodd" /></svg>
                  </button>
                )}
              </div>

              <p className="text-gray-400 text-sm shrink-0">Ketuk untuk membalik</p>
            </div>

            {/* Back Side */}
            <div className={`absolute inset-0 py-6 px-6 flex flex-col items-center justify-center transition-opacity duration-250 ease-in-out ${flipped ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}>
              <h2 className="text-3xl sm:text-4xl font-black text-gray-900 text-center mb-4 leading-tight px-2">
                {card.translation}
              </h2>
              {card.ipaUk && (
                <p className="text-gray-500 font-medium text-lg mb-6">{card.ipaUk}</p>
              )}
              
              <div className="flex gap-4 shrink-0">
                {card.audioUs && (
                  <button 
                    onClick={(e) => playAudio(e, 'us', card.word, card.audioUs)}
                    className="flex items-center gap-2 bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-2 rounded-full transition-colors font-bold text-sm"
                  >
                    <span className="text-lg">🇺🇸</span> US
                  </button>
                )}
                {card.audioUk && (
                  <button 
                    onClick={(e) => playAudio(e, 'uk', card.word, card.audioUk)}
                    className="flex items-center gap-2 bg-gray-100 hover:bg-gray-200 text-gray-700 px-4 py-2 rounded-full transition-colors font-bold text-sm"
                  >
                    <span className="text-lg">🇬🇧</span> UK
                  </button>
                )}
              </div>
            </div>
            
          </div>
        </div>

      </div>

      {/* Action Controls & Hints */}
      <div className="mt-4 max-w-[420px] mx-auto w-full h-[70px] relative flex flex-col justify-end shrink-0">
        
        {/* Device hints (Show only if flipped and no drag) */}
        <div className={`absolute inset-0 flex justify-center items-start transition-opacity duration-300 ${flipped && dragOffset === 0 ? 'opacity-100' : 'opacity-0 pointer-events-none'}`}>
           <p className="text-gray-400 text-xs font-medium md:hidden">Geser kiri/kanan</p>
           <p className="text-gray-400 text-xs font-medium hidden md:block">Gunakan ← →</p>
        </div>

        {/* Action Buttons */}
        <div className={`flex gap-3 w-full transition-all duration-300 transform ${flipped ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-4 pointer-events-none'}`}>
          <button 
            onClick={(e) => { e.stopPropagation(); handleAction(false); }}
            className="flex-1 bg-rose-50 hover:bg-rose-100 border border-rose-100 text-rose-600 font-bold py-3 px-2 rounded-[16px] transition-colors flex justify-center items-center shadow-sm"
          >
            Belum hafal
          </button>
          <button 
            onClick={(e) => { e.stopPropagation(); handleAction(true); }}
            className="flex-1 bg-green-500 hover:bg-green-600 text-white font-bold py-3 px-2 rounded-[16px] transition-colors flex justify-center items-center shadow-sm"
          >
            Sudah hafal
          </button>
        </div>
      </div>
    </div>
  );
}
