import { useState } from "react";

export default function QuestionCard({ frage, antworten, onNext, onCheck, isLast }) {
  const [selected, setSelected] = useState([]);
  const [checked, setChecked] = useState(false); // wurde „Überprüfen“ gedrückt

  const toggleAntwort = (idx) => {
    if (checked) return; // Sperre Änderungen nach Überprüfung

    setSelected((prev) =>
      prev.includes(idx)
        ? prev.filter((i) => i !== idx)
        : [...prev, idx]
    );
  };

  const isCorrect = (idx) => antworten[idx].korrekt;
  const wasSelected = (idx) => selected.includes(idx);

  const handleCheck = () => {
    setChecked(true);
    const correct = antworten.every((antwort, idx) => {
      return antwort.korrekt === selected.includes(idx);
    });
    if (onCheck) {
      onCheck(correct);
    }
  };

  const handleNext = () => {
    setSelected([]);
    setChecked(false);
    onNext();
  };

  return (
    <div className="bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 p-6 rounded-xl shadow-lg transition transform hover:-translate-y-1 hover:shadow-xl animate-float-in">
      <h2 className="text-lg font-semibold mb-4">{frage}</h2>
      <div className="space-y-2">
        {antworten.map((antwort, idx) => {
          const korrekt = isCorrect(idx);
          const gewählt = wasSelected(idx);
          let style = "";

            if (checked) {
            if (korrekt && gewählt) style = "bg-green-100 dark:bg-green-800 border-green-500";
            else if (!korrekt && gewählt) style = "bg-red-100 dark:bg-red-800 border-red-500";
            else if (korrekt && !gewählt) style = "bg-yellow-100 dark:bg-yellow-800 border-yellow-500";
            else style = "bg-gray-50 dark:bg-gray-700";
            } else {
            style = gewählt
                ? "bg-blue-100 dark:bg-blue-800 border-blue-500"
                : "bg-gray-50 dark:bg-gray-700";
            }

          return (
            <label
              key={idx}
              className={`block border rounded px-4 py-2 cursor-pointer ${style}`}
            >
              <input
                type="checkbox"
                className="mr-2"
                checked={gewählt}
                disabled={checked}
                onChange={() => toggleAntwort(idx)}
              />
              {antwort.text}
            </label>
          );
        })}
      </div>

      <div className="mt-6 flex justify-end gap-4">
        {!checked ? (
          <button
            onClick={handleCheck}
            //disabled={selected.length === 0}
            className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 transition disabled:opacity-50"
          >
            Überprüfen
          </button>
        ) : (
          <button
            onClick={handleNext}
            className="bg-green-600 text-white px-4 py-2 rounded hover:bg-green-700 transition"
          >
            {isLast ? "Fertig" : "Weiter"}
          </button>
        )}
      </div>
    </div>
  );
}
