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 { TimePicker } from "antd";
import dayjs from "dayjs";

export interface FormTimeProps extends InputProps {
  label?: React.ReactNode | string;
  showRequired?: boolean;
  name: string;
  className?: any;
  placeholder?: string;
  labelIcon?: React.ReactNode;
}

const FormTime: React.FC<FormTimeProps> = ({
  name,
  label,
  showRequired = true,
  className,
  placeholder = "Time",
  labelIcon,
}) => {
  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">
              <TimePicker
                className={`px-4 ${className}`}
                suffixIcon={<DateIcon />}
                placeholder={t("select", { name: t(placeholder) })}
                onChange={(time: any) => {
                  if (time) {
                    field.onChange(time.format("HH:mm"));
                  } else {
                    field.onChange("");
                  }
                }}
                name={name}
                allowClear
                format="HH:mm"
                value={field.value ? dayjs(field.value, "HH:mm") : null}
                status={errors[name] && errors[name]?.message && "error"}
              />
            </div>
          </FormControl>
          <FormMessage />
        </FormItem>
      )}
    />
  );
};

export default FormTime;
