import React, { useState } from "react";
import ReactQuill from "react-quill";
import moment from "moment";
import Avatar from "../common/Avatar";
import { DirectoryRepository } from "../../repositories/DirectoryRepository";
import showToast from "../../services/toastService";
import { cacheData, getCachedData } from "../../slices/apiDataManager";
import ConfirmModal from "../common/ConfirmModal"; // Make sure path is correct
import "../common/TextEditor/Editor.css";
import GlobalModel from "../common/GlobalModel";
import { useActiveInActiveNote, useUpdateNote } from "../../hooks/useDirectory";
import { useDirectoryContext } from "../../pages/Directory/DirectoryPage";

const NoteCardDirectoryEditable = ({
  noteItem,
  contactId,
  onNoteUpdate,
  onNoteDelete,
}) => {
  const [editing, setEditing] = useState(false);
  const [editorValue, setEditorValue] = useState(noteItem.note);
  const [isLoading, setIsLoading] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isRestoring, setIsRestoring] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);

  const { mutate: UpdateNote, isPending: isUpatingNote } = useUpdateNote(() =>
    setEditing(false)
  );
  const { mutate: ActiveInactive, isPending: isUpdatingStatus } =
    useActiveInActiveNote(() => setIsDeleteModalOpen(false));
  const { setContactOpen } = useDirectoryContext();


  const handleUpdateNote = async () => {
    const payload = {
      id: noteItem.id,
      note: editorValue,
      contactId,
    };

    UpdateNote({ noteId: noteItem.id, notePayload: payload });
  };

  const ActiveInActive = (noteItem) => {
    ActiveInactive({ noteId: noteItem.id, noteStatus: !noteItem.isActive });
  };


  const handleRestore = async () => {
    try {
      setIsRestoring(true);
      await DirectoryRepository.DeleteNote(noteItem.id, true);
      onNoteDelete?.(noteItem.id);
      showToast("Note restored successfully", "success");
    } catch (error) {
      showToast("Failed to restore note", "error");
    } finally {
      setIsRestoring(false);
    }
  };

  return (
    <>

      <div
        className="card shadow-sm border-1 mb-3 p-4 rounded"
        style={{
          width: "100%",
          background: noteItem.isActive ? "#fff" : "#f8f6f6",
        }}
        key={noteItem.id}
      >
        {/* Header */}
        <div className="d-flex justify-content-between align-items-center mb-1">
          <div className="d-flex align-items-center">
            <Avatar
              size="xxs"
              firstName={noteItem?.createdBy?.firstName}
              lastName={noteItem?.createdBy?.lastName}
              className="m-0"
            />
            <div>
              <div
                className="d-flex ms-3 align-middle cursor-pointer"
                onClick={() =>
                  setContactOpen({ contact: { id: noteItem.contactId }, Open: true })
                }
              >
                <span>
                  <span className="fw-bold "> {noteItem?.contactName} </span>{" "}
                  <span className="text-muted font-weight-normal">
                    ({noteItem?.organizationName})
                  </span>
                </span>
              </div>

              <div className="d-flex ms-0 align-middle"></div>
              <div className="d-flex ms-3 mt-2">
                <span className="text-muted">
                  by{" "}
                  <span className="fw-bold ">
                    {" "}
                    {noteItem?.createdBy?.firstName}{" "}
                    {noteItem?.createdBy?.lastName}{" "}
                  </span>
                  &nbsp;{" "}
                  <span className="text-muted">
                    on{" "}
                    {moment
                      .utc(noteItem?.createdAt)
                      .add(5, "hours")
                      .add(30, "minutes")
                      .format("DD MMMM, YYYY [at] hh:mm A")}
                  </span>
                </span>
              </div>
            </div>
          </div>

          {/* Action Icons */}
          <div>
            {noteItem.isActive ? (
              <>
                <i
                  className="bx bxs-edit bx-sm me-2 text-primary cursor-pointer"
                  onClick={() => setEditing(true)}
                  title="Edit"
                ></i>
                {!isDeleting ? (
                  <i
                    className="bx bx-trash bx-sm me-2 text-danger cursor-pointer"
                    onClick={() => setIsDeleteModalOpen(true)}
                    title="Delete"
                  ></i>
                ) : (
                  <div className="spinner-border spinner-border-sm text-danger" />
                )}
              </>
            ) : isUpdatingStatus ? (
              <i className="bx bx-loader-alt bx-spin text-primary"></i>
            ) : (
              <i
                className="bx bx-recycle me-2 text-primary cursor-pointer"
                onClick={() => ActiveInActive(noteItem)}
                title="Restore"
              ></i>
            )}
          </div>
        </div>

        <hr className="mt-0 mb-2" />

        {/* Editor or Content */}
        {editing ? (
          <>
            <ReactQuill
              value={editorValue}
              onChange={setEditorValue}
              theme="snow"
              className="compact-editor"
            />
            <div className="d-flex justify-content-end gap-0 mt-2">
              <button
                type="button"
                className="btn btn-sm btn-label-secondary me-2 px-2 py-1"
                onClick={() => setEditing(false)}
              >
                Cancel
              </button>

              <button
                type="button"
                className="btn btn-sm btn-primary px-2 py-1"
                onClick={handleUpdateNote}
                disabled={isUpatingNote}
              >
                {isUpatingNote ? "Saving..." : "Submit"}
              </button>
            </div>

          </>
        ) : (
          <div
            className="mx-4 px-11 text-start"
            dangerouslySetInnerHTML={{ __html: noteItem.note }}
          />
        )}
      </div>

      <ConfirmModal
        type="delete"
        header="Delete Note"
        message="Are you sure you want to delete this note?"
        onSubmit={ActiveInActive}
        onClose={() => setIsDeleteModalOpen(false)}
        loading={isUpdatingStatus}
        paramData={noteItem}
        isOpen={isDeleteModalOpen}
      />
    </>
  );
};

export default NoteCardDirectoryEditable;
