import React, { useState, useRef } from "react";
import img from "../../assets/image/image.png";
import { useNavigate } from "react-router-dom";
import { getUserData } from "./functions/getUserData";
import { useProjectName } from "../../store/builder/store";
import { viewProject } from "../../services/dashboard/viewProject";
import OuterClick from "../../utils/outerClick";
import { KebabIcon } from "../icons/ExportCommonIcons";

interface DashBoardCardProps {
  projectName: string;
  thumbnail: any;
  projectId: string;
  handleDeleteProject?: (projectId: string) => Promise<void>;
  handleRestoreProject?: (projectId: string) => Promise<void>;
}

const DashboardCard: React.FC<DashBoardCardProps> = ({
  projectName,
  handleDeleteProject,
  thumbnail,
  projectId,
  handleRestoreProject,
}) => {
  const navigate = useNavigate();
  const { setProjectName } = useProjectName();
  const { userId, organization, userName } = getUserData();
  const [isKebabOpen, setIsKebabOpen] = useState(false);

  const kebabRef = useRef<HTMLDivElement>(null);

  const navigateToProject = async () => {
    try {
      const viewedProject = await viewProject(organization, projectId, userId);
      console.log("Viewed project:", viewedProject);
    } catch (error) {
      console.error("Error opening project:", error);
    }

    setProjectName(projectName);
    navigate(`/${projectId}`);
  };

  const handleOptionClick = async (option: string) => {
    console.log('option: ', option);
    switch (option) {
      case "delete":
        if (handleDeleteProject) {
          await handleDeleteProject(projectId);
        }
        break;
      case "restore":
        if (handleRestoreProject) {
          await handleRestoreProject(projectId);
        }
        break;
      case "openInNewTab":
        window.open(`/${projectId}`, "_blank");
        break;
      case "rename":
        // Add rename logic here
        break;
      case "duplicate":
        // Add duplication logic here
        break;
      default:
        break;
    }
    setIsKebabOpen(false);
  };

  OuterClick({
    contextClassName: ["kebab-wrapper", "kebab-options-wrapper"],
    setMenuVisible: () => setIsKebabOpen(false),
  });
  return (
    <button
      className="dashboard-card-container"
      onClick={navigateToProject}
      title={projectName}
    >
      <div className="dashboard-card-wrapper">
        <div className="preview-container">
          {thumbnail ? (
            <img src={thumbnail} alt="" />
          ) : (
            <img src={img} alt="" />
          )}
        </div>
        <div className="project-details-container">
          <div className="project-details">
            <div className="project-name">{projectName}</div>
            <div className="project-data">24-12-2025</div>
          </div>
          <div className="users-list-container" ref={kebabRef}>
            <div className="user-profile">
              {userName ? userName.charAt(0).toUpperCase() : "A"}
            </div>

            <button
              className="kebab-wrapper"
              onClick={(e) => {
                e.stopPropagation(); // Prevents click from bubbling up
                console.log("Kebab menu clicked");
                setIsKebabOpen((prev) => !prev);
              }}
            >
              <KebabIcon />
            </button>
          </div>
        </div>
      </div>

      {isKebabOpen && (
        <div className="kebab-options-wrapper">
          {["rename", "restore", "delete", "duplicate", "open in new tab"].map((option) => (
            <button
              key={option}
              className="option"
              onClick={(e) => {
                console.log(option);
                e.stopPropagation();
                handleOptionClick(option);
              }}
            >
              {option}
            </button>
          ))}
        </div>
      )}
    </button>
  );
};

export default DashboardCard;
