// import React, { useState } from "react";
// import {
//   Button,
//   Modal,
//   Table,
//   Form,
//   Spinner,
//   Tooltip,
//   OverlayTrigger
// } from "react-bootstrap";

// const DashboardNewAll = () => {
//   const [addModal, setAddModal] = useState(false);
//   const [deleteModal, setDeleteModal] = useState(false);
//   const [selectedRow, setSelectedRow] = useState(null);
//   const[data,setData] = useState([]);
//   const[loading,setLoading] = useState();
//   const [error,setError] = useState();
//   const[translate,setTranslate] = useState();

//   const handleAddClick = () => setAddModal(true);
//   const handleDeleteClick = (row) => {
//     setSelectedRow(row);
//     setDeleteModal(true);
//   };

//   const handleDeleteConfirm = () => {
//     console.log("Deleting row: ", selectedRow.id);
//     setDeleteModal(false);
//   };

//   return (
//     <div className="dg-wrapper">
//       <div className="d-flex justify-content-between align-items-center mb-3">
//         <h3>{translate("Dashboard_builder")}</h3>
//         <div>
//           <Button variant="primary" onClick={() => console.log("Go to Runner")}>
//             <i className="bi bi-grid"></i> {translate("Dashboard_runner")}
//           </Button>
//           <Button
//             variant="outline-secondary"
//             className="mx-2"
//             onClick={() => console.log("Export")}
//           >
//             <i className="bi bi-file-earmark-excel"></i> {translate("EXPORT_XLSX")}
//           </Button>
//           <Button variant="primary" onClick={handleAddClick}>
//             <i className="bi bi-plus"></i> {translate("ADD")}
//           </Button>
//         </div>
//       </div>

//       <Table striped bordered hover>
//         <thead>
//           <tr>
//             <th>{translate("Go_to")}</th>
//             <th>{translate("Dashboard_Name")}</th>
//             <th>{translate("Description")}</th>
//             <th>{translate("Security_Profile")}</th>
//             <th>{translate("Add_to_home")}</th>
//             <th>{translate("Action")}</th>
//           </tr>
//         </thead>
//         <tbody>
//           {loading ? (
//             <tr>
//               <td colSpan="6" className="text-center">
//                 <Spinner animation="border" /> {translate("Loading")} ......
//               </td>
//             </tr>
//           ) : error ? (
//             <tr>
//               <td colSpan="6" className="text-center text-danger">
//                 {error}
//               </td>
//             </tr>
//           ) : (
//             data?.slice()?.reverse()?.map((user) => (
//               <tr key={user.id}>
//                 <td>
//                   <span
//                     className="badge bg-info text-dark"
//                     style={{ cursor: "pointer" }}
//                     onClick={() => console.log("Go to Edit", user.id)}
//                   >
//                     {translate("SET_UP")}
//                   </span>
//                 </td>
//                 <td>{user.dashboard_name}</td>
//                 <td>{user.description}</td>
//                 <td>{user.security_profile}</td>
//                 <td>{user.add_to_home}</td>
//                 <td>
//                   <OverlayTrigger
//                     placement="top"
//                     overlay={<Tooltip>{translate("Delete")}</Tooltip>}
//                   >
//                     <i
//                       className="bi bi-trash text-danger"
//                       style={{ cursor: "pointer" }}
//                       onClick={() => handleDeleteClick(user)}
//                     ></i>
//                   </OverlayTrigger>
//                   <OverlayTrigger
//                     placement="top"
//                     overlay={<Tooltip>{translate("Edit")}</Tooltip>}
//                   >
//                     <i
//                       className="bi bi-pencil text-primary mx-2"
//                       style={{ cursor: "pointer" }}
//                       onClick={() => console.log("Edit", user.id)}
//                     ></i>
//                   </OverlayTrigger>
//                 </td>
//               </tr>
//             ))
//           )}
//         </tbody>
//       </Table>

