import React, { createContext, useState } from 'react';
import { apiConfig } from '@/config/api.config';
import { useCallApi } from '@/hooks';
import { toast } from 'sonner';
import axios from 'axios';
import { useAuthContext } from '@/auth';

interface Password {
  password: string;
  retype_password: string;
  username: string;
  current_password: string;
}

interface Profile {
  name: string;
  email: string;
  username: string;
}

interface ContextProps {
  password: Password | null;
  profile: Profile | null;
  setPassword: (password: Password) => Promise<void>;
  setProfile: (profile: Profile) => Promise<void>;
}

const initialProps: ContextProps = {
  profile: null,
  password: null,
  setPassword: async () => {},
  setProfile: async () => {}
};

const AccountUserProfileContext = createContext<ContextProps>(initialProps);

const API_URL = apiConfig.service_dashboard;

const AccountUserProfileContextProvider = ({ children }: { children: React.ReactNode }) => {
  /* state */
  const { login } = useAuthContext();
  const [profile, setProfile] = useState<Profile | null>(null);
  const [password, setPassword] = useState<Password | null>(null);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });

  const { PutData } = useCallApi();
  const { PostData } = useCallApi();
  const handleSetPassword = async (newPassword: Password) => {
    setPassword(newPassword);

    const handleError = (error: any, defaultMessage: string) => {
      const errorMessage = error?.response?.data?.message || error?.message || defaultMessage;
      setAlert({ show: true, message: errorMessage });
      toast.error(errorMessage);
    };

    try {
      const validate = await PostData(`${API_URL}/login`, {
        password: newPassword.current_password,
        username: newPassword.username
      });

      if (!validate || !validate.status) {
        toast.error('Current password validation failed.');
        return;
      }

      const response = await PutData(`${API_URL}/user/update_password`, {
        password: newPassword.password,
        retype_password: newPassword.retype_password
      });

      if (response && response.status) {
        toast.success('Password updated successfully!');
      } else {
        toast.error(response?.message || 'Failed to update password.');
      }
    } catch (error: any) {
      handleError(error, 'Failed to update password. Please try again.');
    }
  };

  const handleSetProfile = async (newProfile: Profile) => {
    try {
      setProfile(newProfile);

      const response = await PutData(`${API_URL}/user/update_profile/`, {
        name: newProfile.name,
        email: newProfile.email,
        username: newProfile.username
      });

      toast.success('Profile updated successfully.');
    } catch (error: any) {
      const errorMessage = error?.message || 'Failed to update Profile. Please try again.';
      setAlert({ show: true, message: errorMessage });
      toast.error(errorMessage);
    }
  };

  return (
    <AccountUserProfileContext.Provider
      value={{
        password,
        profile,
        setPassword: handleSetPassword,
        setProfile: handleSetProfile
      }}
    >
      {children}
    </AccountUserProfileContext.Provider>
  );
};

export { AccountUserProfileContextProvider, AccountUserProfileContext };
