"use client";

import DatePicker, { DateObject } from "react-multi-date-picker";
import persian from "react-date-object/calendars/persian";
import persian_fa from "react-date-object/locales/persian_fa";
import gregorian from "react-date-object/calendars/gregorian";

/**
 * Jalali (Persian) date picker for the admin. Displays a Persian calendar but keeps
 * the value as a Gregorian ISO string ("YYYY-MM-DD"), so backends/DTOs stay unchanged.
 */
export function PersianDateInput({
  value,
  onChange,
  className,
  placeholder,
}: {
  value: string; // Gregorian ISO "YYYY-MM-DD" or ""
  onChange: (iso: string) => void;
  className?: string;
  placeholder?: string;
}) {
  const dateObj = value
    ? new DateObject({ date: value, format: "YYYY-MM-DD", calendar: gregorian }).convert(
        persian,
        persian_fa
      )
    : "";

  return (
    <DatePicker
      calendar={persian}
      locale={persian_fa}
      calendarPosition="bottom-right"
      value={dateObj}
      onChange={(d) => {
        if (!d || Array.isArray(d)) {
          onChange("");
          return;
        }
        onChange((d as DateObject).convert(gregorian).format("YYYY-MM-DD"));
      }}
      inputClass={className}
      placeholder={placeholder ?? "انتخاب تاریخ"}
      editable={false}
    />
  );
}
