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 ProfileContactDirectory from "./ProfileContactDirectory";
import GlobalModel from "../common/GlobalModel";

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 [open_contact, setOpen_contact] = useState(null);
  const [isOpenModalNote, setIsOpenModalNote] = useState(false);

  const handleUpdateNote = async () => {
    try {
      setIsLoading(true);
      const payload = {
        id: noteItem.id,
        note: editorValue,
        contactId,
      };
      const response = await DirectoryRepository.UpdateNote(
        noteItem.id,
        payload
      );

      const cachedContactProfile = getCachedData("Contact Profile");
      if (cachedContactProfile?.contactId === contactId) {
        const updatedCache = {
          ...cachedContactProfile,
          data: {
            ...cachedContactProfile.data,
            notes: cachedContactProfile.data.notes.map((note) =>
              note.id === noteItem.id ? response.data : note
            ),
          },
        };
        cacheData("Contact Profile", updatedCache);
      }

      onNoteUpdate?.(response.data);
      setEditing(false);
      showToast("Note updated successfully", "success");
    } catch (error) {
      showToast("Failed to update note", "error");
    } finally {
      setIsLoading(false);
    }
  };

  const suspendEmployee = async () => {
    try {
      setIsDeleting(true);
      await DirectoryRepository.DeleteNote(noteItem.id, false);
      onNoteDelete?.(noteItem.id);
      setIsDeleteModalOpen(false);
      showToast("Note deleted successfully", "success");
    } catch (error) {
      showToast("Failed to delete note", "error");
    } finally {
      setIsDeleting(false);
    }
  };

  const contactProfile = (contactId) => {
    DirectoryRepository.GetContactProfile(contactId).then((res) => {
      setOpen_contact(res?.data);
      setIsOpenModalNote(true);
    });
  };

  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 (
    <>
      {isOpenModalNote && (
        <GlobalModel
          isOpen={isOpenModalNote}
          closeModal={() => {
            setOpen_contact(null);
            setIsOpenModalNote(false);
          }}
          size="xl"
        >
          {open_contact && (
            <ProfileContactDirectory
              contact={open_contact}
              setOpen_contact={setOpen_contact}
              closeModal={() => setIsOpenModalNote(false)}
            />
          )}
        </GlobalModel>
      )}
      <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-0 align-middle cursor-pointer"
                onClick={() => contactProfile(noteItem.contactId)}
              >
                <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-0 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" />
                )}
              </>
            ) : isRestoring ? (
              <i className="bx bx-loader-alt bx-spin text-primary"></i>
            ) : (
              <i
                className="bx bx-recycle me-2 text-primary cursor-pointer"
                onClick={handleRestore}
                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-3 mt-2">
              <span
                className="text-secondary cursor-pointer"
                onClick={() => setEditing(false)}
              >
                Cancel
              </span>
              <span
                className="text-primary cursor-pointer"
                onClick={handleUpdateNote}
              >
                {isLoading ? "Saving..." : "Submit"}
              </span>
            </div>
          </>
        ) : (
          <div
            className="mx-4 px-10 text-start"
            dangerouslySetInnerHTML={{ __html: noteItem.note }}
          />
        )}
      </div>

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

export default NoteCardDirectoryEditable;
