import * as DateUtils from "utils/DateUtils"

export const defaultHomePage = '/dashboard'

// ** Checks if an object is empty (returns boolean)
export const isObjEmpty = obj => {
    if (obj === null || obj === undefined) {
        return true
    }

    return Object.keys(obj).length === 0
}

// ** Returns K format from a number
export const kFormatter = num => (num > 999 ? `${(num / 1000).toFixed(1)}k` : num)

// ** Converts HTML to string
export const htmlToString = html => html.replace(/<\/?[^>]+(>|$)/g, '')

// ** Checks if the passed date is today
const isToday = date => {
    const today = new Date()
    return (
        /* eslint-disable operator-linebreak */
        date.getDate() === today.getDate() &&
        date.getMonth() === today.getMonth() &&
        date.getFullYear() === today.getFullYear()
        /* eslint-enable */
    )
}

/**
 ** Format and return date in Humanize format
 ** Intl docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format
 ** Intl Constructor: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
 * @param {String} value date to format
 * @param {Object} formatting Intl object to format with
 */
export const formatDate = (value, formatting = {month: 'short', day: 'numeric', year: 'numeric'}) => {
    if (!value) return value
    return new Intl.DateTimeFormat('en-US', formatting).format(new Date(value))
}

// ** Returns short month of passed date
export const formatDateToMonthShort = (value, toTimeForCurrentDay = true) => {
    const date = new Date(value)
    let formatting = {month: 'short', day: 'numeric'}

    if (toTimeForCurrentDay && isToday(date)) {
        formatting = {hour: 'numeric', minute: 'numeric'}
    }

    return new Intl.DateTimeFormat('en-US', formatting).format(new Date(value))
}

/**
 ** Return if user is logged in
 ** This is completely up to you and how you want to store the token in your frontend application
 *  ? e.g. If you are using cookies to store the application please update this function
 */
export const isUserLoggedIn = () => localStorage.getItem('userData') != null
export const getUserData = () => JSON.parse(localStorage.getItem('userData'))
export const isAdminLoggedIn = () =>{
    if (localStorage.getItem('userData') != null){
        return JSON.parse(localStorage.getItem('userData')).role === 'admin'
    }
}
export const isGLDLoggedIn = () =>{
    if (localStorage.getItem('userData') != null){
        return JSON.parse(localStorage.getItem('userData')).type === 'GLD'
    }
}
export const isINDLoggedIn = () =>{
    if (localStorage.getItem('userData') != null){
        return JSON.parse(localStorage.getItem('userData')).type === 'IND'
    }
}
export const isORGLoggedIn = () =>{
    if (localStorage.getItem('userData') != null){
        return JSON.parse(localStorage.getItem('userData')).type === 'ORG'
    }
}
export const isPrimaryLoggedIn = () =>{
    if (localStorage.getItem('userData') != null){
        return JSON.parse(localStorage.getItem('userData')).role === 'primary'
    }
} 
export const isCreditorLoggedIn = () =>{
    if (localStorage.getItem('userData') != null){
        return JSON.parse(localStorage.getItem('userData')).creditor
    }
} 
export const isDummyLoggedIn = () =>{
    if (localStorage.getItem('userData') != null){
        return JSON.parse(localStorage.getItem('userData')).role === 'dummy'
    }
}
export const haveOrgPaymentRecord = () =>{
    if (localStorage.getItem('userData') != null){
        return JSON.parse(localStorage.getItem('userData')).orgPaymentRecord
    }
}
export const haveOrgDnRecord = () =>{
    if (localStorage.getItem('userData') != null){
        return JSON.parse(localStorage.getItem('userData')).orgDnRecord
    }
}
export const checkSysEnv = () =>{
    if (localStorage.getItem('sysEnv') != null){
        // console.log(localStorage.getItem('sysEnv'))
        return localStorage.getItem('sysEnv')
    }
}
export const checkPaymentSuspension = () =>{
    if (localStorage.getItem('paymentSuspension') != null){
        return JSON.parse(localStorage.getItem('paymentSuspension'))
    }
}
/**
 ** This function is used for demo purpose route navigation
 ** In real app you won't need this function because your app will navigate to same route for each users regardless of ability
 ** Please note role field is just for showing purpose it's not used by anything in frontend
 ** We are checking role just for ease
 * ? NOTE: If you have different pages to navigate based on user ability then this function can be useful. However, you need to update it.
 * @param {String} userRole Role of user
 */
export const getHomeRouteForLoggedInUser = userRole => {
    if (userRole === 'admin') return defaultHomePage
    if (userRole === 'user') return defaultHomePage
    if (userRole === 'client') return '/access-control'
    return '/login'
}

