import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/ui/form";
import { InputProps } from "@/shared/ui/input";
import { useTranslations } from "next-intl";
import React from "react";
import { useFormContext } from "react-hook-form";
import { DateIcon } from "../Icons";
import { DatePicker } from "antd";
import dayjs from "dayjs";
export interface FormDateProps extends InputProps {
  label?: React.ReactNode | string;
  showRequired?: boolean;
  name: string;
  className?: any;
  placeholder?: string;
  maxDate?: string;
  minDate?: string;
  disabled?: boolean;
}

const FormDate: React.FC<FormDateProps> = ({
  name,
  label,
  showRequired = true,
  className,
  placeholder,
  maxDate,
  minDate,
  disabled = false,
}) => {
  const form = useFormContext();
  const t = useTranslations("LABELS");
  const {
    formState: { errors },
  } = form;
  return (
    <FormField
      control={form.control}
      name={name}
      render={({ field }) => (
        <FormItem>
          <div className="flex items-center gap-2">
            {label && (
              <FormLabel className=" text-text-primary font-medium text-sm leading-6 px-4 ">
                {typeof label === "string" ? t(label) : label}
                {showRequired && (
                  <span className="text-error mx-1 text-lg translate-y-1 inline-block">
                    *
                  </span>
                )}
              </FormLabel>
            )}
          </div>
          <FormControl>
            <div className="relative app-form">
              <DatePicker
                disabled={disabled}
                className={`px-4 ${className}`}
                suffixIcon={<DateIcon />}
                placeholder={t("select", {
                  name: placeholder ? t(placeholder || "") : "",
                })}
                onChange={(date: any) => {
                  if (date && typeof date === "object" && "$d" in date) {
                    const formattedDate = date.format("YYYY-MM-DD");
                    field.onChange(formattedDate);
                  } else {
                    field.onChange(date);
                  }
                }}
                name={name}
                allowClear
                format={{ format: "YYYY-MM-DD", type: "mask" }}
                {...(minDate ? { minDate: dayjs(minDate) } : {})}
                {...(maxDate ? { maxDate: dayjs(maxDate) } : {})}
                value={field.value ? dayjs(field.value) : null}
                status={errors[name] && errors[name]?.message && "error"}
              />
            </div>
          </FormControl>
          <FormMessage />
        </FormItem>
      )}
    />
  );
};

export default FormDate;
