import { useState, useEffect } from "react";
import MainLayout from "../layouts/MainLayout";
import { uploadAvatar } from "../api/account/uploadAvatar";
import { me } from "../api/auth/me"; // bu fonksiyon token ile kullanıcıyı döndürecek

export default function AccountSettingsPage() {
  const [image, setImage] = useState<File | null>(null);
  const [preview, setPreview] = useState<string | null>(null);

  useEffect(() => {
    const user = JSON.parse(localStorage.getItem("user") || "{}");
    if (user?.avatarUrl) setPreview(user.avatarUrl);
  }, []);

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setImage(file);
    setPreview(URL.createObjectURL(file));
  };

  const handleUpload = async () => {
    if (!image) return;
    try {
      const token = localStorage.getItem("token") || "";
      await uploadAvatar( image);
      
      // avatar yüklendikten sonra güncel kullanıcıyı backend’den çek
      const updatedUser = await me();
      localStorage.setItem("user", JSON.stringify(updatedUser));
      setPreview(updatedUser.avatarUrl);
      alert("Profil fotoğrafı güncellendi");
    } catch (err) {
      console.error(err);
      alert("Yükleme başarısız");
    }
  };

  return (
    <MainLayout>
      <div className="max-w-md mx-auto p-4">
        <h2 className="text-xl font-semibold mb-4">Hesap Ayarları</h2>

        <div className="flex flex-col items-center">
          {preview ? (
            <img
              src={preview}
              alt="Profil Fotoğrafı"
              className="w-32 h-32 rounded-full object-cover mb-3"
            />
          ) : (
            <div className="w-32 h-32 bg-gray-200 rounded-full mb-3" />
          )}

          <input type="file" accept="image/*" onChange={handleImageChange} />
          <button
            onClick={handleUpload}
            className="mt-3 px-4 py-2 bg-blue-600 text-white rounded"
          >
            Kaydet
          </button>
        </div>
      </div>
    </MainLayout>
  );
}
