import React, { useEffect, useState } from "react";
import Avatar from "../common/Avatar";
import { useAppForm } from "../../hooks/appHooks/useAppForm";
import { zodResolver } from "@hookform/resolvers/zod";
import { JobCommentSchema } from "./ServiceProjectSchema";
import {
  useAddCommentJob,
  useJobComments,
} from "../../hooks/useServiceProject";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import Filelist from "../Expenses/Filelist";
import { formatFileSize, getIconByFileType } from "../../utils/appUtils";

const JobComments = ({ data }) => {
  const {
    register,
    handleSubmit,
    watch,
    reset,
    setValue,
    formState: { errors },
  } = useAppForm({
    resolver: zodResolver(JobCommentSchema),
    defaultValues: { comment: "", attachments: [] },
  });

  const {
    data: comments,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useJobComments(data?.id, ITEMS_PER_PAGE, 1);
  const jobComments = comments?.pages?.flatMap((p) => p?.data ?? []) ?? [];

  const { mutate: AddComment, isPending } = useAddCommentJob(() => reset());
  const onSubmit = (formData) => {
    formData.jobTicketId = data?.id;
    AddComment(formData);
  };

  useEffect(() => {
    document.documentElement.style.setProperty("--sticky-top", `-25px`);
  }, []);

  const files = watch("attachments");
  const onFileChange = async (e) => {
    const newFiles = Array.from(e.target.files);
    if (newFiles.length === 0) return;

    const existingFiles = Array.isArray(watch("attachments"))
      ? watch("attachments")
      : [];

    const parsedFiles = await Promise.all(
      newFiles.map(async (file) => {
        const base64Data = await toBase64(file);
        return {
          fileName: file.name,
          base64Data,
          contentType: file.type,
          fileSize: file.size,
          description: "",
          isActive: true,
        };
      })
    );

    const combinedFiles = [
      ...existingFiles,
      ...parsedFiles.filter(
        (newFile) =>
          !existingFiles?.some(
            (f) =>
              f.fileName === newFile.fileName && f.fileSize === newFile.fileSize
          )
      ),
    ];

    setValue("attachments", combinedFiles, {
      shouldDirty: true,
      shouldValidate: true,
    });
  };

  const toBase64 = (file) =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result.split(",")[1]);
      reader.onerror = (error) => reject(error);
    });
  const removeFile = (index) => {
    const newFiles = files.filter((_, i) => i !== index);
    setValue("attachments", newFiles, { shouldValidate: true });
  };
  return (
    <div className="row">
      <div className="sticky-section bg-white p-3">
        <h6 className="m-0 fw-semibold mb-3">Add Comment</h6>

        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="d-flex">
            <Avatar firstName={"A"} lastName={"D"} />

            <div className="flex-grow-1">
              <textarea
                className="form-control"
                rows={3}
                placeholder="Write your comment..."
                {...register("comment")}
              ></textarea>

              {errors?.comment && (
                <small className="danger-text">
                  {errors?.comment?.message}
                </small>
              )}
            </div>
          </div>
          <div className="flex-grow-1 ms-10 mt-2">
            {files?.length > 0 && (
              <Filelist files={files} removeFile={removeFile} />
            )}
          </div>
          <div className="d-flex justify-content-end gap-2 align-items-center text-end mt-3 ms-10 ms-md-0">
            <div
              onClick={() => document.getElementById("attachments").click()}
              className="cursor-pointer"
              style={{ whiteSpace: "nowrap" }}
            >
              <input
                type="file"
                accept=".pdf,.jpg,.jpeg,.png"
                id="attachments"
                multiple
                className="d-none"
                {...register("attachments")}
                onChange={(e) => {
                  onFileChange(e);
                  e.target.value = "";
                }}
              />
              <i className="bx bx-sm bx-paperclip mb-1 me-1"></i>
              Add Attachment
            </div>

            <button
              className="btn btn-primary btn-sm px-1 py-1" // smaller padding + slightly smaller font
              type="submit"
              disabled={!watch("comment")?.trim() || isPending}
            >
              <i className="bx bx-xs bx-send me-1"></i>
              Submit
            </button>
          </div>
        </form>
      </div>
      <div className="card-body p-0">
        <div className="list-group p-0 m-0">
          {jobComments?.map((item) => {
            const user = item?.createdBy;

            return (
              <div
                key={item.id}
                className="list-group-item border-0 border-bottom p-0"
              >
                <div className="d-flex align-items-start mt-2 mx-0 px-0">
                  <Avatar
                    firstName={user?.firstName}
                    lastName={user?.lastName}
                  />
                  <div className="">
                    <div className="d-flex flex-row gap-3">
                      <span className="fw-semibold">
                        {user?.firstName} {user?.lastName}
                      </span>
                      <span className="text-secondary">
                        <em>{formatUTCToLocalTime(item?.createdAt, true)}</em>
                      </span>
                    </div>
                    <div className="text-muted text-secondary">
                      {user?.jobRoleName}
                    </div>
                    <div className="text-wrap">
                      <p className="mb-1 mt-2 text-muted">{item.comment}</p>
                      <div className="d-flex flex-wrap jusify-content-end gap-2 gap-sm-6 ">
                        {item.attachments?.map((file) => (
                          <div className="d-flex align-items-center">
                            <i
                              className={`bx bx-xxl ${getIconByFileType(
                                file?.contentType
                              )} fs-3`}
                            ></i>
                            <div className="d-flex flex-column">
                              <p className="m-0">{file.fileName}</p>
                              <small className="text-secondary">
                                {formatFileSize(file.fileSize)}
                              </small>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

export default JobComments;
