"use client";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import postData from "@/api/post-data";
import { useTranslations } from "next-intl";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { FaSpinner } from "react-icons/fa";

export default function AddTicketCommentForm({ id, locale }) {
  const t = useTranslations("user");
  const e = useTranslations("form-errors");

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
  } = useForm({
    resolver: zodResolver(
      z.object({
        contents: z
          .string()
          .min(1, { message: e("required") })
          .trim(),
        ticket_id: z.string().min(1, { message: e("required") }),
      })
    ),
    defaultValues: { ticket_id: id },
  });

  const handleAddComment = async (data) => {
    const { contents, ticket_id } = data;

    const formData = new FormData();
    formData.append("contents", contents);
    formData.append("ticket_id", ticket_id);

    const res = await postData({
      endPoint: "/tickets/reply",
      body: formData,
      locale,
    });

    if (res.error) {
      toastError(res.message || "something went wrong ");
    } else {
      toastSuccess(res.message || t("success"));
      reset(); // Clear input field
    }
  };

  return (
    <form onSubmit={handleSubmit(handleAddComment)} className="mt-6">
      {/* Contents Field */}
      <textarea
        {...register("contents")}
        className={`w-full p-3 border rounded-lg focus:outline-none focus:ring focus:ring-blue-200 ${
          errors.contents ? "border-red-500" : "border-gray-300"
        }`}
        placeholder={t("add-comment-placeholder")}
        rows="4"
      />
      {errors.contents && (
        <p className="text-red-500 text-sm mt-1">{errors.contents.message}</p>
      )}

      {/* Hidden Ticket ID Field */}
      <input type="hidden" {...register("ticket_id")} />

      <button
        type="submit"
        disabled={isSubmitting}
        className="mt-4 py-2 w-32 text-center h-10 bg-main text-white rounded-lg hover:bg-blue-700 disabled:bg-blue-300"
      >
        {isSubmitting ? (
          <FaSpinner className="animate-spin m-auto" />
        ) : (
          t("add-comment")
        )}
      </button>
    </form>
  );
}
