import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { fetchAllReportsApi } from '../../../ApiServices/ReportRunnerAPI';
import {
  Container,
  Grid,
  Card,
  CardHeader,
  CardContent,
  CardActions,
  Typography,
  Button,
  CircularProgress,
  Alert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Avatar,
  IconButton,
  Chip,
  Divider,
  Paper
} from '@mui/material';
import {
  AddCircleOutline,
  Link,
  Storage as Database,
  MoreVert,
  AccessTime,
  Delete,
  CheckCircle,
  Cancel
} from '@mui/icons-material';

const ReportRunnerAll = () => {
  const [gridData, setGridData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [rowSelected, setRowSelected] = useState(null);
  const [openDeleteDialog, setOpenDeleteDialog] = useState(false);

  const navigate = useNavigate();

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

  const fetchAllReports = async () => {
    setIsLoading(true);
    try {
      const data = await fetchAllReportsApi();
      console.log("Fetched all reports:", data);
      setGridData(data);
      if (data.length === 0) setError("No data available");
    } catch (error) {
      console.error("Error while fetching reports:", error);
      setError("Error fetching data.");
      toast.error("Failed to load reports");
    } finally {
      setIsLoading(false);
    }
  };

  const goToAdd = () => navigate("/admin/user-report");
  const goToAdd2 = () => navigate("/admin/reportbuild2all");

  const goToRunner = (report) => {
    if (report.isSql) {
      navigate(`/admin/report-runner1/${report.id}`, { 
        state: { reportId: report.id, reportData: report }
      });
    } else {
      navigate(`/admin/report-runner2/${report.id}`, { 
        state: { reportId: report.id, reportData: report }
      });
    }
  };

  const handleDelete = async (id) => {
    setOpenDeleteDialog(false);
    try {
      const response = await fetch(`/api/report-builder/${id}`, { 
        method: "DELETE" 
      });
      if (response.ok) {
        toast.success("Report deleted successfully");
        fetchAllReports();
      } else {
        throw new Error("Failed to delete");
      }
    } catch (err) {
      console.error(err);
      toast.error("Error deleting report");
    }
  };

  const openDeleteModal = (row) => {
    setRowSelected(row);
    setOpenDeleteDialog(true);
  };

  return (
    <Container maxWidth="xl" sx={{ py: 4 }}>
      {/* Header */}
      <Paper elevation={2} sx={{ p: 3, mb: 4, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Typography variant="h4" color="primary">
          <Database sx={{ verticalAlign: 'middle', mr: 1 }} />
          All Reports
        </Typography>
        <div>
          <Button
            variant="contained"
            startIcon={<AddCircleOutline />}
            onClick={goToAdd}
            sx={{ mr: 2 }}
          >
            SQL Report
          </Button>
          <Button
            variant="outlined"
            startIcon={<Link />}
            onClick={goToAdd2}
          >
            URL Report
          </Button>
        </div>
      </Paper>

      {/* Loading state */}
      {isLoading && (
        <Grid container justifyContent="center" sx={{ py: 8 }}>
          <CircularProgress size={60} />
        </Grid>
      )}

      {/* Error state */}
      {error && !isLoading && (
        <Alert severity="error" sx={{ mb: 4 }}>
          {error}
        </Alert>
      )}

      {/* Report Cards */}
      {!isLoading && gridData.length > 0 && (
        <Grid container spacing={3}>
          {gridData.map((report, index) => (
            <Grid item xs={12} sm={6} md={4} lg={3} key={index}>
              <Card 
                sx={{ 
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  cursor: 'pointer',
                  transition: 'transform 0.3s, box-shadow 0.3s',
                  '&:hover': {
                    transform: 'translateY(-8px)',
                    boxShadow: 6
                  }
                }}
                onClick={() => goToRunner(report)}
              >
                {/* Card Header */}
                <CardHeader
                  avatar={
                    <Avatar sx={{ 
                      bgcolor: report.isSql ? 'primary.light' : 'secondary.light',
                      color: report.isSql ? 'primary.main' : 'secondary.main'
                    }}>
                      {report.isSql ? <Database /> : <Link />}
                    </Avatar>
                  }
                  action={
                    <Chip
                      label={report.active ? "Active" : "Inactive"}
                      size="small"
                      color={report.active ? "success" : "error"}
                      icon={report.active ? <CheckCircle fontSize="small" /> : <Cancel fontSize="small" />}
                      sx={{ ml: 1 }}
                    />
                  }
                  title={
                    <Typography variant="subtitle1" color="text.secondary">
                      {report.isSql ? "SQL Report" : "URL Report"}
                    </Typography>
                  }
                  sx={{
                    bgcolor: report.isSql ? 'primary.50' : 'secondary.50',
                    borderBottom: '1px solid',
                    borderColor: 'divider'
                  }}
                />

                {/* Card Content */}
                <CardContent sx={{ flexGrow: 1 }}>
                  <Typography gutterBottom variant="h6" component="div" noWrap>
                    {report.reportName}
                  </Typography>
                  <Typography variant="body2" color="text.secondary" sx={{
                    display: '-webkit-box',
                    WebkitLineClamp: 2,
                    WebkitBoxOrient: 'vertical',
                    overflow: 'hidden',
                    minHeight: '40px'
                  }}>
                    {report.description || "No description available"}
                  </Typography>
                </CardContent>

                {/* Card Footer */}
                <Divider />
                <CardActions sx={{ justifyContent: 'space-between', p: 2 }}>
                  <Typography variant="caption" color="text.secondary" sx={{ display: 'flex', alignItems: 'center' }}>
                    <AccessTime fontSize="small" sx={{ mr: 0.5 }} />
                    Updated: {new Date(report.updatedAt).toLocaleDateString()}
                  </Typography>
                  <IconButton 
                    size="small" 
                    onClick={(e) => {
                      e.stopPropagation();
                      openDeleteModal(report);
                    }}
                  >
                    <MoreVert />
                  </IconButton>
                </CardActions>
              </Card>
            </Grid>
          ))}
        </Grid>
      )}

      {/* Delete Dialog */}
      <Dialog
        open={openDeleteDialog}
        onClose={() => setOpenDeleteDialog(false)}
      >
        <DialogTitle>Delete Confirmation</DialogTitle>
        <DialogContent>
          <Typography>
            Are you sure you want to delete the report?
          </Typography>
          <Typography variant="subtitle1" sx={{ mt: 1 }}>
            {rowSelected?.reportName}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenDeleteDialog(false)}>Cancel</Button>
          <Button 
            onClick={() => handleDelete(rowSelected?.id)} 
            color="error"
            startIcon={<Delete />}
          >
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default ReportRunnerAll;