import React, { useState, useEffect } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { useTranslation } from "react-i18next";
import * as XLSX from "xlsx";
import { toast } from "react-toastify";
import {
  Box,
  Button,
  Card,
  CardContent,
  Typography,
  CircularProgress,
  Alert,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  IconButton,
  Modal,
  Tooltip
} from "@mui/material";
import {
  Add as AddIcon,
  Delete as DeleteIcon,
  Edit as EditIcon,
  GridOn as GridIcon,
  FileDownload as ExportIcon,
  Schedule as TimeIcon
} from "@mui/icons-material";
import DashboardBuilderService from "../../../src/ApiServices/DashboardBuilderServices";
import ConfirmModal from "../common/ConfirmModel";

const DashboardNewAll = () => {
  const { t: translate } = useTranslation();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [selectedRow, setSelectedRow] = useState(null);

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

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

  const fetchAllDashboards = async () => {
    try {
      setLoading(true);
      const dashboards = await DashboardBuilderService.getAllDash();
      setData(dashboards);
      toast.success("Dashboards fetched successfully.");
    } catch (error) {
      console.error('Error fetching dashboards:', error);
      toast.error('Failed to fetch dashboards.');
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleAddClick = () => {
    navigate("/dashboard/dashboard-new-add");
  };

  const handleRunner = () => {
    navigate("/dashboard/dashboard-runner-all");
  };

  const handleEditClick = (dashboard) => {
    navigate(`/dashboard/dashboard-new-edit/${dashboard.id}`, { state: { dashboard } });
  };

  const handleDeleteClick = (row) => {
    setSelectedRow(row);
    setShowConfirmModal(true);
  };

  const handleDeleteConfirm = async () => {
    try {
      await DashboardBuilderService.deleteField(selectedRow.id);
      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.");
    }
    setShowConfirmModal(false);
  };

  const handleExport = () => {
    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.json_to_sheet(data);
    XLSX.utils.book_append_sheet(workbook, worksheet, "Dashboards");
    XLSX.writeFile(workbook, "dashboards_export.xlsx");
  };

  const handleSetUp = (id) => {
    navigate(`/dashboard/edit-new-dash/${id}`, { dashboardId: id });
  };

  return (
    <Box sx={{ p: 3 }}>
      <Box sx={{ display: "flex", justifyContent: "space-between", mb: 3 }}>
        <Typography variant="h4">{translate("Dashboard Builder")}</Typography>
        <Box sx={{ display: "flex", gap: 2 }}>
          <Button
            variant="contained"
            startIcon={<GridIcon />}
            onClick={handleRunner}
          >
            {translate("Dashboard_runner")}
          </Button>
          <Button
            variant="outlined"
            startIcon={<ExportIcon />}
            onClick={handleExport}
          >
            {translate("EXPORT_XLSX")}
          </Button>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={handleAddClick}
          >
            {translate("ADD")}
          </Button>
        </Box>
      </Box>

      {loading ? (
        <Box sx={{ display: "flex", justifyContent: "center", my: 4 }}>
          <CircularProgress />
        </Box>
      ) : error ? (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      ) : data.length === 0 ? (
        <Alert severity="info">No dashboards available.</Alert>
      ) : (
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Go To</TableCell>
                <TableCell>Dashboard Name</TableCell>
                <TableCell>Description</TableCell>
                <TableCell>Security Profile</TableCell>
                <TableCell>Add to Home</TableCell>
                <TableCell>Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {data.map((dashboard) => (
                <TableRow key={dashboard.id}>
                  <TableCell>
                    <Button
                      variant="outlined"
                      size="small"
                      onClick={() => handleSetUp(dashboard.id)}
                    >
                      SET UP
                    </Button>
                  </TableCell>
                  <TableCell>{dashboard.dashboard_name}</TableCell>
                  <TableCell>{dashboard.description}</TableCell>
                  <TableCell>{dashboard.secuirity_profile}</TableCell>
                  <TableCell>{dashboard.add_to_home ? "Yes" : "No"}</TableCell>
                  <TableCell>
                    <Tooltip title="Edit">
                      <IconButton
                        color="primary"
                        onClick={() => handleEditClick(dashboard)}
                      >
                        <EditIcon />
                      </IconButton>
                    </Tooltip>
                    <Tooltip title="Delete">
                      <IconButton
                        color="error"
                        onClick={() => handleDeleteClick(dashboard)}
                      >
                        <DeleteIcon />
                      </IconButton>
                    </Tooltip>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      )}

      <ConfirmModal
        open={showConfirmModal}
        onClose={() => setShowConfirmModal(false)}
        onConfirm={handleDeleteConfirm}
        title="Delete Dashboard"
        message={`Are you sure you want to delete "${selectedRow?.dashboard_name || 'this dashboard'}"?`}
        confirmText="Delete"
        cancelText="Cancel"
        confirmColor="error"
      />
    </Box>
  );
};

export default DashboardNewAll;