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

export default function ScenarioQuiz({ content, onComplete }) {
  const [selectedOptionId, setSelectedOptionId] = useState(null);
  const [showExplanations, setShowExplanations] = useState(false);

  const handleSelect = (idx) => {
    if (showExplanations) return;
    setSelectedOptionId(idx);
    setShowExplanations(true);
  };

  return (
    <Card className="w-full">
      <div className="mb-6 pb-4 border-b border-bg-warm">
        <h2 className="text-xl font-bold">Scenario Quiz</h2>
      </div>
      <div className="space-y-6">
        <div className="prose dark:prose-invert">
          <p className="text-lg font-medium">{content?.scenario}</p>
        </div>
        
        <div className="space-y-4">
          {content?.options?.map((option, idx) => {
            const isSelected = selectedOptionId === idx;
            
            let buttonStyle = "w-full justify-start text-left h-auto p-4 ";
            if (showExplanations) {
              if (option.isCorrect) buttonStyle += "bg-green-100 dark:bg-green-900 border-green-500 ";
              else if (isSelected && !option.isCorrect) buttonStyle += "bg-red-100 dark:bg-red-900 border-red-500 ";
              else buttonStyle += "opacity-70 ";
            } else {
              if (isSelected) buttonStyle += "bg-teal/10 ";
            }

            return (
              <div key={idx} className="space-y-2">
                <Button 
                  variant={isSelected ? "primary" : "outline"}
                  className={buttonStyle}
                  onClick={() => handleSelect(idx)}
                  disabled={showExplanations}
                >
                  <span className="flex-1 whitespace-normal">{option.text}</span>
                </Button>
                
                {showExplanations && (
                  <div className={`p-3 rounded-[var(--r-md)] text-sm ${option.isCorrect ? 'bg-green-50 text-green-800' : 'bg-slate-50 text-slate-700'}`}>
                    <span className="font-semibold">{option.isCorrect ? '✓ ' : '✗ '}</span>
                    {option.explanation}
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {showExplanations && (
          <div className="pt-4 border-t border-bg-warm flex justify-end">
            <Button onClick={onComplete}>Finish session</Button>
          </div>
        )}
      </div>
    </Card>
  );
}
