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

const Report = () => {
  const [reports, setReports] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const navigate = useNavigate();

  const api = process.env.REACT_APP_API_BASE_URL;
  console.log("API Base URL:", api);
  useEffect(() => {
    const fetchData = async () => {
      const token = localStorage.getItem("authToken");

      if (!token) {
        setError("No auth token found. Please login.");
        toast.error("Authentication required");
        navigate("/login");
        return;
      }

      try {
        const response = await fetch(`${api}/Rpt_builder2/Rpt_builder2`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (!response.ok) {
          throw new Error(response.status === 401 ? "Session expired" : "Failed to fetch data");
        }

        const data = await response.json();
        setReports(data);
      } catch (error) {
        console.error("Error fetching data:", error);
        setError(error.message);
        if (error.message === "Session expired") {
          toast.error("Session expired. Please login again.");
          navigate("/login");
        }
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [api, navigate]);

  const goToAddSQLReport = () => {
    navigate("/dashboard/user-report");
  };

  const goToAddURLReport = () => {
    navigate("/admin/reportbuild2all");
  };

  const handleCardClick = (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 }
      });
    }
  };

  return (
    <Container maxWidth="xl" sx={{ py: 4 }}>
      {/* Header Section */}
      <Paper elevation={2} sx={{ 
        p: 3, 
        mb: 4, 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        borderRadius: '12px'
      }}>
        <Typography variant="h4" color="primary" sx={{ fontWeight: 'bold' }}>
          All Reports
        </Typography>
        <Box>
          <Button
            variant="contained"
            startIcon={<AddCircleOutline />}
            onClick={goToAddSQLReport}
            sx={{ mr: 2 }}
          >
            Report Builder SQL
          </Button>
          <Button
            variant="contained"
            startIcon={<AddCircleOutline />}
            onClick={goToAddURLReport}
          >
            Report Builder URL
          </Button>
        </Box>
      </Paper>

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

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

      {/* Reports Grid */}
      {!loading && reports.length > 0 && (
        <Grid container spacing={3}>
          {reports.map((report) => (
            <Grid item xs={12} sm={6} md={4} lg={3} key={report.id}>
              <Card 
                sx={{ 
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  cursor: 'pointer',
                  transition: 'transform 0.3s, box-shadow 0.3s',
                  '&:hover': {
                    transform: 'translateY(-8px)',
                    boxShadow: 6
                  },
                  borderRadius: '16px',
                  overflow: 'hidden'
                }}
                onClick={() => handleCardClick(report)}
              >
                {/* Card Header with Gradient */}
                <Box
                  sx={{
                    p: 2,
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    borderBottom: '1px solid',
                    borderColor: 'divider',
                    background: report.isSql 
                      ? 'linear-gradient(135deg, #f5f7fa 0%,rgb(198, 218, 255) 100%)' 
                      : 'linear-gradient(135deg, #fff9f0 0%,rgb(217, 204, 255) 100%)',
                    height: '60px'
                  }}
                >
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <Avatar
                      sx={{ 
                        width: 36,
                        height: 36,
                        mr: 2,
                        borderRadius: '10px',
                        bgcolor: report.isSql ? 'rgba(65, 105, 225, 0.15)' : 'rgba(255, 165, 0, 0.15)',
                        color: report.isSql ? '#4169E1' : '#FF8C00'
                      }}
                    >
                      {report.isSql ? <Database /> : <LinkIcon />}
                    </Avatar>
                    <Typography
                      variant="subtitle2"
                      sx={{ 
                        color: report.isSql ? '#4169E1' : '#FF8C00',
                      }}
                    >
                      {report.isSql ? "SQL Report" : "URL Report"}
                    </Typography>
                  </Box>

                  {/* Status Chip */}
                  <Chip
                    label={report.active ? "Active" : "Inactive"}
                    size="small"
                    color={report.active ? "success" : "error"}
                    icon={report.active ? <CheckCircle fontSize="small" /> : <Cancel fontSize="small" />}
                    sx={{
                      backgroundColor: report.active ? 'rgba(40, 167, 69, 0.1)' : 'rgba(220, 53, 69, 0.1)',
                      color: report.active ? '#28a745' : '#dc3545',
                      px: 1,
                      py: 0.5
                    }}
                  />
                </Box>

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

                {/* Card Footer */}
                <Box
                  sx={{
                    p: 2,
                    borderTop: '1px solid',
                    borderColor: 'divider',
                    backgroundColor: 'background.default'
                  }}
                >
                  <Box sx={{ 
                    display: 'flex', 
                    justifyContent: 'space-between', 
                    alignItems: 'center' 
                  }}>
                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                      <AccessTime fontSize="small" sx={{ mr: 1, color: 'text.secondary' }} />
                      <Typography variant="caption" color="text.secondary">
                        Updated: {new Date(report.updatedAt).toLocaleDateString()}
                      </Typography>
                    </Box>
                    <IconButton
                      size="small"
                      sx={{ 
                        backgroundColor: 'action.hover',
                        '&:hover': {
                          backgroundColor: 'action.selected'
                        }
                      }}
                      onClick={(e) => {
                        e.stopPropagation();
                        // Add menu functionality here
                      }}
                    >
                      <MoreVert fontSize="small" />
                    </IconButton>
                  </Box>
                </Box>
              </Card>
            </Grid>
          ))}
        </Grid>
      )}

      {/* Empty State */}
      {!loading && reports.length === 0 && !error && (
        <Paper sx={{ 
          p: 4, 
          textAlign: 'center',
          borderRadius: '12px'
        }}>
          <Typography variant="h6" gutterBottom>
            No reports available
          </Typography>
          <Typography variant="body1" color="text.secondary" sx={{ mb: 3 }}>
            Create your first report by clicking one of the "Add Report" buttons
          </Typography>
          <Box>
            <Button
              variant="contained"
              startIcon={<AddCircleOutline />}
              onClick={goToAddSQLReport}
              sx={{ mr: 2 }}
            >
              Add SQL Report
            </Button>
            <Button
              variant="contained"
              startIcon={<AddCircleOutline />}
              onClick={goToAddURLReport}
            >
              Add URL Report
            </Button>
          </Box>
        </Paper>
      )}
    </Container>
  );
};

export default Report;