//       {/* Add Modal */}
//       <Modal show={addModal} onHide={() => setAddModal(false)} size="lg" centered>
//         <Modal.Body>
//           <div className="d-flex justify-content-around">
//             <div
//               className="chart-box text-center"
//               onClick={() => console.log("Start from Scratch")}
//             >
//               <img
//                 src="/assets/images/fromscratch.png"
//                 alt="Start from Scratch"
//                 height="90"
//                 width="90"
//               />
//               <h5>{translate("Start_from_scratch")}</h5>
//             </div>
//             <div
//               className="chart-box text-center"
//               onClick={() => console.log("Import from Template")}
//             >
//               <img
//                 src="/assets/images/copytemplate.png"
//                 alt="Import from Template"
//                 height="90"
//                 width="90"
//               />
//               <h5>{translate("Import_from_template")}</h5>
//             </div>
//             <div
//               className="chart-box text-center"
//               onClick={() => console.log("Import from Public Project")}
//             >
//               <img
//                 src="/assets/images/database.png"
//                 alt="Import from Public Project"
//                 height="90"
//                 width="90"
//               />
//               <h5>{translate("Import_from_public_project")}</h5>
//             </div>
//           </div>
//         </Modal.Body>
//       </Modal>

//       {/* Delete Modal */}
//       <Modal show={deleteModal} onHide={() => setDeleteModal(false)} centered>
//         <Modal.Body>
//           <h1 className="text-danger text-center">
//             {translate("Are_you_sure_want_to_delete")}
//           </h1>
//           <h2 className="text-center">{selectedRow?.id}</h2>
//           <div className="d-flex justify-content-around mt-4">
//             <Button variant="outline-secondary" onClick={() => setDeleteModal(false)}>
//               {translate("Cancel")}
//             </Button>
//             <Button variant="primary" onClick={handleDeleteConfirm}>
//               {translate("Delete")}
//             </Button>
//           </div>
//         </Modal.Body>
//       </Modal>
//     </div>
//   );
// };

// export default DashboardNewAll;


import React, { useState, useEffect } from "react";
import {
  Button,
  Modal,
  Table,
  Spinner,
  Tooltip,
  OverlayTrigger,
} from "react-bootstrap";
import { useTranslation } from "react-i18next";
import { useNavigate, useLocation } from "react-router-dom";
import * as XLSX from "xlsx";
import { toast } from "react-toastify";
import ConfirmModal from "../../../common/ConfirmModal"
import DashboardBuilderService from "../../../../APIServices/DashboardBuilderService";

