"use client";

import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";

export default function UserProfile() {
  const router = useRouter();
  const [userData, setUserData] = useState(null);

  useEffect(() => {
    const storedUser = localStorage.getItem("user");
    if (!storedUser) {
      router.push("/login");
      return;
    }
    setUserData(JSON.parse(storedUser));
  }, [router]);

  const handleLogout = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("user");
    router.push("/login");
  };

  if (!userData) {
    return <div className="p-4">加载中...</div>;
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="bg-yellow-400 p-8">
        <div className="flex items-center gap-6">
          <Image
            src={
              userData.avatar ||
              "https://s2.loli.net/2025/02/11/miDGcVpHvQUzNwr.jpg"
            }
            alt="avatar"
            width={80}
            height={80}
            className="rounded-full"
          />
          <div>
            <h2 className="text-xl font-bold">{userData.username}</h2>
            <p className="text-sm text-gray-700 mt-2">
              用户ID: {userData.userId}
            </p>
          </div>
        </div>
      </div>

      <div className="p-4">
        <div className="bg-white rounded-lg p-4 mt-4">
          <h3 className="text-lg font-bold mb-4">账户信息</h3>
          <div className="space-y-4">
            <div className="flex justify-between items-center py-2 border-b">
              <span className="text-gray-500">用户名</span>
              <span>{userData.username}</span>
            </div>
            <div className="flex justify-between items-center py-2 border-b">
              <span className="text-gray-500">用户ID</span>
              <span>{userData.userId}</span>
            </div>
            <div className="flex justify-between items-center py-2 border-b">
              <span className="text-gray-500">注册时间</span>
              <span>
                {new Date(userData.createdAt).toLocaleDateString("zh-CN", {
                  year: "numeric",
                  month: "long",
                  day: "numeric",
                })}
              </span>
            </div>
          </div>
        </div>

        <button
          onClick={handleLogout}
          className="w-full mt-8 bg-red-500 text-white py-3 rounded-lg"
        >
          退出登录
        </button>
      </div>
    </div>
  );
}
