import {
  convertToIranianTime,
  convertPersianToEnglishNumerals,
} from "../../../../../utils/formatTime";
import { fromJalali } from "../../../../../utils/jalali";

export const convertGregorianToPersian = (gregorianDateString) => {
  if (!gregorianDateString || typeof gregorianDateString !== "string") {
    return "";
  }

  // Check if the date is already in Persian format (YYYY/MM/DD with year < 1500)
  const persianPattern = /^\d{4}\/\d{2}\/\d{2}$/;
  if (persianPattern.test(gregorianDateString)) {
    const year = parseInt(gregorianDateString.split("/")[0]);
    // If year is < 1500, it's likely Persian, return as is
    if (year < 1500) {
      return gregorianDateString;
    }
  }

  // Try to convert using convertToIranianTime
  try {
    return convertToIranianTime(gregorianDateString);
  } catch (error) {
    console.error("Error converting Gregorian date to Persian:", error);
    return gregorianDateString; // Return original on error
  }
};

export const convertPersianToGregorian = (persianDateString) => {
  if (!persianDateString || typeof persianDateString !== "string") {
    return "";
  }

  const normalizedDateString =
    convertPersianToEnglishNumerals(persianDateString);

  const gregorianPattern = /^\d{4}[-/]\d{2}[-/]\d{2}$/;
  if (gregorianPattern.test(normalizedDateString)) {
    const year = parseInt(normalizedDateString.split(/[-/]/)[0]);
    if (year > 1500) {
      return normalizedDateString.replace(/\//g, "-");
    }
  }

  const parts = normalizedDateString.split("/");
  if (parts.length !== 3) {
    return persianDateString;
  }

  const py = parseInt(parts[0]);
  const pm = parseInt(parts[1]);
  const pd = parseInt(parts[2]);

  if (isNaN(py) || isNaN(pm) || isNaN(pd)) {
    return persianDateString;
  }

  try {
    const gregorianDate = fromJalali(py, pm, pd);
    const year = gregorianDate.getFullYear();
    const month = String(gregorianDate.getMonth() + 1).padStart(2, "0");
    const day = String(gregorianDate.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  } catch (error) {
    console.error("Error converting Persian date to Gregorian:", error);
    return persianDateString;
  }
};

export const normalizeExternalApiDate = (dateString) => {
  if (!dateString || typeof dateString !== "string") {
    return "";
  }
  return convertPersianToEnglishNumerals(dateString);
};

export const normalizeDatabaseDate = (dateString) => {
  if (!dateString || typeof dateString !== "string") {
    return "";
  }
  const first10Chars = dateString.substring(0, 10);
  const normalizedDate = first10Chars.replace(/-/g, "/");
  return convertToIranianTime(normalizedDate);
};

export const formatDateForSubmitExternal = (dateString) => {
  if (!dateString || typeof dateString !== "string") {
    return "";
  }
  return convertPersianToEnglishNumerals(dateString);
};

export const formatDateForSubmitDatabase = (dateString) => {
  if (!dateString || typeof dateString !== "string") {
    return "";
  }

  const normalizedDate = convertPersianToEnglishNumerals(dateString);
  const persianPattern = /^\d{4}\/\d{2}\/\d{2}$/;

  if (persianPattern.test(normalizedDate)) {
    const year = parseInt(normalizedDate.split("/")[0]);
    if (year < 1500) {
      const parts = normalizedDate.split("/");
      const py = parseInt(parts[0]);
      const pm = parseInt(parts[1]);
      const pd = parseInt(parts[2]);

      if (!isNaN(py) && !isNaN(pm) && !isNaN(pd)) {
        try {
          const gregorianDate = fromJalali(py, pm, pd);
          const gy = gregorianDate.getFullYear();
          const gm = String(gregorianDate.getMonth() + 1).padStart(2, "0");
          const gd = String(gregorianDate.getDate()).padStart(2, "0");
          return `${gy}/${gm}/${gd}`;
        } catch (error) {
          console.error("Error converting Persian to Gregorian:", error);
        }
      }
    }
  }

  const gregorianPattern = /^\d{4}[-/]\d{2}[-/]\d{2}$/;
  if (gregorianPattern.test(normalizedDate)) {
    const year = parseInt(normalizedDate.split(/[-/]/)[0]);
    if (year > 1900) {
      return normalizedDate.replace(/-/g, "/");
    }
  }

  try {
    const date = new Date(normalizedDate);
    if (!isNaN(date.getTime())) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}/${month}/${day}`;
    }
  } catch (error) {
    console.error("Error formatting database date:", error);
  }

  return normalizedDate.replace(/-/g, "/");
};

/**
 * Always formats date for submit as Jalali YYYY/MM/DD with English numerals.
 * Used for birthDate and licenseExpireDate (and licenseIssueDate) in every scenario.
 * Example: "1403/02/26", "1404/06/10"
 */
export const formatDateForSubmit = (dateString) => {
  if (!dateString || typeof dateString !== "string") {
    return "";
  }

  const normalized = convertPersianToEnglishNumerals(dateString);

  // Already Jalali (YYYY/MM/DD, year < 1500): ensure zero-padded and return
  const persianPattern = /^\d{4}\/\d{1,2}\/\d{1,2}$/;
  if (persianPattern.test(normalized)) {
    const parts = normalized.split("/");
    const py = parseInt(parts[0], 10);
    const pm = parseInt(parts[1], 10);
    const pd = parseInt(parts[2], 10);
    if (py < 1500 && !isNaN(py) && !isNaN(pm) && !isNaN(pd)) {
      return `${py}/${String(pm).padStart(2, "0")}/${String(pd).padStart(
        2,
        "0"
      )}`;
    }
  }

  // Gregorian YYYY-MM-DD or YYYY/MM/DD: convert to Jalali
  const gregorianPattern = /^\d{4}[-/]\d{1,2}[-/]\d{1,2}$/;
  if (gregorianPattern.test(normalized)) {
    const [y, m, d] = normalized.split(/[-/]/).map((s) => parseInt(s, 10));
    if (y > 1500 && !isNaN(y) && !isNaN(m) && !isNaN(d)) {
      try {
        const gregorianDate = new Date(y, m - 1, d);
        const jalaliStr = convertToIranianTime(
          gregorianDate.toISOString().split("T")[0]
        );
        return convertPersianToEnglishNumerals(jalaliStr).replace(/-/g, "/");
      } catch (e) {
        console.error("Error converting to Jalali:", e);
      }
    }
  }

  // Fallback: try parsing as date then convert to Jalali
  try {
    const date = new Date(normalized.replace(/\//g, "-"));
    if (!isNaN(date.getTime())) {
      const iso = date.toISOString().split("T")[0];
      const jalaliStr = convertToIranianTime(iso);
      return convertPersianToEnglishNumerals(jalaliStr).replace(/-/g, "/");
    }
  } catch (e) {
    console.error("Error formatting date for submit:", e);
  }

  return normalized.replace(/-/g, "/");
};
