import { zodResolver } from "@hookform/resolvers/zod";
import React from "react";
import { useForm } from "react-hook-form";
import { CommentSchema } from "./collectionSchema";
import { useAddComment } from "../../hooks/useCollections";
import Avatar from "../common/Avatar";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import moment from "moment";

const Comment = ({ invoice }) => {
  const {
    register,
    reset,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(CommentSchema),
    defaultValues: { comment: "" },
  });

  const { mutate: AddComment, isPending } = useAddComment(() => {
    reset();
  });

  const onSubmit = (formData) => {
    const payload = { ...formData, invoiceId: invoice?.id };
    AddComment(payload);
  };
  return (
    <div className="row pt-1 px-2">
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className="col-12">
          <textarea
            className="form-control "
            rows={3}
            {...register("comment")}
          />
          {errors.comment && (
            <small className="danger-text">{errors.comment.message}</small>
          )}
        </div>
        <div className="d-flex justify-content-end p-2">
          <button
            className="btn btn-sm btn-primary"
            type="submit"
            disabled={isPending}
          >
            {isPending ? "Please wait..." : "Submit"}
          </button>
        </div>
      </form>
      {invoice?.comments?.length > 0 ? (
        invoice.comments.map((comment, index) => (
          <div
            className="border-start border-primary ps-1 py-2 mb-3"
            key={comment.id || index}
          >
            <div className="d-flex justify-content-between align-items-center mb-1">
              <div className="d-flex align-items-center">
                <Avatar
                  size="xs"
                  firstName={comment?.createdBy?.firstName}
                  lastName={comment?.createdBy?.lastName}
                />
                <span className="ms-1 fw-semibold">
                  {comment?.createdBy?.firstName} {comment?.createdBy?.lastName}
                </span>
              </div>

              <small className="text-secondary">
                {moment.utc(comment?.createdAt).local().fromNow()}
              </small>
            </div>

           <div className="ms-9"> <p className="mb-1">{comment?.comment}</p></div>
          </div>
        ))
      ) : (
        <p className="text-muted">No comments yet.</p>
      )}
    </div>
  );
};

export default Comment;
