import axios from 'axios';
import moment from 'moment-timezone';
import Swal from 'sweetalert2';
// import { useRequest } from "../components/App/request";
// import useFetchData from "@/components/App/useFetchData";
import Cookies from 'js-cookie';
import { API_ERROR } from '@/types/interfaces';



export const setAuthToken = (token: string | boolean) => {
  if (typeof token == 'string') {
    Cookies.set('accessToken', token);
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  } else {
    delete axios.defaults.headers.common['Authorization'];
  }
};


export const toastr = (message: string, icon: string, title?: string) => {
  return null
  const Toast = Swal.mixin({
    // toast: true,
    position: 'top-end',
    showConfirmButton: false,
    timer: 3000,
    showCloseButton: true,
    timerProgressBar: true,
    // focusCancel: true,
    didOpen: toast => {
      toast.addEventListener('mouseenter', Swal.stopTimer);
      toast.addEventListener('mouseleave', Swal.resumeTimer);
    },
  });

  Toast.fire({
    iconHtml: '',
    title: '',
    html: `
        <div class="TosterUI">
            <img src="/assets/icons/${icon === 'success' ? 'GreenCheck' : 'Error'}.svg" />
            ${title ? `<h4 class="${icon}">${title}</h4>` : ''}
            <p>${message}</p>        
        </div>`,
    // ${statusCode ? `<p class='mt-1'>Error: ${statusCode}</p>`:''}
    customClass: {
      popup: "fireToaster",
    },
    showClass: {
      backdrop: 'swal2-noanimation', // disable backdrop animation
      popup: '', // disable popup animation
      icon: '', // disable icon animation
    },
    hideClass: {
      popup: '', // disable popup fade-out animation
    },
    timer: 3000,
    timerProgressBar: true,
    heightAuto: true,
    width: '356px',
    grow: 'row',
  });
};


export const toastrC = (message: string, icon: string, title?: string) => {
  const Toast = Swal.mixin({
    // toast: true,
    position: 'center',
    showConfirmButton: false,
    timer: 3000,
    showCloseButton: true,
    timerProgressBar: true,
    // focusCancel: true,
    didOpen: toast => {
      toast.addEventListener('mouseenter', Swal.stopTimer);
      toast.addEventListener('mouseleave', Swal.resumeTimer);
    },
  });

  Toast.fire({
    iconHtml: '',
    title: '',
    html: `
        <div class="TosterUI">
            <img src="/assets/${icon === 'success' ? 'check75' : 'close75'}.png"/>
            ${title ? `<h4 class="${icon}">${title}</h4>` : ''}
            <p>${message}</p>        
        </div>`,
    // ${statusCode ? `<p class='mt-1'>Error: ${statusCode}</p>`:''}
    customClass: {
      popup: "fireToaster",
    },
    showClass: {
      backdrop: 'swal2-noanimation', // disable backdrop animation
      popup: '', // disable popup animation
      icon: '', // disable icon animation
    },
    hideClass: {
      popup: '', // disable popup fade-out animation
    },
    timer: 3000,
    timerProgressBar: true,
    heightAuto: true,
    width: '30%',
    grow: 'row',
  });
};



// export const formatDate = (date: string | Date, type?: string | null | undefined, iso?: boolean) => {
//   if (!date) date = new Date(); // If date is not provided, default to current date
//   if (iso) return moment(date).tz('Asia/Kolkata').toISOString(); // Convert date to ISO format
//   const formattedDate = moment(date)
//     .tz('Asia/Kolkata')
//     .format(type || 'DD/MM/YYYY'); // Format date as DD/MM/YYYY hh:mm:ss A with timezone offset +10:00 (Australia/Sydney)

//   return formattedDate;
// };

export const formatDate = (date: string | Date, iso?: boolean, isSecondFormat = false) => {
  if (!date) date = new Date(); // Default to current date
  if (iso) return moment(date).tz("Asia/Kolkata").toISOString(); // Convert to ISO format
  if (isSecondFormat) {
    return moment(date).tz("Asia/Kolkata").format("DD-MMM-YY HH:mm:ss");
  }
  const formattedDate = moment(date)
    .tz("Asia/Kolkata")
    .format("DD-MMM-YY"); // Format as "20-Feb-25"

  return formattedDate;
};

export const formatYearDate = (date: string | Date, iso?: boolean) => {
  if (!date) date = new Date(); // Default to current date
  if (iso) return moment(date).tz("Asia/Kolkata").toISOString(); // Convert to ISO format

  const formattedDate = moment(date)
    .tz("Asia/Kolkata")
    .format("YY-MMM"); // Format as "20-Feb-25"

  return formattedDate;
};

export const formatDateYear = (date: string | Date, iso?: boolean) => {
  if (!date) date = new Date(); // Default to current date
  if (iso) return moment(date).tz("Asia/Kolkata").toISOString(); // Convert to ISO format

  const formattedDate = moment(date)
    .tz("Asia/Kolkata")
    .format("MMM-YY"); // Format as "20-Feb-25"

  return formattedDate;
};

export const formatDateWithFormatType = (date: string | Date, formatType: string) => {
  return moment(date).tz("Asia/Kolkata").format(formatType);
}

