import dayjs from 'dayjs';
import "dayjs/locale/zh-hk";
import "dayjs/locale/zh-cn";

var days_ZH = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
var days_CN = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];

export const datetimeStr = (date) =>{
    
    return dateFormat(date,"DD/MM/YYYY HH:mm:ss")
};

export const dateStr = (date) =>{
    return dateFormat(date,"DD/MM/YYYY")
};

export const dateValue = (date) =>{
    return dateFormat(date,"YYYY-MM-DD")
};


export const dateStr_Year = (date) =>{
    return dateFormat(date,'YYYY')
};

export const datetimeStr_Cht = (date) =>{ 
    return dateFormat(date,"YYYY年MM月DD日 HH:mm:ss")
};

export const dateStr_Cht = (date) =>{
    return dateFormat(date,"YYYY年MM月DD日")
};

export const dateStr_Eng = (date) =>{
    return dateFormat(date,"DD MMM YYYY")
};

export const datetimeFieldFormat = (date) =>{
    return dateFormat(date,"YYYY-MM-DDTHH:mm");
};

export const timeFormat = (date, locale) => {
    if (!date) return "";

    let d;

    // 支援 LocalDateTime array
    if (Array.isArray(date)) {
        const [y, m, d1, h = 0, min = 0, s = 0] = date;
        d = dayjs(new Date(y, m - 1, d1, h, min, s));
    } else {
        d = dayjs(date);
    }

    if (!d.isValid()) return "";

    const hour = d.hour();
    const minute = d.minute();

    if (locale === "en") {
        return d.format("h:mm a"); // 12:00 pm
    }

    const period = hour < 12 ? "上午" : "下午";
    const h12 = hour % 12 === 0 ? 12 : hour % 12;

    if (minute === 0) {
        return `${period}${h12}時`;
    }

    return `${period}${h12}時${minute}分`;
};



export const convertToDate = (date)=>{
    if(typeof date == 'number'){
        return dayjs(date).toDate();
    }else if(Array.isArray(date)){
        // if(date.length==3){
        //     return new Date(date[0],date[1]-1,date[2],0,0,0);
        // }else if(date.length==4){
        //     return new Date(date[0],date[1]-1,date[2],0,0,0);
        // }
        return new Date(date[0]
            ,date[1]-1
            ,date[2]
            ,date.length>=4?date[3]:0
            ,date.length>=5?date[4]:0
            ,date.length>=6?date[5]:0);
    }else if(typeof date == "string"){
        return new Date(date);
    }
    
    return date;
}

export const toDate = (date) => {
  if (date === null || date === undefined || date === '') return new Date(NaN);

  if (typeof date === 'number') {
    // support seconds or millis
    const ms = date < 1e12 ? date * 1000 : date;
    return new Date(ms);
  }

  if (Array.isArray(date)) {
    const [y, m, d, hh = 0, mm = 0, ss = 0] = date;
    return new Date(y, m - 1, d, hh, mm, ss);
  }

  if (typeof date === 'string') {
    const normalized = date.includes(' ') && !date.includes('T') ? date.replace(' ', 'T') : date;
    const d = new Date(normalized);
    return isNaN(d.getTime()) ? new Date(NaN) : d;
  }

  return date instanceof Date ? date : new Date(NaN);
};

export const formatDateForLocale = (date, intl, locale) => {
  const fmt = intl.formatMessage({ id: "paymentMethodDatetimeStrFormat" });
  let s = dateFormat(date, fmt) || "";

  return locale === "en"
    ? s.replace("am", "a.m.").replace("pm", "p.m.")
    : s.replace("am", "上午").replace("pm", "下午").replace("00分", "");
};

export const is18_00 = (date) => {
  const d = convertToDate(date);
  if (!d) return false;
  return d.getHours() === 18 && d.getMinutes() === 0;
};

export const dateFormat = (date, format) =>{
    date = convertToDate(date);
    if(date) return dayjs(date).format(format);
    return "";
};

export const dateFormatWithFix = (date, format, hours, minutes) =>{
    date = convertToDate(date);
    date.setHours(hours);
    date.setMinutes(minutes);
    if(date) return dayjs(date).format(format);
    return "";
};

export const getWeekdayStr_ZH = (date) =>{
    date = convertToDate(date);
    if(date) return days_ZH[date.getDay()]
    return "";
};

export const getWeekdayStr_CN = (date) =>{
    date = convertToDate(date);
    if(date) return days_CN[date.getDay()]
    return "";
};

const formatPickerAriaDate = (dateStr, locale) => {
  if (!dateStr) return "";

  // MUI may pass a full Date string; parse via native Date first
  const dNative = new Date(dateStr);
  const d = isNaN(dNative.getTime()) ? null : dNative;

  if (!d) return dateStr; // fallback if parsing fails

  // Format only the date part (ignore time/GMT)
  const dj = dayjs(d);

  if (locale === "zh-HK" || locale === "zh") {
    return dj.locale("zh-hk").format("YYYY年MM月DD日");
  }
  if (locale === "zh-CN") {
    return dj.locale("zh-cn").format("YYYY年MM月DD日");
  }
  return dj.locale("en").format("DD MMM YYYY");
};

export const getPickerLocaleText = (locale) => {
  if (locale === "zh-HK" || locale === "zh") {
    return {
      openDatePickerDialogue: (dateStr) => {
        const s = formatPickerAriaDate(dateStr, locale);
        return s ? `選擇日期，已選日期為 ${s}` : "選擇日期";
      }
    };
  }

  if (locale === "zh-CN") {
    return {
      openDatePickerDialogue: (dateStr) => {
        const s = formatPickerAriaDate(dateStr, locale);
        return s ? `选择日期，已选日期为 ${s}` : "选择日期";
      }
    };
  }

  return {
    openDatePickerDialogue: (dateStr) => {
      const s = formatPickerAriaDate(dateStr, locale);
      return s ? `Choose date, selected date is ${s}` : "Choose date";
    }
  };
};
