import React, { useEffect, useState } from "react";
import Editor from "../common/TextEditor/Editor";
import Avatar from "../common/Avatar";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { showText } from "pdf-lib";
import { DirectoryRepository } from "../../repositories/DirectoryRepository";
import moment from "moment";
import { cacheData, getCachedData } from "../../slices/apiDataManager";
import NoteCardDirectory from "./NoteCardDirectory";
import showToast from "../../services/toastService";
import { useContactNotes } from "../../hooks/useDirectory";

const schema = z.object({
  note: z.string().min(1, { message: "Note is required" }),
});

const NotesDirectory = ({
  refetchProfile,
  isLoading,
  contactProfile,
  setProfileContact,
}) => {
  const [IsActive, setIsActive] = useState(true);
  const { contactNotes, refetch } = useContactNotes(contactProfile?.id, true);

  const [NotesData, setNotesData] = useState();
  const [IsSubmitting, setIsSubmitting] = useState(false);
  const [addNote, setAddNote] = useState(true);
  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(schema),
    defaultValues: {
      note: "",
    },
  });

  const noteValue = watch("note");

  const handleEditorChange = (value) => {
    setValue("note", value, { shouldValidate: true });
  };

  const onSubmit = async (data) => {
    const newNote = { ...data, contactId: contactProfile?.id };
    try {
      setIsSubmitting(true);
      const response = await DirectoryRepository.CreateNote(newNote);

      const createdNote = response.data;

      setProfileContact((prev) => ({
        ...prev,
        notes: [...(prev.notes || []), createdNote],
      }));

      const cached_contactProfile = getCachedData("Contact Profile");
      if (
        cached_contactProfile &&
        cached_contactProfile.contactId === contactProfile?.id
      ) {
        const updatedProfile = {
          ...cached_contactProfile.data,
          notes: [...(cached_contactProfile.notes || []), createdNote],
        };
        cacheData("Contact Profile", updatedProfile);
      }

      setValue("note", "");
      setIsSubmitting(false);
      showToast("Note added successfully!", "success");
      setAddNote(true);
      setIsActive(true);
    } catch (error) {
      setIsSubmitting(false);
      const msg =
        error.response.data.message ||
        error.message ||
        "Error occured during API calling";
      showToast(msg, "error");
    }
  };

  const onCancel = () => {
    setValue( "note", "" );
    
  };
  const handleSwitch = () => {
    setIsActive(!IsActive);
    if (IsActive) {
      refetch(contactProfile?.id, false);
    }
  };

  return (
    <div className="text-start">
      <div className="d-flex align-items-center justify-content-between">
        <p className="fw-semibold m-0">Notes :</p>
      </div>
      <div className="d-flex align-items-center justify-content-between mb-5">
  <div className="m-0 d-flex align-items-center">
    {contactNotes?.length > 0 ? (
      <label className="switch switch-primary">
        <input
          type="checkbox"
          className="switch-input"
          onChange={() => handleSwitch(!IsActive)}
          value={IsActive}
        />
        <span className="switch-toggle-slider">
          <span className="switch-on"></span>
          <span className="switch-off"></span>
        </span>
        <span className="switch-label">Include Deleted Notes</span>
      </label>
    ) : (
      <div style={{ visibility: "hidden" }}>
        <label className="switch switch-primary">
          <input type="checkbox" className="switch-input" />
          <span className="switch-toggle-slider">
            <span className="switch-on"></span>
            <span className="switch-off"></span>
          </span>
          <span className="switch-label">Include Deleted Notes</span>
        </label>
      </div>
    )}
  </div>

  <div className="d-flex justify-content-end">
    <span
      className={`btn btn-sm ${addNote ? "btn-danger" : "btn-primary"}`}
      onClick={() => setAddNote(!addNote)}
    >
      {addNote ? "Hide Editor" : "Add a Note"}
    </span>
  </div>
</div>


      {addNote && (
        <div className="card m-2 mb-5">
          <button
            type="button"
            class="btn  btn-close btn-secondary position-absolute top-0 end-0 m-2 mt-3 rounded-circle"
            aria-label="Close"
            style={{ backgroundColor: "#eee", color: "white" }}
            onClick={() => setAddNote(!addNote)}
          ></button>
          {/* <div className="d-flex justify-content-end px-2">
            <span
              className={`btn btn-sm   ${
                addNote ? "btn-danger" : "btn-primary"
              }`}
              onClick={() => setAddNote(!addNote)}
            >
              {addNote ? "Hide Editor" : "Add Note"}
            </span>
          </div> */}
          <form onSubmit={handleSubmit(onSubmit)}>
            <Editor
              value={noteValue}
              loading={IsSubmitting}
              onChange={handleEditorChange}
              onCancel={onCancel}
              onSubmit={handleSubmit(onSubmit)}
            />
            {errors.notes && (
              <p className="text-danger small mt-1">{errors.note.message}</p>
            )}
          </form>
        </div>
      )}

      <div className=" justify-content-start  px-1 mt-1">
        {isLoading && (
          <div className="text-center">
            {" "}
            <p>Loading...</p>{" "}
          </div>
        )}
        {!isLoading &&
          [...(IsActive ? contactProfile?.notes || [] : contactNotes || [])]
            .reverse()
            .map((noteItem) => (
              <NoteCardDirectory
                refetchProfile={refetchProfile}
                refetchNotes={refetch}
                refetchContact={refetch}
                noteItem={noteItem}
                contactId={contactProfile?.id}
                setProfileContact={setProfileContact}
                key={noteItem.id}
              />
            ))}

        {IsActive && (
          <div>
            {!isLoading && contactProfile?.notes.length == 0 && !addNote && (
              <div className="text-center mt-5">No Notes Found</div>
            )}
          </div>
        )}
        {!IsActive && (
          <div>
            {!isLoading && contactNotes.length == 0 && !addNote && (
              <div className="text-center  mt-5">No Notes Found</div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default NotesDirectory;