const DashboardNewAll = () => {
  const { t: translate } = useTranslation(); // Use `translate` as the translation function
  const [addModal, setAddModal] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [deleteModal, setDeleteModal] = useState(false);
  const [selectedRow, setSelectedRow] = useState(null);
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [refresh, setRefresh] = useState(false);
  const [tableData, setTableData] = useState([]);

  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    const storedDashboards = JSON.parse(localStorage.getItem("dashboards")) || [];
    setData(storedDashboards);
    console.log("Stored Dashboards:", storedDashboards);

    if (location.state?.updatedDashboard) {
      const updatedDashboard = location.state.updatedDashboard;
      setData(prevData => prevData.map(dashboard =>
        dashboard.id === updatedDashboard.id ? updatedDashboard : dashboard
      ));
      location.state.updatedDashboard = null;
    }
    setLoading(false);
  }, [refresh, location.state?.updatedDashboard]);

  const handleAddClick = () => {
    navigate("/admin/dashboard-new-add");
  }
  const handleDeleteClick = (row) => {
    setSelectedRow(row);
    setShowConfirmModal(true);
  };

  const handleDeleteConfirm = async () => {
    try {
      // Call the delete API
      await DashboardBuilderService.deleteField(selectedRow.id);

      // Update the UI after successful deletion
      setData((prevData) => prevData.filter((dashboard) => dashboard.id !== selectedRow.id));
      toast.success("Dashboard deleted successfully!");
    } catch (error) {
      console.error("Error deleting dashboard field:", error);
      toast.error("Failed to delete dashboard. Please try again.");
    }
  };
  const handleRunner = () => {
    console.log("Go to Runner");
    navigate("/admin/dashboard-runner-all");

  }

  useEffect(() => {
    fetchAllDashboards();
  }, []);

  const fetchAllDashboards = async () => {
    try {
      setLoading(true);
      const dashboards = await DashboardBuilderService.getAllDash(); // Call service
      console.log('Fetched Dashboards:', dashboards); // Verify data
      setData(dashboards); // Update state with the array
      toast.success("Dashboards fetched successfully.");
    } catch (error) {
      console.error('Error fetching dashboards:', error);
      toast.error('Failed to fetch dashboards.');
    } finally {
      setLoading(false);
    }
  };

  const handleEditClick = (dashboard) => {
    navigate(`/admin/dashboard-new-edit/${dashboard.id}`, { state: { dashboard } }); // Pass the ID in the URL
  }

  const handleExport = () => {
    console.log("Export to Excel");
    // Create a new workbook and a worksheet
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.json_to_sheet(data);

    // Append the worksheet to the workbook
    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

    // Write the workbook and download the file
    XLSX.writeFile(workbook, "exported_data.xlsx");
  }

  const handleSetUp = (id) => {
    console.log("dashboard id : ", id)
    navigate(`/admin/edit-new-dash/${id}`,{dashboardId:id});
  }
  const refreshData = () => {
    setRefresh((prev) => !prev); // Toggle the refresh state to trigger re-fetch
  }

  return (
    <div className="dg-wrapper">
      <div className="d-flex justify-content-between align-items-center mb-3">
        <h3>{translate("Dashboard Builder")}</h3>
        <div>
          <Button variant="primary" onClick={() => handleRunner()}>
            <i className="bi bi-grid"></i> {translate("Dashboard_runner")}
          </Button>
          <Button
            variant="outline-secondary"
            className="mx-2"
            onClick={() => handleExport()}
          >
            <i className="bi bi-file-earmark-excel"></i> {translate("EXPORT_XLSX")}
          </Button>
          <Button variant="primary" onClick={handleAddClick}>
            <i className="bi bi-plus"></i> {translate("ADD")}
          </Button>
        </div>
      </div>
      <Table striped bordered hover>
        <thead>
          <tr>
            <th>Go To</th>
            <th>Dashboard Name</th>
            <th>Description</th>
            <th>Security Profile</th>
            <th>Add to Home</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
          {loading ? (
            <tr>
              <td colSpan="6" className="text-center">
                <Spinner animation="border" /> Loading...
              </td>
            </tr>
          ) : data.length === 0 ? (
            <tr>
              <td colSpan="6" className="text-center">No dashboards available.</td>
            </tr>
          ) : (
            data.map((dashboard) => (
              <tr key={dashboard.id}>
                <td>
                  <span
                    className="badge bg-info text-dark"
                    style={{ cursor: "pointer" }}
                    onClick={() => handleSetUp(dashboard.id)}
                  >
                    SET UP
                  </span>
                </td>
                <td>{dashboard.dashboard_name}</td>
                <td>{dashboard.description}</td>
                <td>{dashboard.secuirity_profile}</td>
                <td>{dashboard.add_to_home ? "Yes" : "No"}</td>
                <td>
                  <i
                    className="bi bi-trash text-danger"
                    style={{ cursor: "pointer" }}
                    onClick={() => handleDeleteClick(dashboard)}
                  ></i>
                  <i
                    className="bi bi-pencil text-primary mx-2"
                    style={{ cursor: "pointer" }}
                    onClick={() => handleEditClick(dashboard)}
                  ></i>
                </td>
              </tr>
            ))
          )}
        </tbody>
      </Table>
      {/* Add Modal */}
      <Modal show={addModal} onHide={() => setAddModal(false)} size="lg" centered>
        <Modal.Body>
          <div className="d-flex justify-content-around">
            <div
              className="chart-box text-center"
              onClick={() => console.log("Start from Scratch")}
            >
              <img
                src="/assets/images/fromscratch.png"
                alt="Start from Scratch"
                height="90"
                width="90"
              />
              <h5>{translate("Start_from_scratch")}</h5>
            </div>
            <div
              className="chart-box text-center"
              onClick={() => console.log("Import from Template")}
            >
              <img
                src="/assets/images/copytemplate.png"
                alt="Import from Template"
                height="90"
                width="90"
              />
              <h5>{translate("Import_from_template")}</h5>
            </div>
            <div
              className="chart-box text-center"
              onClick={() => console.log("Import from Public Project")}
            >
              <img
                src="/assets/images/database.png"
                alt="Import from Public Project"
                height="90"
                width="90"
              />
              <h5>{translate("Import_from_public_project")}</h5>
            </div>
          </div>
        </Modal.Body>
      </Modal>

      {/* Confirmation Modal */}
      <ConfirmModal
        show={showConfirmModal}
        onHide={() => setShowConfirmModal(false)}
        onConfirm={handleDeleteConfirm}
        title="Delete Dashboard"
        message={`Are you sure you want to delete "${selectedRow?.dashboard_name || 'this dashboard'}"? This action cannot be undone.`}
        confirmLabel="Delete"
        cancelLabel="Cancel"
        variant="danger"
      />

    </div>
  );
};

export default DashboardNewAll;
