"use client"
import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { Icon } from "@iconify/react";
import { Controller } from "react-hook-form";

type CustomDataInputProps = {
  label: string;
  format?: string;
  formInputs: any;
};

const CustomDataInput: React.FC<CustomDataInputProps> = ({
  label,
  format,
  formInputs
}) => {
  // Custom input component
  const CustomInput = ({
    value,
    onClick,
  }: {
    value?: string;
    onClick?: () => void;
  }) => (
    <div className="relative">
      <input
        type="text"
        value={formInputs.watch("handover_date")}
        placeholder="Handover date"
        onClick={onClick}
        readOnly
        className="bg-[#FAF9F6]  text-gray-900 text-sm rounded-[4px] focus:ring-none focus:border-none block w-full p-[15px] dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500"
      />
      <Icon
        icon="ic:outline-date-range"
        className="absolute top-[50%] translate-y-[-50%] ltr:right-3 rtl:left-3 text-secondary size-7"
        onClick={onClick}
      />
    </div>
  );

  // Get the current year
  const currentYear = new Date().getFullYear();

  return (
    <div className="w-full">
      <label
        htmlFor="name"
        className="block mb-2 text-sm font-medium text-gray-900 dark:text-white"
      >
        {label}
      </label>
      <Controller
        control={formInputs.control}
        name="handover_date"
        render={({ field }) => {
          return (
            <DatePicker
              selected={field.value}
              showYearPicker={format === "yyyy"}
              dateFormat={format === "yyyy" ? `yyyy` : `dd/MM/yyyy`}
              customInput={<CustomInput />}
              onChange={(value: any) => {
                field.onChange(new Date(value).getFullYear());
              }}
              wrapperClassName="w-full"
              minDate={new Date(currentYear, 0, 1)} // Set the minDate to the first day of the current year
            />
          );
        }}
      />
    </div>
  );
};

export default CustomDataInput;
