"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";

export default function NewQuestionPage() {
  const router = useRouter();
  const [title, setTitle] = useState("");
  const [text, setText] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!title.trim() || !text.trim()) return;
    setLoading(true);
    setError("");

    try {
      const res = await fetch("/api/questions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ title, text }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error ?? "Ошибка при создании вопроса");
      }
      const q = await res.json();
      router.push(`/questions/${q.id}`);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Ошибка");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="max-w-xl mx-auto px-4 py-8">
      <div className="flex items-center gap-3 mb-6">
        <Link
          href="/questions"
          className="text-sm"
          style={{ color: "var(--muted-foreground)", textDecoration: "underline" }}
        >
          ← Все вопросы
        </Link>
      </div>

      <h1 className="text-xl font-bold mb-6" style={{ color: "var(--foreground)" }}>
        Новый вопрос
      </h1>

      <form onSubmit={handleSubmit} className="flex flex-col gap-4">
        <div>
          <label
            className="block text-sm font-bold mb-1"
            style={{ color: "var(--foreground)" }}
          >
            Тема вопроса
          </label>
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="Кратко опишите суть вопроса"
            required
            className="w-full text-sm px-3 py-2 outline-none"
            style={{
              border: "2px solid var(--border)",
              background: "var(--color-surface)",
              color: "var(--foreground)",
            }}
          />
        </div>

        <div>
          <label
            className="block text-sm font-bold mb-1"
            style={{ color: "var(--foreground)" }}
          >
            Описание
          </label>
          <textarea
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder="Подробно опишите вопрос или проблему"
            required
            rows={6}
            className="w-full text-sm px-3 py-2 outline-none resize-none"
            style={{
              border: "2px solid var(--border)",
              background: "var(--color-surface)",
              color: "var(--foreground)",
            }}
          />
        </div>

        {error && (
          <p className="text-sm" style={{ color: "var(--destructive)" }}>
            {error}
          </p>
        )}

        <button
          type="submit"
          disabled={loading || !title.trim() || !text.trim()}
          className="self-end text-sm font-bold px-6 py-2"
          style={{
            background: "var(--foreground)",
            color: "var(--background)",
            border: "none",
            opacity: loading ? 0.6 : 1,
          }}
        >
          {loading ? "Отправка..." : "Отправить →"}
        </button>
      </form>
    </div>
  );
}
