import { goGet } from "../../utils/goFetch";
import React, { useEffect, useState, useRef } from "react";
import { Card } from "primereact/card";
import { Skeleton } from "primereact/skeleton";
import OSActionButton, {
  OSActionButtonType,
} from "../../components/OSActionButton/OSActionButton";
import { Toast } from "primereact/toast";
import { Message } from "primereact/message";
import { OSNoteModel, OSNoteProps } from "../../types/OSActivity/os-note";
import OSForm, { OSFormRef } from "../../components/OSForm/OSForm";
import { OSInputType } from "../../components/OSForm/Enums";
import { OSLabel } from "../label";
import { timeAgo } from "../../helpers/messageHelper";

/** @deprecated Moved to local copy in Central, not general enough for library */
const OSNote: React.FC<OSNoteProps> = ({ ...props }) => {
  const [notes, setNotes] = useState<OSNoteModel[]>();
  const [networkProcessing, setNetworkProcessing] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(true);

  const toast = useRef<Toast | null>(null);
  const osFormRef = useRef<OSFormRef>(null);

  useEffect(() => {
    fetchNotes(setNotes);
  }, []);

  const fetchNotes = async (setNotes: (data: OSNoteModel[]) => void) => {
    setIsLoading(true);
    goGet(`/frontend/activity/user-notes?user=${props.user}&site=${props.site}`)
      .then((response) => {
        const responseData = response as { notes: OSNoteModel[] };
        // console.table(response);
        setNotes(responseData.notes);
      })
      .catch((e) => {
        console.error("Failed to fetch notes", e);
        showErrorToast("Error fetching notes");
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  const showSuccessToast = (message: string) => {
    if (toast.current) {
      toast.current.show({
        severity: "success",
        summary: "Success",
        detail: message,
      });
    }
  };

  const showErrorToast = (message: string) => {
    if (toast.current) {
      toast.current.show({
        severity: "error",
        summary: "Error",
        detail: message,
      });
    }
  };

  const renderNotes = () => {
    if (notes === undefined || notes.length === 0) {
      return <Message text="No notes found" severity="secondary" />;
    }
    return notes?.map((note) => {
      return (
        <div key={note.guid} className="flex w-full">
          <Card
            id="note-card"
            className="w-full"
            >
              <OSLabel label={`Note added by ${note.manager} ${timeAgo(note.timestamp)}`}
               tag={"h3"} />
            <p>{note.content}</p>
          </Card>
        </div>
      );
    });
  };

  const afterSubmit = () => {
    showSuccessToast("Note added successfully!");
    if (osFormRef.current) {
      osFormRef.current.resetForm();
    }
    fetchNotes(setNotes);
  };

  return (
    <div className="flex flex-col items-center w-full">
      <Toast ref={toast} />
      {isLoading ? (
        <Skeleton height="10rem" className="p-4! m-4! w-full" />
      ) : (
        renderNotes()
      )}
      <div className="flex flex-col w-full">
        <OSForm
          ref={osFormRef}
          useCustomButtons
          customEndpoint="/frontend/activity/create-user-note"
          model="Note"
          fields={[
            {
              field: "content",
              label: "Note",
              required: true,
              type: OSInputType.TextArea,
              placeholder: "Enter note here",
              stringMax: 255,
              className: "h-30",
              hideLabel: true,
            },
            {
              field: "user",
              value: props.user,
              type: OSInputType.Hidden,
            },
            {
              field: "site",
              value: props.site,
              type: OSInputType.Hidden,
            },
          ]}
          onNetworkProcessingChange={(networkProcessing) => {
            setNetworkProcessing(networkProcessing);
          }}
          afterSubmit={afterSubmit}
        />
        <div className="flex justify-end mr-4">
          <OSActionButton
            props={{
              label: "Add Note",
              primaryIconEnabled: true,
              primaryIcon: "circle-plus",
              type: OSActionButtonType.Primary,
              onClick: () => {
                if (osFormRef.current) {
                  osFormRef.current.handleSubmit();
                }
              },
            }}
          >
            {networkProcessing && (
              <OSLabel label="Creating..."
                  colour="white"
                  leadingIcon={{identifier: "spinner", animation: "spin-pulse"}}
              />
            )}
          </OSActionButton>
        </div>
      </div>
    </div>
  );
};

export default OSNote;