export const formatDateOnly = (date: string | Date, type?: string | null | undefined, iso?: boolean) => {
  if (!date) date = new Date(); // If date is not provided, default to current date
  if (iso) return moment(date).tz('Asia/Kolkata').toISOString(); // Convert date to ISO format

  // Format date as DD/MM/YYYY if no type is provided
  const formattedDate = moment(date)
    .tz('Asia/Kolkata')
    .format(type || 'DD/MM/YYYY'); // Changed to return only date

  return formattedDate;
};

export const isValidDate = (value: string) => {
  if (/[^0-9/]/.test(value)) {
    return false;
  }
  if (!/([^/]*\/){2}/.test(value)) return false;

  if (moment(value, 'DD/MM/YYYY').isValid()) return 'DD/MM/YYYY';
  if (moment(value, 'M/D/YY').isValid()) return 'M/D/YY';
  if (moment(value, 'YYYY/MM/DD').isValid()) return 'YYYY/MM/DD';
  if (moment(value, 'DD/MM/YYYY').isValid()) return 'DD/MM/YYYY';
  return false;
};


export const handleErrors = (res: API_ERROR) => {
  let msg = '';
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const { statusCode, message, error } = res;
  if (error) {
    if (typeof error == 'object' && Object.keys(error)?.length) {
      Object.entries(error).map(([, value]) => {
        msg += capitalize(value?.toString() || '') + '\n';
      });
    } else {
      if (typeof message === 'string') {
        msg = message;
      } else if (typeof error == 'string') {
        msg = error;
      }
    }

    if (typeof msg === 'string' && msg?.toLowerCase() == 'unauthorized') {
      logout();
    }
  } else {
    if (typeof message === 'string') {
      msg = message;
      if (typeof msg === 'string' && msg?.toLowerCase() == 'unauthorized') {
        logout();
      }
    } else if (typeof error == 'string') {
      msg = error;
    }
  }
  toastr(msg, 'error', 'Error Occurred');
};

export const logout = async () => {
  // Clear frontend state
  setAuthToken(false);
  Cookies.remove('accessToken');
  Cookies.remove('rememberme');

  // Redirect
  if (typeof window !== 'undefined') {
    window.location.href = '/auth/login';
  }
  // setAuthToken(false);
  // Cookies.remove('accessToken');
  // Cookies.remove('rememberme');
  // if (window) window.location.href = '/auth/login';
};


export const setHeader = (token: string | boolean, tokenName: string) => {
  if (typeof token == 'string') {
    Cookies.set(tokenName, token);
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  } else {
    delete axios.defaults.headers.common['Authorization'];
  }
};


export const capitalize = (title: string) => (title ? title.charAt(0).toUpperCase() + title.slice(1) : '');


export const formatDateHelper = (
  date: string | Date | null,
  type?: string | null | undefined
) => {
  if (!date) return null;
  // if (iso) return moment(date).toISOString(); // Convert date to ISO format

  const formattedDate = moment(date).format(type || "DD/MM/YYYY hh:mm:ss A"); // Set timezone offset to +10:00 (Australia/Sydney) and format date
  const isValid = moment(
    formattedDate,
    type || "DD/MM/YYYY hh:mm:ss A",
    true
  ).isValid(); // Check if the formatted date is valid
  if (isValid) {
    return formattedDate;
  } else {
    return moment(date, type || "DD/MM/YYYY hh:mm:ss A").format(
      type || "DD/MM/YYYY hh:mm:ss A"
    );
  }
};


export const debounce = (fn, delay) => {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
};


export const getStartInitialDate = (accountCreationDate: moment.Moment) => {
  const currentYear = moment().year();
  const accountYear = accountCreationDate.year();

  // If account was created in current year, use account creation date
  if (accountYear === currentYear) {
    return accountCreationDate.format('DD/MM/YYYY');
  }

  // If account was created in a previous year, use start of current year
  if (accountYear < currentYear) {
    return moment().startOf('year').format('DD/MM/YYYY');
  }

  // If account was created in a future year (shouldn't happen, but just in case)
  return accountCreationDate.format('DD/MM/YYYY');
}

export const getExpiryStatus = (date: string | Date) => {
  if (!date) return '';
  const now = moment().startOf('day');
  const expiry = moment(date).startOf('day');
  const diff = expiry.diff(now, 'days');
  if (diff > 0) {
    return `Expires ${formatDate(date)} - ${diff} day${diff === 1 ? '' : 's'} remaining`;
  } else if (diff === 0) {
    return `Expires ${formatDate(date)} - 0 days`;
  } else {
    const absDiff = Math.abs(diff);
    return `Expired: ${formatDate(date)} - Since ${absDiff} day${absDiff === 1 ? '' : 's'} `;
  }
};


export const getExpiryStatusTaxed = (date: string | Date) => {
  if (!date) return '';
  const now = moment().startOf('day');
  const expiry = moment(date).startOf('day');
  const diff = expiry.diff(now, 'days');
  if (diff > 0) {
    return `Tax due: ${formatDate(date)} - ${diff} day${diff === 1 ? '' : 's'} remaining`;
  } else if (diff === 0) {
    return `Tax due ${formatDate(date)} - 0 days `;
  } else {
    const absDiff = Math.abs(diff);
    return `Tax due: ${formatDate(date)} - Since ${absDiff} day${absDiff === 1 ? '' : 's'}`;
  }
};