"use client"
import { useRouter } from "next/navigation"
import { useFlashMessage } from "@/context/FlashMessageContext"

export default function NewPostPage() {
  const router = useRouter();
  const { showFlashMessage } = useFlashMessage()

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    // -------------------------------------------------------------- دریافت اطلاعات از فرم
    e.preventDefault()
    const formData = new FormData(e.currentTarget)
    const title = formData.get("title")
    const content = formData.get("content")

    // -------------------------------------------------------------- ارسال اطلاعات به API
    fetch("/api/posts", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${localStorage.getItem("loginToken")}`
      },
      body: JSON.stringify({ title, content })
    })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          //  ----------  پست با موفقیت ایجاد شد
          router.push(`/posts/${data.postId}`);
          showFlashMessage("New Post Successfuly Created", "success")

        } else {
          alert("❌ خطا: " + data.message)
        }
      })
      .catch(err => {
        console.error("خطا در ارسال:", err)
        alert("❌ خطا در ارتباط با سرور")
      })
  }

  return (

    <form className="container p-4" onSubmit={handleSubmit}>
      <div className="form-group">
        <label htmlFor="post-title" className="text-muted mb-1">
          <small>Title</small>
        </label>
        <input autoFocus name="title" id="post-title" className="form-control form-control-lg form-control-title" placeholder="" autoComplete="off" />
      </div>

      <div className="form-group">
        <label htmlFor="post-body" className="text-muted mb-1 d-block">
          <small>Body Content</small>
        </label>
        <textarea rows={10} name="content" id="post-body" className="body-content tall-textarea form-control"></textarea>
      </div>

      <button className="btn btn-primary">Save New Post</button>
    </form>

  )
}