import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useSocketStore } from "../../../store/socket/useSocketStore";
import { useLoadingProgress } from "../../../store/builder/store";
import { getUserData } from "../../../functions/getUserData";
import { getAllProjectsApi } from "../../../services/dashboard/getAllProjectsApi";
import { recentlyViewedApi } from "../../../services/dashboard/recentlyViewedApi";

interface DashboardProjectCollection {
    [key: string]: DashboardProject[];
}

interface ProjectSocketResProps {
    setRecentProjects?: React.Dispatch<React.SetStateAction<DashboardProjectCollection>>;
    setWorkspaceProjects?: React.Dispatch<React.SetStateAction<DashboardProjectCollection>>;
    setIsSearchActive?: React.Dispatch<React.SetStateAction<boolean>>;
}

const ProjectSocketRes = ({ setRecentProjects, setWorkspaceProjects, setIsSearchActive }: ProjectSocketResProps) => {
    const navigate = useNavigate();
    const { projectSocket } = useSocketStore();
    const { userId, organization } = getUserData();
    const { setLoadingProgress } = useLoadingProgress();

    useEffect(() => {
        if (!projectSocket) return;

        const handleAdd = (data: any) => {
            if (data.message === "Project created successfully") {
                setLoadingProgress(1);
                navigate(`/projects/${data.data.projectId}`);
            }
        };

        const handleDelete = (data: any) => {
            // console.log("Delete:", data);
        };

        const handleUpdate = (data: any) => {
            // console.log("Update:", data);
        };

        const handleTrashDelete = (data: any) => {
            // console.log("Trash Delete:", data);
        };

        const handleDuplicate = async (data: any) => {
            if (data?.message === "Project Duplicated successfully") {
                if (setWorkspaceProjects) {
                    const allProjects = await getAllProjectsApi();
                    setWorkspaceProjects(allProjects);
                } else if (setRecentProjects) {
                    const recentProjects = await recentlyViewedApi();
                    setRecentProjects(recentProjects);
                }
                if (setIsSearchActive) setIsSearchActive(false);
            } else {
                console.warn("Duplication failed or unexpected response.");
            }
        };

        projectSocket.on("v1-project:response:add", handleAdd);
        projectSocket.on("v1-project:response:delete", handleDelete);
        projectSocket.on("v1-project:response:update", handleUpdate);
        projectSocket.on("v1-project:response:Duplicate", handleDuplicate);
        projectSocket.on("v1:trash:response:delete", handleTrashDelete);

        return () => {
            projectSocket.off("v1-project:response:add", handleAdd);
            projectSocket.off("v1-project:response:delete", handleDelete);
            projectSocket.off("v1-project:response:update", handleUpdate);
            projectSocket.off("v1-project:response:Duplicate", handleDuplicate);
            projectSocket.off("v1:trash:response:delete", handleTrashDelete);
        };
        // eslint-disable-next-line
    }, [projectSocket, userId, organization]);

    return null;
};

export default ProjectSocketRes;
