import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
import { getUserId, getToken } from '@/app/utils/token';

// Cancel User
export const cancelUser = createAsyncThunk(
  'auth/cancelUser',
  async (_, { rejectWithValue }) => { 
    try {
      const baseURL = process.env.NEXT_PUBLIC_API_URL_New;
      const token = getToken();
      const userId = getUserId();

      if (!token) {
        return rejectWithValue('No authentication token found');
      }

      if (!userId) {
        return rejectWithValue('User ID not found');
      }

      const response = await axios.patch(
        `${baseURL}/users/${userId}/cancel`,
        {},
        {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        }
      );

      if (response.data) {
        return {
          data: response.data,
          message: 'User cancelled successfully'
        };
      } else {
        return rejectWithValue('User cancellation failed');
      }
    } catch (error: any) {
      const errorMessage = error.response?.data?.message || 
                          error.response?.data?.error || 
                          'User cancellation failed';
      return rejectWithValue(errorMessage);
    }
  }
);

// Update Email
export const updateEmail = createAsyncThunk(
  'auth/updateEmail',
  async (email: string, { rejectWithValue }) => { // Only need email parameter
    try {
      const baseURL = process.env.NEXT_PUBLIC_API_URL_New;
      const token = getToken();
      const userId = getUserId();

      if (!userId) {
        return rejectWithValue('User ID not found');
      }

      const response = await axios.patch(
        `${baseURL}/users/${userId}/email`,
        { email: email },
        {
          headers: {
            'Content-Type': 'application/json',
            ...(token && { 'Authorization': `Bearer ${token}` })
          }
        }
      );

      if (response.data) {
        return {
          data: response.data,
          message: 'Email updated successfully'
        };
      } else {
        return rejectWithValue('Email update failed');
      }
    } catch (error: any) {
      const errorMessage = error.response?.data?.message || 
                          error.response?.data?.error || 
                          'Email update failed';
      return rejectWithValue(errorMessage);
    }
  }
);

// Update Organization Contact
export const updateOrganizationContact = createAsyncThunk(
  'auth/updateOrganizationContact',
  async (updateData: { 
    organization: string;
    person_to_contact: string;
  }, { rejectWithValue }) => { // Remove userId parameter
    try {
      const baseURL = process.env.NEXT_PUBLIC_API_URL_New;
      const token = getToken();
      const userId = getUserId();

      if (!userId) {
        return rejectWithValue('User ID not found');
      }

      const response = await axios.patch(
        `${baseURL}/users/${userId}/organization-contact`,
        {
          organization: updateData.organization,
          person_to_contact: updateData.person_to_contact
        },
        {
          headers: {
            'Content-Type': 'application/json',
            ...(token && { 'Authorization': `Bearer ${token}` })
          }
        }
      );

      if (response.data) {
        return {
          data: response.data,
          message: 'Organization contact updated successfully'
        };
      } else {
        return rejectWithValue('Organization contact update failed');
      }
    } catch (error: any) {
      const errorMessage = error.response?.data?.message || 
                          error.response?.data?.error || 
                          'Organization contact update failed';
      return rejectWithValue(errorMessage);
    }
  }
);

// Update Basic User Info
export const updateBasicUserInfo = createAsyncThunk(
  'auth/updateBasicUserInfo',
  async (updateData: { 
    christian_name: string;
    sur_name: string;
    name: string;
    date_of_birth: string;
    phone: string;
  }, { rejectWithValue }) => {
    try {
      const baseURL = process.env.NEXT_PUBLIC_API_URL_New;
      const token = getToken();
      const userId = getUserId();

      if (!token) {
        return rejectWithValue('No authentication token found');
      }

      if (!userId) {
        return rejectWithValue('User ID not found');
      }

      const response = await axios.patch(
        `${baseURL}/users/${userId}/profile-basic`,
        {
          christian_name: updateData.christian_name,
          sur_name: updateData.sur_name,
          name: updateData.name,
          date_of_birth: updateData.date_of_birth,
          phone: updateData.phone
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          }
        }
      );

      if (response.data) {
        return {
          data: response.data,
          message: 'Basic user info updated successfully'
        };
      } else {
        return rejectWithValue('Basic user info update failed');
      }
    } catch (error: any) {
      const errorMessage = error.response?.data?.message || 
                          error.response?.data?.error || 
                          'Basic user info update failed';
      return rejectWithValue(errorMessage);
    }
  }
);

// Update Password
export const updatePassword = createAsyncThunk(
  'auth/updatePassword',
  async (updateData: { 
    currentPassword: string;
    newPassword: string;
  }, { rejectWithValue }) => { // Remove userId and token parameters
    try {
      const baseURL = process.env.NEXT_PUBLIC_API_URL_New;
      const token = getToken();
      const userId = getUserId();

      if (!token) {
        return rejectWithValue('No authentication token found');
      }

      if (!userId) {
        return rejectWithValue('User ID not found');
      }

      const response = await axios.patch(
        `${baseURL}/users/${userId}/password`,
        {
          currentPassword: updateData.currentPassword,
          newPassword: updateData.newPassword
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          }
        }
      );

      if (response.data) {
        return {
          data: response.data,
          message: 'Password updated successfully'
        };
      } else {
        return rejectWithValue('Password update failed');
      }
    } catch (error: any) {
      const errorMessage = error.response?.data?.message || 
                          error.response?.data?.error || 
                          'Password update failed';
      return rejectWithValue(errorMessage);
    }
  }
);