"use client";

import { useState } from "react";

export default function ProfileForm({ user }: { user: { id: string; name: string; email: string } }) {
  const [name, setName] = useState(user.name);
  const [saved, setSaved] = useState(false);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    await fetch("/api/user/profile", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name }),
    });
    setSaved(true);
    setLoading(false);
    setTimeout(() => setSaved(false), 3000);
  }

  return (
    <form onSubmit={handleSubmit} className="bg-white rounded-2xl shadow p-6 flex flex-col gap-4">
      <h2 className="font-bold text-lg">اطلاعات حساب</h2>
      <div>
        <label className="block text-sm font-medium mb-1">نام</label>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          className="w-full border rounded-xl px-4 py-2.5 focus:outline-none focus:ring-2 focus:ring-green-500"
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">ایمیل</label>
        <input
          type="email"
          value={user.email}
          disabled
          className="w-full border rounded-xl px-4 py-2.5 bg-gray-50 text-gray-400"
        />
      </div>
      <button
        type="submit"
        disabled={loading}
        className="bg-green-700 text-white py-2.5 rounded-xl font-bold hover:bg-green-800 transition disabled:opacity-50"
      >
        {loading ? "در حال ذخیره..." : "ذخیره"}
      </button>
      {saved && <p className="text-green-600 text-sm text-center">✓ ذخیره شد</p>}
    </form>
  );
}
