import { format } from "date-fns-jalali";

export const formatTime = (time: any) => {
  const date = new Date(time);
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");

  return format(new Date(time), "yyyy/MM/dd  ") + `(${hours}:${minutes})`;
};

export const formatJustDate = (time: any) => {
  if (time) {
    return format(new Date(time), "yyyy/MM/dd");
  } else {
    return null;
  }
};

export const formatJustTime = (time: any) => {
  return format(new Date(time), "HH:MM");
};

export function formatStampDate(timestamp: number) {
  const date = new Date(timestamp);
  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}`;
}

export function formatStampDateTime(timestamp: number) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  return `${year}/${month}/${day} ${hours}:${minutes}`;
}

export const formatAgeCalcuation = (dateString: string) => {
  const birthDate = new Date(dateString);
  const currentDate = new Date();

  let years = currentDate.getFullYear() - birthDate.getFullYear();
  let months = currentDate.getMonth() - birthDate.getMonth();
  let days = currentDate.getDate() - birthDate.getDate();

  if (days < 0) {
    months--;
    const lastMonth = new Date(
      currentDate.getFullYear(),
      currentDate.getMonth(),
      0
    );
    days += lastMonth.getDate();
  }

  if (months < 0) {
    years--;
    months += 12;
  }

  const parts: string[] = [];

  if (years > 0) {
    parts.push(`${years} سال`);
  }

  if (months > 0) {
    parts.push(`${months} ماه`);
  }

  if (days > 0) {
    parts.push(`${days} روز`);
  }

  if (parts.length === 0) {
    return "0 روز";
  }

  return parts.join(" و ");
};

export function convertToIranianTime(dateString: Date | string): string {
  const gregorianDate = new Date(dateString);
  const jalaliDate = format(gregorianDate, "yyyy/MM/dd");
  return jalaliDate;
}

