import { useState, useEffect } from 'react';
import settingService from '../services/SettingService';
import { MEDIA_URL } from '../../../../utils/Constant';

const useSettings = () => {
  const [profile, setProfile] = useState(null);
  const [selectedImage, setSelectedImage] = useState(null);
  const [idUser, setIdUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [loadingUpdate, setLoadingUpdate] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(false);
  const thumbPath = `${MEDIA_URL}/avatar/`;

  useEffect(() => {
    const fetchData = async () => {
        try {
            const data = await settingService.fetchProfile();
            setProfile(data.payload);
            setIdUser(data.payload.ID)
        } catch (err) {
            setError(err);
        } finally {
            setLoading(false);
        }
    };
    fetchData();
  }, []);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setProfile((prevProfile) => ({
      ...prevProfile,
      [name]: value,
    }));
  };

  const handleImageChange = (e) => {
    const file = e.target.files[0];
    if (file && file.size <= 5 * 1024 * 1024) {
      setSelectedImage(file);
    } else {
      setError('File size must be less than 5 MB');
    }
  };
  
  const handleSubmitProfile = async (e) => {
    e.preventDefault();
    setLoadingUpdate(true);
    setError(null);
    setSuccess(false);

    const formData = new FormData();
    formData.append('NAME_USERS', profile.NAME_USERS);
    formData.append('EMAIL', profile.EMAIL);
    formData.append('NISN', profile.NISN);

    if (selectedImage) {
      formData.append('PICTURE', selectedImage);
    }

    try {
      await settingService.updateProfile(idUser, formData);
      setSuccess(true); 
    } catch (err) {
      setError('Failed to update profile');
    } finally {
      setLoadingUpdate(false);
    }
  };



  //Change Pass
  const [formData, setFormData] = useState({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
  });

  const [loadingPass, setLoadingPass] = useState(false);
  const [errorPass, setErrorPass] = useState(null);
  const [successPass, setSuccessPass] = useState(false);

  const handleInputPassChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const handleChangePass = async (e) => {
    e.preventDefault();
    setLoadingPass(true);
    setErrorPass(null);
    setSuccessPass(false);

    const passwordData = {
      OLD_PASSWORD: formData.oldPassword,
      PASSWORD: formData.newPassword,
      CONFIRM_PASSWORD: formData.confirmPassword,
    };

    // Validasi bahwa password baru dan confirm password cocok
    if (formData.newPassword !== formData.confirmPassword) {
      setErrorPass("New Password and Confirm Password don't match");
      setLoadingPass(false);
      return;
    }

    try {
      // Panggil API untuk update password
      await settingService.updatePassword(idUser, passwordData);
      setSuccessPass(true); // Tampilkan pesan sukses jika berhasil
    } catch (err) {
      setErrorPass('Failed to update password: ' + err.message);
    } finally {
      setLoadingPass(false); // Reset loading setelah selesai
    }
  };

  const resetForm = () => {
    setFormData({
      oldPassword: '',
      newPassword: '',
      confirmPassword: '',
    });
    setSuccess(false);
  };

  const resetStatus = () => {
    setLoadingUpdate(false);
    setError(null);
    setSuccess(false);
    setLoadingPass(false);
    setErrorPass(null);
    setSuccessPass(false);
  }

  return {
    profile,
    selectedImage,
    loading,
    loadingUpdate,
    error,
    success,
    handleInputChange,
    handleImageChange,
    handleSubmitProfile,
    thumbPath,
    
    // Change Pass 
    formData,
    handleInputPassChange,
    handleChangePass,
    loadingPass,
    errorPass,
    successPass,
    resetForm,
    resetStatus
  };

};

export default useSettings;
