import React, { useState } from "react";
import Editor from "../common/TextEditor/Editor";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import NoteCardDirectory from "./NoteCardDirectory";
import showToast from "../../services/toastService";
import {
  useActiveInActiveNote,
  useContactNotes1,
  useCreateNote,
  useUpdateNote,
} from "../../hooks/useDirectory";
import { NoetCard } from "./DirectoryPageSkeleton";

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

const NotesDirectory = ({ contactId,contactPerson }) => {
  const [isActive, setIsActive] = useState(true);
  const [showEditor, setShowEditor] = useState(false);

  // Queries & mutations
  const { data, isError, isLoading } = useContactNotes1(contactId, isActive);
  const { mutate: createNote, isPending } = useCreateNote(() =>
    setShowEditor(false)
  );
  const { mutate: updateNote } = useUpdateNote();
  const { mutate: toggleNoteStatus } = useActiveInActiveNote();

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    reset,
    formState: { errors },
  } = useForm({
    resolver: zodResolver(schema),
    defaultValues: { note: "" },
  });

  const noteValue = watch("note");

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

  const onSubmit = (formData) => {
    const notPayload = { ...formData, contactId };
    createNote(notPayload);
  };

  const handleSwitch = () => {
    setIsActive((prev) => !prev);
  };

  const handleCancel =()=>{
    reset()
     setShowEditor(false)
  }

  return (
    <div className="text-start mt-10">
      <div className="d-flex align-items-center justify-content-between">
        <div className="row w-100 align-items-center">
          {data?.length > 0 && (
            <div className="col col-2">
              <p className="fw-semibold m-0 ms-3">Notes :</p>
            </div>
          )}
          <div className="col d-flex justify-content-end gap-2 pe-0">
            <div className="d-flex align-items-center justify-content-between">
              {/* Switch */}
              <label
                className="switch switch-primary"
                style={{ fontSize: "15px" }}
              >
                <input
                  type="checkbox"
                  className="switch-input"
                  onChange={handleSwitch}
                  checked={!isActive} // invert binding
                  style={{ transform: "scale(0.8)" }}
                />
                <span
                  className="switch-toggle-slider"
                  style={{ width: "30px", height: "15px" }}
                >
                  <span className="switch-on"></span>
                  <span className="switch-off"></span>
                </span>
                <span
                  className="switch-label"
                  style={{ fontSize: "14px", marginLeft: "-14px" }}
                >
                  Include Deleted Notes
                </span>
              </label>

              {!showEditor && (
                <div className="d-flex justify-content-end">
                  <button
                    type="button"
                    className="btn btn-sm d-flex align-items-center"
                    onClick={() => setShowEditor(true)}
                    style={{
                      color: "#6c757d",
                      backgroundColor: "transparent",
                      boxShadow: "none",
                      border: "none",
                    }}
                  >
                    <i
                      className="bx bx-plus-circle me-0 text-primary"
                      style={{ fontSize: "1.5rem", color: "#6c757d" }}
                    ></i>
                    Add a Note
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Editor */}
      {showEditor && (
        <div className="card m-2 mb-5 position-relative">
          <span
            type="button"
            className="position-absolute top-0 end-0 mt-3 bg-secondary rounded-circle"
            aria-label="Close"
            onClick={() => setShowEditor(false)}
          >
            <i className="bx bx-x fs-5 p-1 text-white"></i>
          </span>
          <form onSubmit={handleSubmit(onSubmit)}>
            <Editor
              value={noteValue}
              loading={isPending}
              onChange={handleEditorChange}
              onCancel={handleCancel}
              onSubmit={handleSubmit(onSubmit)}
            />
            {errors.note && (
              <p className="text-danger small mt-1">{errors.note.message}</p>
            )}
          </form>
        </div>
      )}

      <div className="justify-content-start px-1 mt-1">
        {isLoading && (
          <NoetCard/>
        )}

        {!isLoading && data?.length > 0
          ? data.map((noteItem) => (
              <NoteCardDirectory
                key={noteItem.id}
                noteItem={noteItem}
                contactId={contactId}
                // updateNote={updateNote}
                // toggleNoteStatus={toggleNoteStatus}
              />
            ))
          : !isLoading &&
            !showEditor && (
              <div className="text-center mt-5">
                {`Be the first to share your insights! ${contactPerson}
                currently has no notes.`}
              </div>
            )}
      </div>
    </div>
  );
};

export default NotesDirectory;
