import { EntryField } from "../../utils/FormTool/Form";
import { Calendar, CalendarProps } from "primereact/calendar";
import { FormEvent, Nullable } from "primereact/ts-helpers";
import React, { SyntheticEvent } from "react";

interface PrimeCalendarProps extends CalendarProps<"range"> {
  id: string;
  model?: EntryField | undefined;
  value?: Nullable<(Date | null)[]>;
  label?: string | null | undefined;
  hint?: string | null | undefined;
  error?: string | null | undefined;
  required?: boolean | undefined;
  selectionMode?: "range";
  onChange?:
    | ((
        event: FormEvent<(Date | null)[], SyntheticEvent<Element, Event>>,
      ) => void)
    | undefined;
}

/** @deprecated */
const PrimeCalendar: React.ForwardRefExoticComponent<
  PrimeCalendarProps & React.RefAttributes<Calendar>
> = React.forwardRef(
  (
    {
      id,
      model,
      value,
      label,
      hint,
      error,
      required = false,
      onChange,
      ...props
    },
    ref,
  ) => {
    const placedValue = model?.value || value || "";
    const placedLabel = model?.label || label || null;
    const placedHint = model?.hint || hint || null;
    const placedError = model?.error || error || null;
    const placedRequired = model?.required || required || false;

    return (
      <div className="flex flex-col gap-2 mb-3">
        {placedLabel && (
          <label
            htmlFor={id}
            title={placedRequired === true ? "Required field" : undefined}
          >
            {placedLabel}
            {placedRequired === true ? (
              <>
                <span className="text-red-500 ml-2">*</span>
              </>
            ) : null}
          </label>
        )}
        <Calendar
          id={id}
          value={placedValue as Date[]}
          {...props}
          readOnlyInput={props.readOnlyInput ?? true}
          hideOnRangeSelection={props.hideOnRangeSelection ?? true}
          ref={ref}
          invalid={placedError !== null}
          required={placedRequired}
          dateFormat={props.dateFormat ?? "yy-mm-dd"}
          showIcon={props.showIcon ?? true}
          onChange={onChange}
          selectionMode="range"
        />
        {placedHint && <small id={`${id}-help`}>{placedHint}</small>}
        {placedError && (
          <small id={`${id}-error`} className="text-red-500">
            {placedError}
          </small>
        )}
      </div>
    );
  },
);

export default PrimeCalendar;
