import { useEffect, useState } from "react";

export default function SolutionsPage({ mode, onBack }) {
  const [questions, setQuestions] = useState([]);
  const [search, setSearch] = useState("");

  useEffect(() => {
    fetch(`/api/questions/${mode}`)
      .then((res) => res.json())
      .then(setQuestions);
  }, [mode]);

  const filtered = questions.filter((q) => {
    const query = search.toLowerCase();
    return (
      q.frage.toLowerCase().includes(query) ||
      q.antworten.some((a) => a.text.toLowerCase().includes(query))
    );
  });

  return (
    <div className="max-w-4xl mx-auto p-4 text-gray-900 dark:text-white">
      <div className="flex justify-between items-center mb-4">
        <h1 className="text-xl font-bold">
          Lösungen ({mode.toUpperCase()}-Modus)
        </h1>
        <button
          onClick={onBack}
          className="text-blue-600 dark:text-blue-400 underline text-sm"
        >
          Zurück
        </button>
      </div>

      {/* Suchfeld mit X-Button */}
      <div className="relative mb-6">
        <input
          type="text"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Frage oder Antwort durchsuchen..."
          className="w-full px-4 py-2 pr-10 border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
        {search && (
          <button
            onClick={() => setSearch("")}
            className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 dark:text-gray-300 hover:text-gray-800 dark:hover:text-white"
          >
            ✕
          </button>
        )}
      </div>

      {filtered.length === 0 && (
        <p className="text-gray-500 dark:text-gray-400">
          Keine passenden Fragen gefunden.
        </p>
      )}

      <div className="space-y-6">
        {filtered.map((frage, idx) => (
          <div
            key={idx}
            className="border border-gray-300 dark:border-gray-600 rounded-lg p-4 shadow-sm bg-white dark:bg-gray-900"
          >
            <p className="font-semibold mb-2">
              {idx + 1}. {frage.frage}
            </p>
            <ul className="list-disc list-inside space-y-1">
              {frage.antworten.map((antwort, aidx) => (
                <li
                  key={aidx}
                  className={
                    antwort.korrekt
                      ? "text-green-600 dark:text-green-400 font-semibold"
                      : ""
                  }
                >
                  {antwort.text}
                </li>
              ))}
            </ul>
          </div>
        ))}
      </div>
    </div>
  );
}
