import { notifications } from '@mantine/notifications';
import axios from 'axios';

interface SendOtpPayload {
  mobileNumber?: string;
  type: string;
  amount?: number;
  beneficiary?: string;
  ifsc?: string;
  acctFrom?: string;
  acctTo?: string;
  ref?: string;
  date?: string;
  userOtp?: string;
  username?: string
}

function getStoredMobileNumber(): string | null {
  const mobileNumber = localStorage.getItem('remitter_mobile_no');
  // const mobileNumber = "7890544527";
  if (!mobileNumber) {
    notifications.show({
      title: 'Missing Mobile Number',
      message: 'Mobile number not found. Please re-login or update your profile.',
      color: 'red',
    });
    return null;
  }
  return mobileNumber;
}

export async function sendOtp(payload: SendOtpPayload) {
  try {
    const mobileNumber = payload.mobileNumber || getStoredMobileNumber();
    const response = await axios.post(
      'http://localhost:8080/api/otp/send',
      { ...payload, mobileNumber },
      { headers: { 'Content-Type': 'application/json' } }
    );
    console.log('otp sended.');
    return response.data;
  } catch (error: any) {
    console.error('Error sending OTP:', error.response?.data || error.message);
    throw error.response?.data || error;
  }
}

export async function verifyOtp(otp: string) {
  try {
    const mobileNumber = getStoredMobileNumber();
    const response = await axios.post(
      `http://localhost:8080/api/otp/verify?mobileNumber=${mobileNumber}`,
      { otp },
      { headers: { 'Content-Type': 'application/json' } }
    );
    console.log('Otp verified');
    return response.data;
  } catch (error: any) {
    console.error('Error verifying OTP:', error.response?.data || error.message);
    throw error.response?.data || error;
  }
}

export async function verifyLoginOtp(otp: string, mobileNumber: string) {
  try {
    // const mobileNumber = getStoredMobileNumber();
    const response = await axios.post(
      `http://localhost:8080/api/otp/verify?mobileNumber=${mobileNumber}`,
      { otp },
      { headers: { 'Content-Type': 'application/json' } }
    );
    console.log('Otp verified.');
    return response.data;
  } catch (error: any) {
    console.error('Error verifying OTP:', error.response?.data || error.message);
    throw error.response?.data || error;
  }
}