import React, { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import moment from "moment";
import { toast, Toaster } from "react-hot-toast";
import {
  Box,
  Button,
  Card,
  CardContent,
  CardHeader,
  CardActions,
  Grid,
  Typography,
  CircularProgress,
  Alert,
  IconButton,
  Modal
} from "@mui/material";
import {
  Add as AddIcon,
  CalendarToday as CalendarIcon,
  AccessTime as TimeIcon,
  Apps as AppsIcon,
  Delete as DeleteIcon,
  Edit as EditIcon
} from "@mui/icons-material";
import DashboardBuilderService from "../../../ApiServices/DashboardBuilderServices";

const DashboardRunnerAll = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [selectedDashboard, setSelectedDashboard] = useState(null);

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

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

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

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

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

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

  return (
    <Box sx={{ p: 3 }}>
      <Box sx={{ display: "flex", justifyContent: "space-between", mb: 3 }}>
        <Typography variant="h4">All Dashboards</Typography>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={handleAdd}
        >
          Dashboard Builder
        </Button>
      </Box>

      {loading && (
        <Box sx={{ display: "flex", justifyContent: "center", my: 4 }}>
          <CircularProgress />
        </Box>
      )}

      {error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}

      <Grid container spacing={3}>
        {data.map((app, index) => (
          <Grid item xs={12} sm={6} md={4} key={index}>
            <Card
              sx={{
                height: "100%",
                display: "flex",
                flexDirection: "column",
                cursor: "pointer",
                "&:hover": {
                  boxShadow: 6,
                },
              }}
              onClick={() => handleEdit(app.id)}
            >
              <CardHeader
                avatar={<AppsIcon />}
                title={
                  <Typography noWrap fontWeight="bold">
                    {app.dashboard_name}
                  </Typography>
                }
              />
              <CardContent sx={{ flexGrow: 1 }}>
                <Typography variant="body2" color="text.secondary" noWrap>
                  {app.description || "No description available"}
                </Typography>
              </CardContent>
              <CardActions sx={{ justifyContent: "space-between" }}>
                <Typography variant="caption" color="text.secondary">
                  <TimeIcon fontSize="small" sx={{ verticalAlign: "middle", mr: 0.5 }} />
                  {moment(app.updatedAt).format("DD/MM/YYYY")}
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  <CalendarIcon fontSize="small" sx={{ verticalAlign: "middle", mr: 0.5 }} />
                  {moment(app.createdAt).format("HH:mm:ss")}
                </Typography>
              </CardActions>
            </Card>
          </Grid>
        ))}
      </Grid>

      {/* Delete Confirmation Modal */}
      <Modal
        open={deleteModalOpen}
        onClose={() => setDeleteModalOpen(false)}
      >
        <Box sx={{
          position: "absolute",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          width: 400,
          bgcolor: "background.paper",
          boxShadow: 24,
          p: 4,
          borderRadius: 1
        }}>
          <Typography variant="h6" gutterBottom>
            Delete Confirmation
          </Typography>
          <Typography variant="body1" sx={{ mb: 3 }}>
            Are you sure you want to delete this dashboard?
          </Typography>
          <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 2 }}>
            <Button
              variant="outlined"
              onClick={() => setDeleteModalOpen(false)}
            >
              Cancel
            </Button>
            <Button
              variant="contained"
              color="error"
              onClick={() => handleDelete(selectedDashboard?.id)}
            >
              Delete
            </Button>
          </Box>
        </Box>
      </Modal>

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

export default DashboardRunnerAll;