import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom'; // Add useNavigate
import { Box, Typography, CircularProgress, Card, CardHeader, CardContent, Button } from '@mui/material';
import DashboardBuilderService from "../../../APIServices/DashboardBuilderService";

// Import chart components
import LineChartComponent from '../dashboardnew/gadgets/line-chart/LineChart';
import PieChartComponent from '../dashboardnew/gadgets/pie-chart/Piechart';
import PolarChartComponent from '../dashboardnew/gadgets/polar-chart/PolarChart';
import RadarChartComponent from '../dashboardnew/gadgets/radar-chart/RadarChart';
import BubbleChart from '../dashboardnew/gadgets/bubble-chart/BubbleChart';
import BarChart from '../dashboardnew/gadgets/bar-chart/BarChart';
import DoughnutChart from '../dashboardnew/gadgets/doughnut-charts/DoughnutChart';
import DynamicChart from '../dashboardnew/gadgets/dynamic-chart/DynamicChart';
import FinancialChart from '../dashboardnew/gadgets/financial-chart/FinancialChart';
import GridViewComponent from '../dashboardnew/gadgets/grid-view/GridView';
import ScatterChartComponent from '../dashboardnew/gadgets/scatter-chart/ScatterChart';
import ToDoChartComponent from '../dashboardnew/gadgets/to-do-chart/TodoChart';

const ViewDashboard = () => {
  const { id } = useParams(); // Get dashboard ID from URL
  const navigate = useNavigate(); // Use the useNavigate hook
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [dashboard, setDashboard] = useState(null);
  const [layout, setLayout] = useState([]);

  // Define component mapping object
  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
  };

  // Component name to identifier mapping for reverse lookup
  const componentNameToIdentifier = {
    'Radar Chart': 'radar_chart',
    'Polar Chart': 'polar_chart',
    'Pie Chart': 'pie_chart',
    'Bar Chart': 'bar_chart',
    'Bubble Chart': 'bubble_chart',
    'Line Chart': 'line_chart',
    'Doughnut Chart': 'doughnut_chart',
    'Dynamic Chart': 'dynamic_chart',
    'Financial Chart': 'financial_chart',
    'Grid View': 'grid_view',
    'Scatter Chart': 'scatter_chart',
    'Todo Chart': 'todo_chart'
  };

  // Fetch dashboard data using the ID
  useEffect(() => {
    const fetchDashboard = async () => {
      try {
        setLoading(true);
        const response = await DashboardBuilderService.getById(id);
        console.log("Dashboard data:", response);

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

        // Parse and transform widget data
        if (response.dashbord1_Line && response.dashbord1_Line[0]?.model) {
          try {
            const modelData = response.dashbord1_Line[0].model;
            const parsedModel = JSON.parse(modelData);

            if (Array.isArray(parsedModel.dashboard)) {
              console.log("Dashboard widgets from API:", parsedModel.dashboard);

              // Create the layout directly from the API response
              const dashboardLayout = parsedModel.dashboard.map((widget, index) => {
                // Get the component identifier from name
                const componentName = widget.component || "Unknown";
                const typeIdentifier = componentNameToIdentifier[componentName] ||
                  componentName.toLowerCase().replace(' ', '_');

                // Get component reference
                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'
                };
              });

              console.log("Processed layout:", dashboardLayout);
              setLayout(dashboardLayout);
            } else {
              console.warn("Dashboard data is not an array:", parsedModel.dashboard);
              setLayout([]);
            }
          } catch (parseError) {
            console.error("Error parsing dashboard model:", parseError);
            setError("Failed to parse dashboard data. The dashboard may be corrupted.");
            setLayout([]);
          }
        } else {
          console.warn("No dashboard model found");
          setLayout([]);
        }
      } catch (error) {
        console.error("Error fetching dashboard:", error);
        setError("Failed to load dashboard. Please try again later.");
      } finally {
        setLoading(false);
      }
    };

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

  // Calculate absolute positioning based on grid coordinates
  const getWidgetStyle = (widget) => {
    const columnWidth = 100 / 6; // 12-column grid, width percentage
    const rowHeight = 40; // Fixed row height in pixels

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

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

  // Render error state
  if (error) {
    return (
      <Box
        sx={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100vh',
          flexDirection: 'column'
        }}
      >
        <Typography variant="h5" color="error" gutterBottom>
          Error Loading Dashboard
        </Typography>
        <Typography variant="body1">{error}</Typography>
      </Box>
    );
  }

  return (
    <Box sx={{ padding: 0 }}>
      {/* Dashboard Header */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h2>{dashboard?.name || 'Dashboard View'}</h2>
        <Button variant="contained" onClick={() => navigate(-1)}>Back</Button>
      </Box>


      {/* Dashboard Content */}
      {layout.length === 0 ? (
        <Box sx={{ textAlign: 'center', p: 5 }}>
          <Typography variant="h6">No widgets found in this dashboard.</Typography>
        </Box>
      ) : (
        <Box
          sx={{
            position: 'relative',
            minHeight: '800px' // Set a minimum height for the dashboard area
          }}
        >
          {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: '0 2px 10px rgba(0, 0, 0, 0.08)'
                }}>
                  <CardHeader
                    title={widget.chartTitle}
                    titleTypographyProps={{ variant: 'h6' }}
                    sx={{
                      p: 2,
                      pb: 1,
                      backgroundColor: '#fafafa',
                      borderBottom: '1px solid #eee'
                    }}
                  />
                  <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;