import getXSRFToken from "../../utils/getXSRF.js";
// import fetchWrapper from "../../utils/fetchWrapper";
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.jsx";

import uploadProfilePhoto from "../../utils/users/uploadProfilePhoto";
import deleteProfilePhoto from "../../utils/users/deleteProfilePhoto.js";


interface TaskType {
  id: number;
  name: string;
  description: string;
  location: string;
  start: string;
  end: string;
  max_participants: number;
  events_id: number;
  created_at: string;
  updated_at: string;
  pivot: {
    user_id: number;
    task_id: number;
  };
}


interface User {
    id: number;
    name: string;
    lastname: string;
    role: string;
    email: string;
    phone: string | null;
    created_at: string;
    isAdmin: boolean;
    tasks: TaskType[];
    profile_photo_path?: string | null;
}

interface AuthContextType {
    user: User | null;
    update: () => void;
}

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 [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = 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(id);
        if (res.status === 404) {
          navigate("/404");
          return;
        }
        if (res.status !== 200) {
          console.error("Erreur lors du chargement du profil", res);
          return;
        }
        setProfileUser(res.data);
      } else {
        //update();
        setProfileUser(user);
        if (user?.profile_photo_path) {
          setProfilePicture(`${import.meta.env.VITE_API_URL}/storage/${user.profile_photo_path}`);
          //setProfilePicture(`${import.meta.env.VITE_API_URL}/${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}`);
        //setProfilePicture(`${import.meta.env.VITE_API_URL}/${res.data.profile_photo_path}`);
        setSuccess("Photo mise à jour !");
        setError(null);
        await update();
      } else {
        setError(res.data?.message || res.error || "Erreur lors de l'upload.");
        setSuccess(null);
      }
    } catch (err) {
      setError("Erreur réseau.");
      setSuccess(null);
    }
  };
  const handleDeletePicture = async () => {
    
       deleteProfilePhoto();
       setProfilePicture(null);
  };

  return (
    <div className={styles.container}>
      <div className={`${styles.profileboard} glassCard`}>
        <div className={styles.contentWrapper}>
          <div className={styles.profilePictureContainer}>
            <img
              src={isOwnProfile ? (profilePicture || "/react.svg") : "/react.svg"}
              alt="Photo de profil"
              className={styles.profilePicture}
            />
          </div>

          {isOwnProfile && (
            <div className={styles.pictureButtons}>
              <button onClick={handleEditPictureClick} className={styles.editPictureButton}>
                Modifier la photo
              </button>
              {user?.profile_photo_path && (
                <button onClick={handleDeletePicture} className={styles.editPictureButton}>
                  Supprimer
                </button>
              )}
            </div>
          )}

          <input
            type="file"
            ref={fileInputRef}
            onChange={handleFileChange}
            accept="image/*"
            style={{ display: "none" }}
          />
          {error && <p className={styles.errorMessage}>{error}</p>}
          {success && <p className={styles.successMessage}>{success}</p>}

          <div className={styles.description}>
            <div className={styles.headerProfile}>
              <h2>
                {profileUser?.name} {profileUser?.lastname}
              </h2>
              {user?.isAdmin && profileUser && !isOwnProfile && (
                <ManageMember userToManage={profileUser} />
              )}
            </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>

              {isOwnProfile && (
                <div className={styles.settingImage}>
                  <SettingsModal />
                </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;