"use client";

import {
  BottomActionButton,
  BottomActionButtonProps,
} from "@/components/widgets/BottomActionButton/BottomActionButton";
import DateInput, {
  DateInputProps,
} from "@/components/widgets/DateInput/DateInput";
import { cn } from "@/lib/utils";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { useEffect } from "react";

const formSchema = z.object({
  date: z.string().min(1, {
    message: "Please select a date",
  }),
});

interface QuestionDateAnswersProps
  extends Omit<React.ComponentProps<"div">, "content"> {
  content: DateInputProps;
  bottomActionButtonProps?: BottomActionButtonProps;
}

function QuestionDateAnswers({
  content,
  bottomActionButtonProps,
  ...props
}: QuestionDateAnswersProps) {
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      date: content.value || "",
    },
  });

  useEffect(() => {
    form.setValue("date", content.value || "");
  }, [content.value, form]);

  const handleChange = (value: string | null) => {
    form.setValue("date", value || "");
    form.trigger("date");
    content.onChange?.(value);
  };

  const isFormValid = form.formState.isValid && form.getValues("date");

  return (
    <div {...props}>
      <DateInput
        {...content}
        onChange={handleChange}
        error={form.formState.errors.date?.message}
      />
      {bottomActionButtonProps && (
        <BottomActionButton
          {...bottomActionButtonProps}
          actionButtonProps={{
            ...bottomActionButtonProps.actionButtonProps,
            disabled: !isFormValid,
          }}
          className={cn("max-w-[560px]", bottomActionButtonProps.className)}
        />
      )}
    </div>
  );
}

export { QuestionDateAnswers };
