import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import moment from "moment";
import { Toaster, toast } from "react-hot-toast";

import DashboardBuilderService from  "../../../../APIServices/DashboardBuilderService";
import "./dashboardRunnerAll.css";


const DashboardRunnerAll = () => {
  const [addModal, setAddModal] = useState(false);
  const [data, setData] = useState([]);
  const [rows, setRows] = useState([]);
  const [rowSelected, setRowSelected] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [projectName, setProjectName] = useState("");
  const [projectId, setProjectId] = useState(null);
  const [moduleId, setModuleId] = useState(null);
  const [modalDelete, setModalDelete] = useState(false);

  const navigate = useNavigate();
  const { id } = useParams();

  useEffect(() => {
    setProjectId(sessionStorage.getItem("projectId"));
    setModuleId(sessionStorage.getItem("moduleId"));
    fetchDashboard();
    fetchProjectName(sessionStorage.getItem("projectId"));
  }, []);

  const fetchProjectName = (id) => {
    // ModuleSetupService.getProjectModules(id).then((response) => {
    //   setProjectName(response.items[0]?.projectName || "");
    // });
  };

  const fetchDashboard = () => {
    setLoading(true);
    DashboardBuilderService.getAllDash()
      .then((response) => {
        setData(response);
        setRows(response);
      })
      .catch(() => setError("No data available"))
      .finally(() => setLoading(false));
  };

  const handleDelete = (id) => {
    setModalDelete(false);
    // Dashboard3Service.deleteField(id).then(() => {
    //   fetchDashboard();
    //   toast.success("Deleted successfully");
    // });
  };

  const handleExport = () => {
    // ExcelService.exportAsExcelFile(
    //   rows,
    //   "user_",
    //   moment().format("YYYYMMDD_HHmmss")
    // );
  };

  const handleAdd = () => {
    navigate("/admin/dashboard-new-all");
  };

  const handleEdit = (id) => {
    navigate(`../dashrunner/${id}`);
  };

  return (
    <div className="dashboard-runner-all">
      <div className="row">
        <div className="col-8">
          <h3>All Dashboards</h3>
        </div>
        <div className="col-4 text-right">
          <button className="btn btn-primary" onClick={handleAdd}>
            <i className="fa fa-plus" /> Dashboard Builder
          </button>
        </div>
      </div>

      {loading && (
        <div className="alert alert-info">
          <i className="fa fa-spinner fa-spin"></i> Loading...
        </div>
      )}

      {error && <div className="alert alert-danger">{error}</div>}

      {/* {!loading && data && (
        <div className="row">
          {data.map((app, index) => (
            <div key={index} className="col-auto">
              <div className="card" onClick={() => handleEdit(app.id)}>
                <div className="card-header">
                  <i className="fa fa-th" />
                  <b title={app.dashboard_name}>{app.dashboard_name}</b>
                  <p title={app.description}>{app.description}</p>
                </div>
                <div className="card-footer">
                  <button className="btn btn-sm btn-link">
                    Last Updated: {moment(app.updatedAt).format("DD/MM/YYYY")}
                  </button>
                  <span>
                    <i className="fa fa-calendar" /> {moment(app.createdAt).format("HH:mm:ss")}
                  </span>
                </div>
              </div>
            </div>
          ))}
        </div>
      )} */}

      {!loading && data && (
  <div className="row g-4 mt-1">
    {data.map((app, index) => (
      <div key={index} className="col-md-4 col-sm-6">
        <div
          className="card h-100 shadow-md"
          onClick={() => handleEdit(app.id)}
          style={{ cursor: "pointer", borderRadius: "8px" }}
        >
          <div className="card-header  text-black d-flex align-items-center justify-content-between" style={{ fontSize:"1rem"}}>
            <span>
              <i className="fa fa-th me-2"></i><span>     </span>
              <b title={app.dashboard_name} className="text-truncate">
                {app.dashboard_name}
              </b>
            </span>
          </div>
          <div className="card-body">
            <p title={app.description} className="text-muted mb-2 text-truncate">
              {app.description || "No description available"}
            </p>
          </div>
          <div className="card-footer d-flex justify-content-between align-items-center">
            <button className="btn btn-sm btn-link text-secondary fw-bold">
              <i className="fa fa-clock me-1"></i>
              Last Updated: {moment(app.updatedAt).format("DD/MM/YYYY")}
            </button>
            <span className="text-secondary">
              <i className="fa fa-calendar me-1"></i>
              {moment(app.createdAt).format("HH:mm:ss")}
            </span>
          </div>
        </div>
      </div>
    ))}
  </div>
)}


      {/* Add Modal */}
      {addModal && (
        <div className="modal show">
          <div className="modal-body">
            <div className="chart-box" onClick={handleAdd}>
              <img src="/assets/images/fromscratch.png" alt="From Scratch" />
              <h5>Start From Scratch</h5>
            </div>
          </div>
        </div>
      )}

      {/* Delete Modal */}
      {modalDelete && rowSelected && (
        <div className="modal show">
          <div className="modal-body">
            <h1>Delete Confirmation</h1>
            <h2>{rowSelected.id}</h2>
            <div className="modal-footer">
              <button
                className="btn btn-outline-secondary"
                onClick={() => setModalDelete(false)}
              >
                Cancel
              </button>
              <button
                className="btn btn-primary"
                onClick={() => handleDelete(rowSelected.id)}
              >
                Delete
              </button>
            </div>
          </div>
        </div>
      )}

      <Toaster position="top-right" />
    </div>
  );
};

export default DashboardRunnerAll;