// ** React Select Theme Colors
export const selectThemeColors = theme => ({
    ...theme,
    colors: {
        ...theme.colors,
        primary25: '#7367f01a', // for option hover bg-color
        primary: '#7367f0', // for selected option bg-color
        neutral10: '#008a9a', // for tags bg-color
        neutral20: '#ededed', // for input border-color
        neutral30: '#ededed' // for input hover border-color
    }
})

export const momentMinuteDiff = (date1, date2) => {
    return moment.duration(moment(new Date(date1)).diff(moment(new Date(date2)))).asMinutes()
}

export const minuteDiff = (nowDate, createdAtDate) => {
    let diff = (nowDate.getTime() - new Date(createdAtDate)) / 1000
    diff /= 60
    return Math.abs(Math.ceil(diff))
}

export const gazetteLength = (length,noOfPages) => {
    let countLength=0;
    if (noOfPages!==null){
        let pages = noOfPages
        countLength = pages*18 
    }else{
        countLength = length
    }
    return countLength+" cm"
}

export const toReceiptLanguage = (locale) => {
    if (locale === 'zh-CN' || locale === 'zh_CN') {
        return 'zh_CN';
    }
    if (locale === 'zh-HK' || locale === 'zh_HK') {
        return 'zh_HK';
    }
    return 'en';
}

export const formatPaymentParticularsLength = (row, intl) => {
    if (row.groupTitle === 'Private Bill') {
        const pages = row.noOfPages ?? 1;
        if (intl) {
            if (intl.locale === 'en') {
                return pages === 1 ? '1 page' : `${pages} pages`;
            }
            const pageLabel = intl.formatMessage({ id: 'pages' });
            return `${pages} ${pageLabel}`;
        }
        return pages === 1 ? '1 page' : `${pages} pages`;
    }
    return `${row.length ?? 0} cm`;
}

export const getUserId = () =>{
    if (localStorage.getItem('userData') != null){
        return JSON.parse(localStorage.getItem('userData')).id
    }
} 

export const isPasswordExpiry = () =>{
    var date;
    if (localStorage.getItem('userData') != null){
        date =  JSON.parse(localStorage.getItem('userData')).passwordExpiryDate
    }
    if (date != null){
        var currentDate = new Date();
        var expirationDate = DateUtils.convertToDate(date);
    
        if (expirationDate < currentDate) {
            // console.log(true)
            return true; // The date has expired
        } else {
            // console.log(false)
            return false; // The date is still valid
        }
    }else{
        return false;
    }
    
}

export const checkIsOnlyOnlinePaymentByIssueDate = (date) => {
    const targetDate = new Date(2026, 0, 28, 0, 0, 0); // hardcode new Date(2026, 0, 28, 0, 0, 0) 28 Jan 2026
    const checkDate = DateUtils.convertToDate(date)
    if (isDummyLoggedIn()){
        return false;
    }
    // console.log(checkDate)
    // console.log(targetDate)
    if (checkDate >= targetDate) {
        return true
    } else {
        return false;
    }
}

export const checkIsOnlyOnlinePayment = () => {
    const targetDate = new Date(2026, 0, 28, 0, 0, 0) // hardcode new Date(2026, 0, 28, 0, 0, 0) 28 Jan 2026
    const checkDate = DateUtils.convertToDate(new Date())
    if (isDummyLoggedIn()){
        return false;
    }
    // console.log(checkDate)
    // console.log(targetDate)
    if (checkDate >= targetDate) {
        return true
    } else {
        return false;
    }
}

export const checkMarkAsCreditClient = () => {
    const targetDate = new Date(2026, 0, 28, 0, 0, 0) // hardcode new Date(2026, 0, 28, 0, 0, 0) 28 Jan 2026
    const checkDate = DateUtils.convertToDate(new Date())
    // console.log(targetDate)
    // console.log(checkDate >= targetDate)
    if (checkDate >= targetDate) {
        return true
    } else {
        return false;
    }
}

export const checkIsNoPaymentByCreateDate = (date) => {
    const targetDate = new Date(2026, 0, 28, 0, 0, 0) // hardcode new Date(2026, 0, 28, 0, 0, 0) 28 Jan 2026
    const checkDate = DateUtils.convertToDate(date)
    if (isDummyLoggedIn()){
        return false;
    }
    // console.log(checkDate)
    // console.log(targetDate)
    if (checkDate <= targetDate && isCreditorLoggedIn()) {
        return true
    } else {
        return false;
    }
}