"use client";

import { useEffect, useState } from "react";

import { apiFetch } from "@/lib/api";
import { readToken } from "@/lib/auth";

type Me = {
  id: number;
  username: string;
  rating: number;
  created_at: number;
};

export default function MePage() {
  const [data, setData] = useState<Me | null>(null);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      setError("");
      try {
        const token = readToken();
        if (!token) throw new Error("请先登录");
        const d = await apiFetch<Me>("/api/v1/me", {}, token);
        setData(d);
      } catch (e: unknown) {
        setError(String(e));
      } finally {
        setLoading(false);
      }
    };
    void load();
  }, []);

  return (
    <main className="mx-auto max-w-3xl px-6 py-8">
      <h1 className="text-2xl font-semibold">我的信息</h1>
      {loading && <p className="mt-3 text-sm text-zinc-500">加载中...</p>}
      {error && <p className="mt-3 text-sm text-red-600">{error}</p>}

      {data && (
        <div className="mt-4 rounded-xl border bg-white p-4 text-sm">
          <p>ID: {data.id}</p>
          <p>用户名: {data.username}</p>
          <p>Rating: {data.rating}</p>
          <p>创建时间: {new Date(data.created_at * 1000).toLocaleString()}</p>
        </div>
      )}
    </main>
  );
}
