import React from "react";

type TimestampProps = {
  value: Date | string | number;
  className?: string;
  format?: "date" | "time";
};

function toDate(input: Date | string | number): Date | null {
  if (input instanceof Date) return isNaN(input.getTime()) ? null : input;
  const d = new Date(input);
  return isNaN(d.getTime()) ? null : d;
}

function formatArabicDate(d: Date): string {
  const now = new Date();
  const sameYear = d.getFullYear() === now.getFullYear();
  const day = new Intl.NumberFormat("ar").format(d.getDate());
  const month = new Intl.DateTimeFormat("ar", { month: "long" }).format(d);
  if (sameYear) return `${day} ${month}`;
  const year = new Intl.NumberFormat("ar").format(d.getFullYear());
  return `${day} ${month} ${year}`;
}

function formatTime12(d: Date): string {
  let hours = d.getHours();
  const minutes = d.getMinutes();
  const ampm = hours >= 12 ? "PM" : "AM";
  hours = hours % 12;
  if (hours === 0) hours = 12;
  const hh = hours.toString().padStart(2, "0");
  const mm = minutes.toString().padStart(2, "0");
  return `${hh}:${mm} ${ampm}`;
}

const Timestamp: React.FC<TimestampProps> = ({ value, className, format = "date" }) => {
  const date = toDate(value);

  if (!date) {
    return <span className={className}>--:--</span>;
  }

  const label = format === "time" ? formatTime12(date) : formatArabicDate(date);
  return (
    <time dateTime={date.toISOString()} className={className} suppressHydrationWarning>
      {label}
    </time>
  );
};

export default Timestamp;
