import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Box,
  Button,
  Card,
  CardContent,
  CardHeader,
  CircularProgress,
  Typography,
  useTheme
} from '@mui/material';
import { ArrowBack as ArrowBackIcon } from '@mui/icons-material';
import DashboardBuilderService from "../../../ApiServices/DashboardBuilderServices";

// Import chart components
import LineChartComponent from '../gadgets/linechart';
import PieChartComponent from '../gadgets/piechart';
import PolarChartComponent from '../gadgets/polarchart';
import RadarChartComponent from '../gadgets/radarchart';
import BubbleChart from '../gadgets/bubblechart';
import BarChart from '../gadgets/barchart';
import DoughnutChart from '../gadgets/doughnut';
import DynamicChart from '../gadgets/dynamicchart';
import FinancialChart from '../gadgets/financialchart';
import GridViewComponent from '../gadgets/gridview';
import ScatterChartComponent from '../gadgets/scatterchart';
import ToDoChartComponent from '../gadgets/todochart';

const ViewDashboard = () => {
  const { id } = useParams();
  const theme = useTheme();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [dashboard, setDashboard] = useState(null);
  const [layout, setLayout] = useState([]);

  const componentMap = {
    'radar_chart': RadarChartComponent,
    'polar_chart': PolarChartComponent,
    'pie_chart': PieChartComponent,
    'bar_chart': BarChart,
    'bubble_chart': BubbleChart,
    'line_chart': LineChartComponent,
    'doughnut_chart': DoughnutChart,
    'dynamic_chart': DynamicChart,
    'financial_chart': FinancialChart,
    'grid_view': GridViewComponent,
    'scatter_chart': ScatterChartComponent,
    'todo_chart': ToDoChartComponent
  };

  useEffect(() => {
    const fetchDashboard = async () => {
      try {
        setLoading(true);
        const response = await DashboardBuilderService.getById(id);

        setDashboard({
          name: response.dashboard_name,
          dashboardLine: response.dashbord1_Line
        });

        if (response.dashbord1_Line && response.dashbord1_Line[0]?.model) {
          const modelData = response.dashbord1_Line[0].model;
          const parsedModel = JSON.parse(modelData);

          if (Array.isArray(parsedModel.dashboard)) {
            const dashboardLayout = parsedModel.dashboard.map((widget, index) => {
              const componentName = widget.component || "Unknown";
              const typeIdentifier = componentName.toLowerCase().replace(' ', '_');
              const Component = componentMap[typeIdentifier] || null;

              return {
                id: `widget-${index}`,
                x: widget.x || 0,
                y: widget.y || 0,
                w: widget.cols || 6,
                h: widget.rows || 8,
                name: widget.name || componentName,
                component: Component,
                chartTitle: widget.chartTitle || widget.name || componentName,
                showLegend: widget.showLegend !== undefined ? widget.showLegend : true,
                showLabel: widget.showLabel !== undefined ? widget.showLabel : true,
                xAxis: widget.xAxis || 'Month',
                yAxis: widget.yAxis || 'Value'
              };
            });

            setLayout(dashboardLayout);
          }
        }
      } catch (error) {
        console.error("Error fetching dashboard:", error);
        setError("Failed to load dashboard. Please try again later.");
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchDashboard();
    }
  }, [id]);

  const getWidgetStyle = (widget) => {
    const columnWidth = 100 / 6;
    const rowHeight = 40;

    return {
      position: 'absolute',
      left: `${widget.x * columnWidth}%`,
      top: `${widget.y * rowHeight}px`,
      width: `${widget.w * columnWidth}%`,
      height: `${widget.h * rowHeight}px`,
    };
  };

  if (loading) {
    return (
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100vh',
          backgroundColor: theme.palette.background.default
        }}
      >
        <CircularProgress />
        <Typography variant="h6" sx={{ ml: 2 }}>
          Loading Dashboard...
        </Typography>
      </Box>
    );
  }

  if (error) {
    return (
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100vh',
          flexDirection: 'column',
          backgroundColor: theme.palette.background.default
        }}
      >
        <Typography variant="h5" color="error" gutterBottom>
          Error Loading Dashboard
        </Typography>
        <Typography variant="body1">{error}</Typography>
        <Button 
          variant="contained" 
          onClick={() => navigate(-1)}
          sx={{ mt: 2 }}
        >
          Go Back
        </Button>
      </Box>
    );
  }

  return (
    <Box sx={{ 
      padding: 3,
      backgroundColor: theme.palette.background.default,
      minHeight: '100vh'
    }}>
      <Box sx={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        mb: 3
      }}>
        <Typography variant="h4" color="text.primary">
          {dashboard?.name || 'Dashboard View'}
        </Typography>
        <Button 
          variant="contained" 
          startIcon={<ArrowBackIcon />}
          onClick={() => navigate(-1)}
        >
          Back
        </Button>
      </Box>

      {layout.length === 0 ? (
        <Card sx={{ textAlign: 'center', p: 5 }}>
          <Typography variant="h6">No widgets found in this dashboard.</Typography>
        </Card>
      ) : (
        <Box
          sx={{
            position: 'relative',
            minHeight: '800px'
          }}
        >
          {layout.map((widget) => {
            const Component = widget.component;
            const style = getWidgetStyle(widget);

            return (
              <Box
                key={widget.id}
                sx={{
                  ...style,
                  padding: 1,
                  boxSizing: 'border-box'
                }}
              >
                <Card sx={{
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  boxShadow: theme.shadows[2]
                }}>
                  <CardHeader
                    title={widget.chartTitle}
                    titleTypographyProps={{ variant: 'h6' }}
                    sx={{
                      backgroundColor: theme.palette.background.paper,
                      borderBottom: `1px solid ${theme.palette.divider}`
                    }}
                  />
                  <CardContent sx={{
                    flex: 1,
                    display: 'flex',
                    flexDirection: 'column',
                    p: 2,
                    pt: 1,
                    overflow: 'hidden'
                  }}>
                    {Component ? (
                      <Box sx={{
                        flexGrow: 1,
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}>
                        <Component
                          chartTitle={widget.chartTitle}
                          showLegend={widget.showLegend}
                          showLabel={widget.showLabel}
                          xAxis={widget.xAxis}
                          yAxis={widget.yAxis}
                          width="100%"
                          height="100%"
                        />
                      </Box>
                    ) : (
                      <Box sx={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        height: '100%'
                      }}>
                        <Typography variant="body2" color="text.secondary">
                          Widget type "{widget.name}" not available
                        </Typography>
                      </Box>
                    )}
                  </CardContent>
                </Card>
              </Box>
            );
          })}
        </Box>
      )}
    </Box>
  );
};

export default ViewDashboard;