"use client"
import { useEffect, useState } from "react"
export default function HomeGuest() {

  // -----------------------------------------------------Load user
  const [users, setUsers] = useState<User[]>([])
  type User = {
    _id: string
    username: string
    email: string
  }
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    async function fetchUsers() {
      try {
        const res = await fetch("/api/users")
        const data = await res.json()
        if (data.connected) {
          setUsers(data.users)
        }
      } catch (error) {
        console.error("خطا در دریافت کاربران:", error)
      } finally {
        setLoading(false)
      }
    }

    fetchUsers()
  }, [])

  // -----------------------------------------------------Form submit
  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {

    e.preventDefault()
    const formData = new FormData(e.currentTarget)
    const username = formData.get("username")
    const email = formData.get("email")
    const password = formData.get("password")

    fetch("/api/users", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ username, email, password })
    })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          alert("✅ کاربر با موفقیت ثبت شد!")
        } else {
          alert("❌ خطا: " + data.message)
        }
      })
      .catch(err => {
        console.error("خطا در ارسال:", err)
        alert("❌ خطا در ارتباط با سرور")
      })
  }

  return (
    <div className="home-guest container py-md-5">
      <div className="row align-items-center">
        <div className="col-lg-7 py-3 py-md-5">
          <h1 className="display-3">Remember Writing?</h1>
          <p className="lead text-muted">Are you sick of short tweets and impersonal &ldquo;shared&rdquo; posts that are reminiscent of the late 90&rsquo;s email forwards? We believe getting back to actually writing is the key to enjoying the internet again.</p>

          {/* // -----------------------------------------------------Show user */}
          <h5 className="">Users List: 👥</h5>
          {loading ? (
            <p>در حال بارگذاری...</p>
          ) : users.length > 0 ? (
            <ul>
              {users.map((user) => (
                <li key={user._id}>
                  {user.username} - {user.email}
                </li>
              ))}
            </ul>
          ) : (
            <p>هیچ کاربری یافت نشد.</p>
          )}
        </div>

        <div className="col-lg-5 pl-lg-5 pb-3 py-lg-5">
          <form onSubmit={handleSubmit}>
            <div className="form-group">
              <label htmlFor="username-register" className="text-muted mb-1">
                <small>Username</small>
              </label>
              <input id="username-register" name="username" className="form-control" type="text" placeholder="Pick a username" autoComplete="off" />
            </div>
            <div className="form-group">
              <label htmlFor="email-register" className="text-muted mb-1">
                <small>Email</small>
              </label>
              <input id="email-register" name="email" className="form-control" type="text" placeholder="you@example.com" autoComplete="off" />
            </div>
            <div className="form-group">
              <label htmlFor="password-register" className="text-muted mb-1">
                <small>Password</small>
              </label>
              <input id="password-register" name="password" className="form-control" type="password" placeholder="Create a password" />
            </div>
            <button type="submit" className="py-3 mt-4 btn btn-lg btn-success btn-block">
              Sign up for ComplexApp
            </button>
          </form>
        </div>
      </div>
    </div>
  )
}