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

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,
}) => {
  let navigate = useNavigate();
  const { setProjectName } = useProjectName();
  const { userId, organization, userName } = getUserData();

  const handleKebabIconClick = async () => {
    try {
      if (handleRestoreProject) {
        await handleRestoreProject(projectId);
      } else if (handleDeleteProject) {
        await handleDeleteProject(projectId);
      }
    } catch { }
  };

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

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

  return (
    <div className="dashboard-card-container" onClick={navigateToProject} title={projectName}>
      <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">
          <div className="user-profile">
            {userName ? userName.charAt(0).toUpperCase() : "Anonymous"}
          </div>
          <div
            onClick={(e) => {
              e.stopPropagation();
              handleKebabIconClick();
            }}
          >
            <KebabIcon />
          </div>
        </div>
      </div>
    </div>
  );
};

export default DashboardCard;