import React from "react";
import {
  DocumentationIcon,
  HelpIcon,
  HomeIcon,
  LogoutIcon,
  NotificationIcon,
  ProjectsIcon,
  TutorialsIcon,
} from "../icons/DashboardIcon";
import { useNavigate } from "react-router-dom";
import darkThemeImage from "../../assets/image/darkThemeProject.png";
import lightThemeImage from "../../assets/image/lightThemeProject.png";
import { SettingsIcon, TrashIcon } from "../icons/ExportCommonIcons";
import { getUserData } from "../../functions/getUserData";
import { useLoadingProgress, useSocketStore } from "../../store/builder/store";
import { createProject } from "../../services/dashboard/createProject";

interface SidePannelProps {
  setActiveTab: React.Dispatch<React.SetStateAction<string>>;
  activeTab: string;
}

const SidePannel: React.FC<SidePannelProps> = ({ setActiveTab, activeTab }) => {
  const { email, userName, userId, organization } = getUserData();
  const navigate = useNavigate();
  const { setLoadingProgress } = useLoadingProgress();
  const { projectSocket } = useSocketStore();
  const savedTheme = localStorage.getItem("theme") ?? "light";

  function generateProjectId() {
    const randomBytes = new Uint8Array(12);
    crypto.getRandomValues(randomBytes);
    return Array.from(randomBytes, (byte) =>
      byte.toString(16).padStart(2, "0")
    ).join("");
  }

  const handleCreateNewProject = async () => {
    const token = localStorage.getItem("token");
    const refreshToken = localStorage.getItem("refreshToken")
    console.log('refreshToken: ', refreshToken);
    try {
      const projectId = generateProjectId();
      useSocketStore.getState().initializeSocket(email, organization, token, refreshToken);

      //API for creating new Project
      // const project = await createProject(
      //   projectId,
      //   userId,
      //   savedTheme === "dark" ? darkThemeImage : lightThemeImage,
      //   organization
      // );

      const addProject = {
        userId,
        thumbnail: savedTheme === "dark" ? darkThemeImage : lightThemeImage,
        organization: organization,
        projectUuid: projectId,
      };

      console.log('projectSocket: ', projectSocket);
      if (projectSocket) {
        const handleResponse = (data: any) => {
          if (data.message === "Project created successfully") {
            setLoadingProgress(1)
            navigate(`/${data.data.projectId}`);
          }
          projectSocket.off("v1-project:response:add", handleResponse); // Clean up
        };
        projectSocket.on("v1-project:response:add", handleResponse);

        projectSocket.emit("v1:project:add", addProject);
      } else {
        console.error("Socket is not connected.");
      }
    } catch (error) {
      console.error("Error creating project:", error);
    }
  };

  return (
    <div className="side-pannel-container">
      <div className="side-pannel-header">
        <div className="user-container">
          <div className="user-profile">
            {userName?.charAt(0).toUpperCase()}
          </div>
          <div className="user-name">
            {userName
              ? userName.charAt(0).toUpperCase() + userName.slice(1).toLowerCase()
              : "Anonymous"}
          </div>
        </div>
        <div className="notifications-container">
          <NotificationIcon />
        </div>
      </div>
      <div
        className="new-project-button"
        style={{ cursor: "pointer" }}
        onClick={handleCreateNewProject}
      >
        + New project
      </div>
      <div className="side-bar-content-container">
        <div className="side-bar-options-container">
          <div
            className={
              activeTab === "Home" ? "option-list active" : "option-list"
            }
            onClick={() => setActiveTab("Home")}
          >
            <HomeIcon />
            Home
          </div>
          <div
            className={
              activeTab === "Projects" ? "option-list active" : "option-list"
            }
            title="Projects"
            onClick={() => setActiveTab("Projects")}
          >
            <ProjectsIcon />
            Projects
          </div>
          <div
            className={
              activeTab === "Trash" ? "option-list active" : "option-list"
            }
            title="Trash"
            onClick={() => setActiveTab("Trash")}
          >
            <TrashIcon />
            Trash
          </div>
          <div
            className={
              activeTab === "Tutorials" ? "option-list active" : "option-list"
            }
            title="coming soon"
            onClick={() => setActiveTab("Tutorials")}
          >
            <TutorialsIcon />
            Tutorials
          </div>
          <div
            className={
              activeTab === "Documentation"
                ? "option-list active"
                : "option-list"
            }
            title="coming soon"
            onClick={() => setActiveTab("Documentation")}
          >
            <DocumentationIcon />
            Documentation
          </div>
        </div>
        <div className="side-bar-options-container" title="coming soon">
          <div className="option-list">
            <SettingsIcon />
            Settings
          </div>
          <div className="option-list" style={{ cursor: "pointer" }} onClick={() => {
            localStorage.clear();
            navigate("/");
          }}>
            <LogoutIcon />
            Log out
          </div>
          <div className="option-list">
            <HelpIcon />
            Help & Feedback
          </div>
        </div>
      </div>
    </div>
  );
};

export default SidePannel;