import { toPersianDigits } from "./persianNumberUtils";

const splitDateTime = (datetime1: string): { date: string; time: string } => {
  const normalized = datetime1.trim();

  if (!normalized) {
    return { date: "", time: "" };
  }

  // Legacy backend format: "date - time"
  if (normalized.includes(" - ")) {
    const [datePart = "", timePart = ""] = normalized.split(" - ");
    return { date: datePart.trim(), time: timePart.trim() };
  }

  // Locale format from toLocaleString: "date, time" or "date، time"
  const commaMatch = normalized.match(/^(.+?)[،,]\s*(.+)$/);
  if (commaMatch) {
    return { date: commaMatch[1].trim(), time: commaMatch[2].trim() };
  }

  // Date-only value
  return { date: normalized, time: "" };
};

export const extractDate = (datetime1?: string, timestamp?: Date): string => {
  if (datetime1) {
    return toPersianDigits(splitDateTime(datetime1).date);
  }
  if (timestamp) {
    // Format timestamp to Persian date only (no time)
    return toPersianDigits(timestamp.toLocaleDateString("fa-IR"));
  }
  return "";
};

export const extractTime = (datetime1?: string, timestamp?: Date): string => {
  if (datetime1) {
    const { time } = splitDateTime(datetime1);
    if (time) return toPersianDigits(time);
  }
  if (timestamp) {
    // Format timestamp to time only
    return formatTimestamp(timestamp);
  }
  return "";
};

export const formatTimestamp = (timestamp: Date): string => {
  return toPersianDigits(
    timestamp.toLocaleTimeString("fa-IR", {
      hour: "2-digit",
      minute: "2-digit",
    }),
  );
};
