import { useState } from "react";
import { Button } from "@/components/ui/button";
import { BaseExercise, type BaseExerciseProps } from "./BaseExercise";
import { cn } from "@/lib/utils";

interface SyllablesExerciseProps extends BaseExerciseProps {
  syllables: string[];
  correctOrder: number[];
}

export function SyllablesExercise({ 
  currentWord, 
  onAnswer, 
  syllables,
  correctOrder,
  disabled 
}: SyllablesExerciseProps) {
  const [selectedSyllables, setSelectedSyllables] = useState<number[]>([]);

  const handleSyllableClick = (index: number) => {
    if (selectedSyllables.includes(index)) {
      setSelectedSyllables(prev => prev.filter(i => i !== index));
    } else {
      setSelectedSyllables(prev => [...prev, index]);
    }
  };

  const handleCheck = () => {
    const isCorrect = selectedSyllables.every(
      (syllableIndex, position) => syllableIndex === correctOrder[position]
    );
    onAnswer(currentWord.word, isCorrect);
  };

  return (
    <div className="space-y-8">
      <BaseExercise currentWord={currentWord} onAnswer={onAnswer} disabled={disabled} />
      
      <div className="space-y-4">
        <div className="text-center text-muted-foreground">
          Selecione as sílabas na ordem correta
        </div>

        <div className="flex flex-wrap justify-center gap-2">
          {syllables.map((syllable, index) => (
            <Button
              key={index}
              onClick={() => handleSyllableClick(index)}
              disabled={disabled}
              variant={selectedSyllables.includes(index) ? "default" : "outline"}
              className={cn(
                "text-lg px-4",
                disabled && correctOrder.indexOf(index) === selectedSyllables.indexOf(index) && "border-green-500 bg-green-50",
                disabled && correctOrder.indexOf(index) !== selectedSyllables.indexOf(index) && "border-red-500 bg-red-50"
              )}
            >
              {syllable}
            </Button>
          ))}
        </div>

        {selectedSyllables.length > 0 && !disabled && (
          <div className="flex justify-center">
            <Button 
              onClick={handleCheck}
              className="mt-4"
            >
              Verificar
            </Button>
          </div>
        )}

        {selectedSyllables.length > 0 && (
          <div className="text-center text-xl font-medium">
            {syllables.filter((_, i) => selectedSyllables.includes(i)).join("-")}
          </div>
        )}
      </div>
    </div>
  );
} 