import {
  DateInput as BaseDateInput,
  DateInputProps,
  DateValue,
} from "@nextui-org/react";
import { ControllerFieldState } from "react-hook-form";
import { CalendarDate } from "@internationalized/date";
import { useState } from "react";

type DateInputCustomProps = {
  fieldProps: any;
  fieldState: ControllerFieldState;
  control?: any;
  name?: string;
};

type InputComponentProps = DateInputCustomProps & DateInputProps;

function DateInput({
  label,
  defaultValue,
  variant = "faded",
  color,
  size,
  placeholderValue,
  minValue,
  maxValue,
  description,
  startContent,
  endContent,
  isRequired = true,
  isReadOnly,
  isDisabled,
  isInvalid,
  inputRef,
  labelPlacement = "outside",
  hourCycle = 24,
  granularity,
  hideTimeZone,
  shouldForceLeadingZeros = true,
  disableAnimation,
  fieldProps,
  fieldState,
  classNames = {
    base: "light text-black ",
    innerWrapper: "text-black",
    label: "block text-sm font-bold text-black tracking-tight font-inter",
    input: `font-noto ${fieldState?.invalid || isInvalid ? "text-black" : ""}`,
    inputWrapper: `${fieldState?.invalid || isInvalid ? "text-black" : ""}`,
    description:
      "font-inter font-regular mt-0.5 text-[12px] leading-tight text-gray-500",
  },
}: InputComponentProps) {
  const parseDate = (dateString: string): CalendarDate => {
    const [day, month, year] = dateString.split("/").map(Number);
    return new CalendarDate(year, month, day);
  };

  const [date, setDate] = useState<DateValue | undefined>(
    fieldProps.value ? parseDate(fieldProps.value) : undefined
  );

  const handleOnChange = (newValue: DateValue) => {
    setDate(newValue);

    const isFullyValid = Boolean(
      newValue?.day && newValue?.month && newValue?.year
    );

    newValue &&
      isFullyValid &&
      fieldProps.onChange(
        `${String(newValue.day).padStart(2, "0")}/${String(
          newValue.month
        ).padStart(2, "0")}/${newValue.year}`
      );
  };

  return (
    <BaseDateInput
      {...fieldProps}
      classNames={classNames}
      color={color}
      defaultValue={defaultValue}
      description={description}
      disableAnimation={disableAnimation}
      endContent={endContent}
      granularity={granularity}
      hideTimeZone={hideTimeZone}
      hourCycle={hourCycle}
      id={fieldProps?.name}
      inputRef={inputRef}
      isDisabled={isDisabled}
      isInvalid={fieldState.invalid ?? isInvalid}
      isReadOnly={isReadOnly}
      isRequired={isRequired}
      label={label}
      labelPlacement={labelPlacement}
      maxValue={maxValue}
      minValue={minValue}
      placeholderValue={new CalendarDate(2024, 12, 1) ?? placeholderValue}
      radius="sm"
      shouldForceLeadingZeros={shouldForceLeadingZeros}
      size={size}
      startContent={startContent}
      value={date}
      variant={variant}
      onChange={handleOnChange}
    />
  );
}

export default DateInput;
