import {useContext, useEffect, useState} from "react";
import styles from "./ProfilePage.module.css";
import {AuthContext} from "../../contexts/Auth/AuthContext";
import formatDate from "../../utils/date/formatDate";
import Task from "../../components/Task/Task";
import SettingsModal from "./components/SettingsModal/SettingsModal";
import {useParams} from "react-router";
import {useNavigate} from "react-router";
import {useRef} from "react";
import getUserById from "../../utils/users/getUserById.js";
import ManageMember from "./components/ManageMember/ManageMember";
import uploadProfilePhoto from "../../utils/users/uploadProfilePhoto";
import deleteProfilePhoto from "../../utils/users/deleteProfilePhoto";
import type { AuthContextType } from "../../interfaces/AuthInterfaces";
import type TaskType from "../../interfaces/task.interface";
import type  User from "../../interfaces/user.interface";



function ProfilePage() {
  const navigate = useNavigate();
  const { id } = useParams();
  const { user, update } = useContext(AuthContext) as AuthContextType;
  const [profileUser, setProfileUser] = useState<User | null>(null);
  const [profilePicture, setProfilePicture] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const isOwnProfile = !id || user?.id.toString() === id;

  useEffect(() => {
    (async () => {
      console.log(JSON.stringify(import.meta.env.VITE_API_URL));
      if (!isOwnProfile && id) {
        const res = await getUserById(Number(id));
        if (res.status === 404) {
          navigate("/404");
          return;
        }
        if (res.status !== 200) {
          console.log("Erreur lors du chargement du profil", res);
          return;
        }
        setProfileUser(res.data);
      } else {
        setProfileUser(user);
        if (user?.profile_photo_path) {
          setProfilePicture(`${import.meta.env.VITE_API_URL}/storage/${user.profile_photo_path}`);
        }
      }
    })();
  }, [user, id]);

  const handleEditPictureClick = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    try {
      const res = await uploadProfilePhoto(file);
      if (res.ok) {
        setProfilePicture(`${import.meta.env.VITE_API_URL}/storage/${res.data.profile_photo_path}`);
        console.log("Photo mise à jour")
        await update();
      } else {
        console.log(res.data?.message || res.error || "Erreur lors de l'upload.");
      }
    } catch (err) {
      console.log("Erreur réseau.");
    }
  };
  const handleDeletePicture = async () => {
    
       await deleteProfilePhoto();
       setProfilePicture(null);
  };

  return (
    <div className={styles.container}>
      <div className={`${styles.profileboard} glassCard`}>
        <div className={styles.contentWrapper}>
          <div className={styles.profilePictureContainer} onClick={isOwnProfile ? handleEditPictureClick : undefined} style={isOwnProfile ? { cursor: "pointer" } : {}}>
            <img
                src={isOwnProfile ? (profilePicture || "/react.svg") : "/react.svg"}
                alt="Photo de profil"
                className={styles.profilePicture}
            />
            {isOwnProfile && (
                <div className={styles.pictureOverlay}>
                  Modifier
                </div>
            )}
          </div>

          <input type="file" ref={fileInputRef} onChange={handleFileChange} accept="image/*" style={{ display: "none" }}/>
          <input
            type="file"
            ref={fileInputRef}
            onChange={handleFileChange}
            accept="image/*"
            style={{ display: "none" }}
          />

          <div className={styles.description}>
            <div className={styles.headerProfile}>
              <h2>
                {profileUser?.name} {profileUser?.lastname}
              </h2>
              {user?.isAdmin && profileUser && !isOwnProfile && (
                <ManageMember userToManage={profileUser} />
              )}
              {isOwnProfile && (
                  <div className={styles.settingAccount}>
                    <SettingsModal />
                  </div>
              )}
            </div>

            <div className={styles.topDescription}>
              <div className={`${styles.infoBlock} glassBorder`}>
                <p><strong>Role :</strong> {profileUser?.role}</p>
                <p><strong>Membre depuis :</strong> {profileUser && formatDate(profileUser.created_at)}</p>
              </div>

              <div className={`${styles.infoBlock} glassBorder`}>
                <p><strong>Mail :</strong> {profileUser?.email}</p>
                <p><strong>Téléphone :</strong> {profileUser?.phone ?? "Non renseigné"}</p>
              </div>

            </div>

            <h2>Tâches :</h2>
            {profileUser?.tasks.length ? (
              profileUser.tasks.map((task) => <Task key={task.id} task={task} />)
            ) : (
              <p>Aucune tâche.</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default ProfilePage;