import { useCreateFeedback } from "@/hooks/firebase/useCreateFeedback";
import { useDeleteFeedback } from "@/hooks/firebase/useDeleteFeedback";
import { useGetFeedbacks } from "@/hooks/firebase/useGetFeedbacks";
import { useUpdateFeedback } from "@/hooks/firebase/useUpdateFeedback";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { createContext, useContext, useState } from "react";

export interface IFeedback {
  id: number;
  title: string;
  text: string;
}

interface IFeedbackContext {
  feedbacks: IFeedback[] | undefined;
  isAddingFeedback: boolean;
  setIsAddingFeedback: (value: boolean) => void;
  addFeedback: (BrainDump: IFeedback) => void;
  updateFeedback: (id: number, changes: Partial<IFeedback>) => void;
  deleteFeedback: (id: number) => void;
}

const FeedbackContext = createContext<IFeedbackContext | undefined>(undefined);

export const FeedbackProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const {
    mutateAsync: createFeedback,
    isLoading: isAdding,
    isError,
  } = useCreateFeedback();
  const { data: feedbacks } = useGetFeedbacks();
  const { mutate: deleteFeedbackMutate } = useDeleteFeedback();
  const { mutate: updateFeedbackMutate } = useUpdateFeedback();

  const [isAddingFeedback, setIsAddingFeedback] = useState<boolean>(false);

  const addFeedback = (Feedback: IFeedback) => {
    createFeedback({ title: Feedback.title, text: Feedback.text });
  };

  const updateFeedback = (id: number, changes: Partial<IFeedback>) => {
    updateFeedbackMutate(
      {
        id: id,
        changes: changes,
      },
      {
        onSuccess: (data) => {
          console.log("Feedback updated successfully", data);
        },
        onError: (error) => {
          console.error("Failed to update feedback:", error);
        },
      }
    );
  };

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

  return (
    <FeedbackContext.Provider
      value={{
        feedbacks,
        isAddingFeedback,
        setIsAddingFeedback,
        addFeedback,
        updateFeedback,
        deleteFeedback,
      }}
    >
      {children}
    </FeedbackContext.Provider>
  );
};

export const useFeedbackContext = () => useContext(FeedbackContext)!;
