import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom"; // <-- import
import { DefaultService } from "../../api/services/DefaultService";
import type { User } from "../../api/models/User";
import styles from "./UserPage.module.css";

const UserPage: React.FC = () => {
  const { id } = useParams<{ id: string }>(); // <-- get user id from URL
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!id) return;

    const getUserInfo = async () => {
      try {
        const userInfo = await DefaultService.getUsersId(id, "all"); // <-- use dynamic id
        setUser(userInfo);
      } catch (err) {
        console.error(err);
        setError("Failed to fetch user info.");
      } finally {
        setLoading(false);
      }
    };
    getUserInfo();
  }, [id]);

  if (loading) return <div className={styles.loader}>Loading...</div>;
  if (error) return <div className={styles.error}>{error}</div>;
  if (!user) return <div className={styles.error}>User not found.</div>;

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.avatarWrapper}>
          {user.image?.image_path ? (
            <img
              src={`/images/${user.image.image_path}.png`}
              alt="User Avatar"
              className={styles.avatarImg}
            />
          ) : (
            <div className={styles.avatarPlaceholder}>
              {user.disp_name?.[0] || "U"}
            </div>
          )}
        </div>

        <div className={styles.userInfo}>
          <h1 className={styles.name}>{user.disp_name || user.nickname}</h1>
          <p className={styles.nickname}>@{user.nickname}</p>
          {/* <p className={styles.created}>
            Joined: {new Date(user.creation_date).toLocaleDateString()}
          </p> */}
        </div>

        <div className={styles.content}>
          {user.user_desc && <p className={styles.desc}>{user.user_desc}</p>}
        </div>
      </div>
    </div>
  );
};

export default UserPage;
