import { useEffect, useState } from "react";
import { apiFetch } from "../lib/api";

type Question = {
  id: string;
  text: string;
  type: string;
  options: string[] | null;
};

export default function Dashboard() {
  const [questions, setQuestions] = useState<Question[]>([]);
  const [text, setText] = useState("");
  const [options, setOptions] = useState(["", "", "", ""]);
  const [selected, setSelected] = useState<string[]>([]);
  const [testTitle, setTestTitle] = useState("");
  const [error, setError] = useState("");

  async function loadQuestions() {
    const data = await apiFetch("/questions");
    setQuestions(data);
  }

  useEffect(() => {
    loadQuestions().catch((e) => setError(e.message));
  }, []);

  async function addQuestion(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    try {
      await apiFetch("/questions", {
        method: "POST",
        body: JSON.stringify({
          type: "COKTAN_SECMELI",
          text,
          options: options.filter(Boolean),
          correctOption: 0,
        }),
      });
      setText("");
      setOptions(["", "", "", ""]);
      loadQuestions();
    } catch (err: any) {
      setError(err.message);
    }
  }

  function toggleSelect(id: string) {
    setSelected((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
  }

  async function createTestAndDownload() {
    setError("");
    try {
      const test = await apiFetch("/tests", {
        method: "POST",
        body: JSON.stringify({ title: testTitle || "Test", questionIds: selected }),
      });
      const token = localStorage.getItem("otm_token");
      const apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:4000/api";
      window.open(`${apiUrl}/pdf/tests/${test.id}?token=${token}`, "_blank");
    } catch (err: any) {
      setError(err.message);
    }
  }

  return (
    <main style={{ maxWidth: 700, margin: "40px auto", fontFamily: "Arial, sans-serif" }}>
      <h1>Panel</h1>
      {error && <p style={{ color: "red" }}>{error}</p>}

      <section style={{ marginBottom: 32 }}>
        <h2>Yeni Soru Ekle</h2>
        <form onSubmit={addQuestion} style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          <textarea
            placeholder="Soru metni"
            value={text}
            onChange={(e) => setText(e.target.value)}
            required
          />
          {options.map((opt, i) => (
            <input
              key={i}
              placeholder={`Şık ${String.fromCharCode(65 + i)}`}
              value={opt}
              onChange={(e) => {
                const next = [...options];
                next[i] = e.target.value;
                setOptions(next);
              }}
            />
          ))}
          <button type="submit">Soruyu Kaydet</button>
        </form>
      </section>

      <section>
        <h2>Soru Bankası</h2>
        <ul style={{ listStyle: "none", padding: 0 }}>
          {questions.map((q) => (
            <li key={q.id} style={{ marginBottom: 8 }}>
              <label>
                <input
                  type="checkbox"
                  checked={selected.includes(q.id)}
                  onChange={() => toggleSelect(q.id)}
                />{" "}
                {q.text}
              </label>
            </li>
          ))}
        </ul>

        <input
          placeholder="Test başlığı"
          value={testTitle}
          onChange={(e) => setTestTitle(e.target.value)}
        />
        <button onClick={createTestAndDownload} disabled={selected.length === 0}>
          Seçilen Sorularla Test Oluştur ve PDF İndir
        </button>
      </section>
    </main>
  );
}
