import { useState } from 'react';
import Card from '../ui/Card';
import Button from '../ui/Button';

export default function FlashcardSet({ content, onComplete }) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isFlipped, setIsFlipped] = useState(false);
  const [viewedCards, setViewedCards] = useState(new Set());

  const cards = content?.cards || [];

  const handleFlip = () => {
    setIsFlipped(!isFlipped);
    const newViewed = new Set(viewedCards);
    newViewed.add(currentIndex);
    setViewedCards(newViewed);
  };

  const handleNext = () => {
    setIsFlipped(false);
    setCurrentIndex((prev) => (prev + 1) % cards.length);
  };

  const handlePrev = () => {
    setIsFlipped(false);
    setCurrentIndex((prev) => (prev - 1 + cards.length) % cards.length);
  };

  if (cards.length === 0) {
    return <div className="text-center p-4">No flashcards available.</div>;
  }

  const currentCard = cards[currentIndex];

  return (
    <div className="w-full flex flex-col items-center space-y-6">
      <div className="text-sm text-slate-500 font-medium">
        Card {currentIndex + 1} of {cards.length}
      </div>

      <Card 
        className="w-full max-w-lg min-h-[300px] cursor-pointer relative flex items-center justify-center p-8 hover:shadow-pill transition-all"
        onClick={handleFlip}
      >
        <div className="text-center text-xl">
          {isFlipped ? (
            <div className="prose dark:prose-invert">
              <p>{currentCard.back}</p>
            </div>
          ) : (
            <div className="prose dark:prose-invert font-bold text-teal">
              <p>{currentCard.front}</p>
            </div>
          )}
        </div>
      </Card>

      <div className="text-sm text-slate-400 mt-2">
        Click the card to flip
      </div>

      <div className="flex space-x-4">
        <Button variant="outline" onClick={handlePrev}>Previous</Button>
        <Button variant="outline" onClick={handleNext}>Next</Button>
      </div>

      <div className="w-full max-w-lg pt-4 border-t border-bg-warm flex items-center justify-between">
        <span className="text-xs text-fg-muted">
          {viewedCards.size}/{cards.length} cards viewed
        </span>
        <Button onClick={onComplete}>Finish session</Button>
      </div>
    </div>
  );
}
