import { useCreateNote } from "@/hooks/firebase/useCreateNote";
import { useDeleteNote } from "@/hooks/firebase/useDeleteNote";
import { useGetNotes } from "@/hooks/firebase/useGetNotes";
import { useUpdateNote } from "@/hooks/firebase/useUpdateNote";
import { createContext, useContext, useState } from "react";

export interface IBrainDump {
  id: number;
  title: string;
  description: string;
}

interface IBrainDumpContext {
  brainDumps: IBrainDump[] | undefined;
  updateBrainDumpItem: (id: number, changes: Partial<IBrainDump>) => void;
  isAddingBrainDump: boolean;
  setIsAddingBrainDump: (value: boolean) => void;
  addBrainDump: (BrainDump: IBrainDump) => void;
  deleteBrainDump: (id: number) => void;
}

const BrainDumpContext = createContext<IBrainDumpContext | undefined>(
  undefined
);

export const BrainDumpProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const { data: brainDumps, refetch } = useGetNotes();
  const { mutate: deleteNote } = useDeleteNote();
  const { mutateAsync: createBrainDump } = useCreateNote();
  const { mutateAsync: updateNoteMutate } = useUpdateNote();

  const [isAddingBrainDump, setIsAddingBrainDump] = useState<boolean>(false);

  const addBrainDump = (BrainDump: IBrainDump) => {
    createBrainDump(BrainDump);
  };

  const updateBrainDumpItem = (id: number, changes: Partial<IBrainDump>) => {
    updateNoteMutate(
      {
        id: id,
        changes: changes,
      },
      {
        onSuccess: (data) => {
          console.log("Note updated successfully", data);
        },
        onError: (error) => {
          console.error("Failed to update note:", error);
        },
      }
    );
  };

  const deleteBrainDump = (id: number) => {
    deleteNote(id.toString(), {
      onSuccess: () => {
        console.log("Feedback deleted successfully");
      },
      onError: (error) => {
        console.error("Failed to delete feedback:", error);
      },
    });
  };

  return (
    <BrainDumpContext.Provider
      value={{
        brainDumps,
        updateBrainDumpItem,
        isAddingBrainDump,
        setIsAddingBrainDump,
        addBrainDump,
        deleteBrainDump,
      }}
    >
      {children}
    </BrainDumpContext.Provider>
  );
};

export const useBrainDumpContext = () => useContext(BrainDumpContext)!;
