import React, { useState, useEffect } from 'react';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
import { Responsive, WidthProvider } from 'react-grid-layout';
import { FormControl, Input, Select, Checkbox, Button, Dialog, DialogActions, DialogContent, DialogTitle, Typography, Card, CardContent, MenuItem, Box } from '@mui/material';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTrash, faGripLines, faPen } from '@fortawesome/free-solid-svg-icons';
import { useNavigate, useParams } from 'react-router-dom';
import DashboardBuilderService from "../../../../APIServices/DashboardBuilderService";
import TextField from '@mui/material/TextField';
import FormControlLabel from '@mui/material/FormControlLabel';

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

// Use WidthProvider to handle responsive behavior
const ResponsiveGridLayout = WidthProvider(Responsive);

const EditNewDash = () => {
  const { id } = useParams();   // fetching id from the url
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [currentEditWidget, setCurrentEditWidget] = useState({});
  const [dashboardName, setDashboardName] = useState();
  const [dashboardLine, setDashboardLine] = useState();  
  const [columnData] = useState(['Column1', 'Column2', 'Column3']);
  const [dashboardWidgets, setDashboardWidgets] = useState([]);
  const [dashboardlineId, setDashboardlineId]= useState();

  // Define available widgets
  const [availableWidgets] = useState([
    { identifier: 'radar_chart', name: 'Radar Chart' },
    { identifier: 'polar_chart', name: 'Polar Chart' },
    { identifier: 'pie_chart', name: 'Pie Chart' },
    { identifier: 'bar_chart', name: 'Bar Chart' },
    { identifier: 'bubble_chart', name: 'Bubble Chart' },
    { identifier: 'line_chart', name: 'Line Chart' },
    { identifier: 'doughnut_chart', name: 'Doughnut Chart' },
    { identifier: 'dynamic_chart', name: 'Dynamic Chart' },
    { identifier: 'financial_chart', name: 'Financial Chart' },
    { identifier: 'grid_view', name: 'Grid View' },
    { identifier: 'scatter_chart', name: 'Scatter Chart' },
    { identifier: 'todo_chart', name: 'Todo Chart' },
  ]);

  // Define component mapping object for easier lookup
  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'
  };

  // fetching dashboard data by id (id is fetched from the url)
  useEffect(() => {
    fetchDashboardData();
  }, []);

  const fetchDashboardData = async () => {
    try {
      const response = await DashboardBuilderService.getById(id);
      console.log("Raw API response:", response);
      console.log("dashboardid: ",response.dashbord1_Line[0].id)
      setDashboardlineId(response.dashbord1_Line[0].id)
      setDashboardName(response.dashboard_name);
      setDashboardLine(response.dashbord1_Line);

      if (response.dashbord1_Line && response.dashbord1_Line[0]?.model) {
        try {
          const modelData = response.dashbord1_Line[0].model;
          console.log("Model Data:", modelData);

          const parsedModel = JSON.parse(modelData);
          console.log("Parsed Model:", parsedModel);

          // Transform the data format to match what ResponsiveGridLayout expects
          const transformedWidgets = Array.isArray(parsedModel.dashboard) 
            ? parsedModel.dashboard.map((widget, index) => {
                // Create a widget ID if not present
                const widgetId = widget.i || `widget-${index}`;
                
                // Get the component identifier from name if component is provided as a string
                const typeIdentifier = widget.type || 
                  (widget.component && typeof widget.component === 'string' 
                    ? componentNameToIdentifier[widget.component] || widget.component.toLowerCase().replace(' ', '_')
                    : 'unknown');
                
                // Get component reference from the component map
                const componentRef = componentMap[typeIdentifier] || null;
                
                // Map the widget properties to the expected format
                return {
                  i: widgetId,
                  x: widget.x || 0,
                  y: widget.y || 0,
                  w: widget.cols || 6,  // Convert cols to w
                  h: widget.rows || 8,  // Convert rows to h
                  type: typeIdentifier,
                  name: widget.name || availableWidgets.find(w => w.identifier === typeIdentifier)?.name || 'Unknown Widget',
                  component: componentRef,
                  chartTitle: widget.chartTitle,
                  showLegend: widget.showLegend,
                  showLabel: widget.showLabel,
                  xAxis: widget.xAxis,
                  yAxis: widget.yAxis
                };
              }) 
            : [];
            
          console.log("Transformed widgets:", transformedWidgets);
          setDashboardWidgets(transformedWidgets);
        } catch (parseError) {
          console.error("Error parsing dashboard model:", parseError);
          setDashboardWidgets([]);
        }
      } else {
        console.log("No valid model data, setting empty widgets.");
        setDashboardWidgets([]);
      }
    } catch (error) {
      console.error("Error fetching dashboard data:", error);
      setDashboardWidgets([]);
    }
  };

  useEffect(() => {
    console.log("Updated dashboardWidgets:", dashboardWidgets);
  }, [dashboardWidgets]);

  const [dashboardForm, setDashboardForm] = useState({
    donut: '',
    chartlegend: '',
    showlabel: '',
    charturl: '',
    chartparameter: '',
    datastore: '',
    table: '',
    datasource: '',
    charttitle: '',
    id: '',
    fieldName: '',
    chartcolor: '',
    slices: '',
    yAxis: '',
    xAxis: '',
  });

  const navigate = useNavigate();

  // Handle widget drag from sidebar
  const onDragStart = (e, widget) => {
    e.dataTransfer.setData('widgetType', widget.identifier);
  };

  // Handle widget drop onto dashboard
  const onDragOver = (e) => {
    e.preventDefault();
  };

  const onDrop = (e) => {
    e.preventDefault();
    const widgetType = e.dataTransfer.getData('widgetType');

    if (!widgetType) return;

    // Calculate drop position relative to the grid
    const gridRect = e.currentTarget.getBoundingClientRect();
    const x = Math.floor((e.clientX - gridRect.left) / 100) * 2;
    const y = Math.floor((e.clientY - gridRect.top) / 100) * 2;

    // Create new widget based on type
    let maxChartId = dashboardWidgets?.reduce((maxId, item) => Math.max(maxId, item.chartid || 0), 0);
    console.log("maxChartId",maxChartId)
    const newWidgetId = `widget-${Date.now()}`;
    const componentRef = componentMap[widgetType] || null;
    const widgetName = availableWidgets.find(w => w.identifier === widgetType)?.name || 'Unknown Widget';
    
    const newWidget = {
      i: newWidgetId,
      x: x,
      y: y,
      w: 6,
      h: 8,
      type: widgetType,
      name: widgetName,
      component: componentRef,  // Add the component reference here
      chartTitle: widgetName,   // Add default chart title
      showLegend: true,         // Add default values for chart config
      showLabel: true,
      xAxis: 'Month',
      yAxis: 'Value'
    };

    setDashboardWidgets(prev => [...prev, newWidget]);
  };

  // Handle layout changes
  const onLayoutChange = (layout) => {
    // Update widget positions when layout changes
    const updatedWidgets = dashboardWidgets.map(widget => {
      const updatedPosition = layout.find(item => item.i === widget.i);
      if (updatedPosition) {
        return { ...widget, x: updatedPosition.x, y: updatedPosition.y, w: updatedPosition.w, h: updatedPosition.h };
      }
      return widget;
    });

    setDashboardWidgets(updatedWidgets);
  };

  // Remove widget
  const removeWidget = (widgetId) => {
    setDashboardWidgets(prev => prev.filter(widget => widget.i !== widgetId));
  };

  // Edit widget
  const editWidget = (widget) => {
    console.log("Opening edit modal for:", widget);
    setCurrentEditWidget(widget);
    setEditModalOpen(true);
  };

  // Save edited widget
  const saveWidgetChanges = () => {
    setDashboardWidgets(prev =>
      prev.map(widget =>
        widget.i === currentEditWidget.i ? { ...widget, ...currentEditWidget } : widget
      )
    );
    setEditModalOpen(false);
  };

  // Navigate back
  const goBack = () => {
    navigate('/admin/dashboard-new-all');
  };

  const dashbord1_Line = {
    model:''
    }
  // Save dashboard
  const saveDashboard = async () => {
    try {
      // Ensure dashboardWidgets is not empty before saving
      if (!dashboardWidgets || dashboardWidgets.length === 0) {
        console.warn("No widgets to save.");
        return;
      }
  
      // Prepare the dashboard data
      const dashboardData = {
        dashboard: dashboardWidgets.map(widget => ({
          x: widget.x ?? 0,  // Default values to prevent errors
          y: widget.y ?? 0,
          cols: widget.w ?? 1,
          rows: widget.h ?? 1,
          component: widget.name || "Unknown",
          name: widget.name || "Unknown",
          // type: widget.type || "Generic",
        })),
      };
  
      console.log("Saving dashboard:", dashboardData);
      console.log("Saving dashboard:", JSON.stringify(dashboardData))
      dashbord1_Line.model = JSON.stringify(dashboardData)
      console.log("dashbord1_Line: ", dashbord1_Line)
      // Call the API to update the dashboard data
      const response = await DashboardBuilderService.updateLineData(dashboardlineId, dashbord1_Line);
  
      if (response) {
        console.log("Dashboard saved successfully:", response.data);
        // Optionally navigate after saving
        navigate('/admin/dashboard-new-all');
      } else {
        console.error("Failed to save dashboard. Server response:", response);
      }
    } catch (error) {
      console.error("Error saving dashboard:", error.message || error);
    }
  };
  

  return (
    <Box sx={{
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      padding: 3
    }}>
      {/* Toolbar */}
      <Box sx={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: '100%',
        marginBottom: 3
      }}>
        <Button
          variant="contained"
          color="primary"
          onClick={() => setSidebarOpen(!sidebarOpen)}
        >
          {sidebarOpen ? 'Hide Components' : 'Add Components'}
        </Button>

        <Typography variant="h5">{dashboardName}</Typography>

        <Box>
          <Button
            variant="outlined"
            sx={{ marginRight: 1 }}
            onClick={goBack}
          >
            Cancel
          </Button>
          <Button
            variant="contained"
            color="primary"
            onClick={saveDashboard}
          >
            Save Dashboard
          </Button>
        </Box>
      </Box>

      {/* Main content */}
      <Box sx={{
        display: 'flex',
        flex: 1,
        width: '100%',
        overflow: 'hidden'
      }}>
        {/* Sidebar */}
        {sidebarOpen && (
          <Box sx={{
            width: 250,
            backgroundColor: '#f5f5f5',
            padding: 2,
            overflowY: 'auto',
            borderRight: '1px solid #e0e0e0'
          }}>
            <Typography variant="h6" sx={{ marginBottom: 2 }}>
              Available Components
            </Typography>
            <Box component="ul" sx={{
              listStyleType: 'none',
              padding: 0,
              margin: 0
            }}>
              {availableWidgets.map(widget => (
                <Box
                  component="li"
                  key={widget.identifier}
                  sx={{
                    padding: 1.5,
                    marginBottom: 1,
                    backgroundColor: 'white',
                    borderRadius: 1,
                    cursor: 'move',
                    border: '1px solid #e0e0e0',
                    '&:hover': {
                      backgroundColor: '#f0f7ff'
                    }
                  }}
                  draggable
                  onDragStart={(e) => onDragStart(e, widget)}
                >
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <FontAwesomeIcon icon={faGripLines} style={{ marginRight: 10 }} />
                    {widget.name}
                  </Box>
                </Box>
              ))}
            </Box>
          </Box>
        )}

        {/* Dashboard grid */}
        <Box
          sx={{
            flex: 1,
            padding: 2,
            overflow: 'auto',
            backgroundColor: '#fafafa'
          }}
          onDragOver={onDragOver}
          onDrop={onDrop}
        >
          <ResponsiveGridLayout
            className="layout"
            draggableCancel=".MuiButton-root, .MuiIconButton-root, button, [role='button']"
            layouts={{
              lg: dashboardWidgets.map(widget => ({
                i: widget.i,
                x: widget.x,
                y: widget.y,
                w: widget.w,
                h: widget.h,
                minW: 3,
                minH: 3
              }))
            }}
            breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
            cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}
            rowHeight={30}
            onLayoutChange={onLayoutChange}
            isDraggable
            isResizable
            margin={[20, 20]}
          >
            {dashboardWidgets.map(widget => (
              <Box key={widget.i} sx={{ overflow: 'hidden' }}>
                <Card sx={{
                  height: '100%',
                  display: 'flex',
                  flexDirection: 'column',
                  boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)'
                }}>
                  <Box sx={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    padding: 1,
                    borderBottom: '1px solid #eee'
                  }}>
                    <Typography variant="subtitle1" sx={{ fontWeight: 'bold' }}>
                      {widget.name}
                    </Typography>
                    <Box>
<Button
  size="small"
  onClick={(e) => {
    e.stopPropagation();
    editWidget(widget);
  }}
>
  <FontAwesomeIcon icon={faPen} />
</Button>

                      <Button
                        size="small"
                        color="error"
                        onClick={() => {
                          console.log("Edit button clicked for widget:", widget);
                          removeWidget(widget.i)}
                        }
                        sx={{ minWidth: 'auto', padding: '4px', ml: 1 }}
                      >
                        <FontAwesomeIcon icon={faTrash} />
                      </Button>
                    </Box>
                  </Box>
                  <CardContent sx={{
                    flex: 1,
                    padding: 2,
                    overflow: 'hidden',
                    display: 'flex',
                    flexDirection: 'column',
                    height: 'calc(100% - 50px)' // Subtracting header height
                  }}>
                    {widget.component && (
                      <Box sx={{
                        width: '100%',
                        height: '100%',
                        display: 'flex',
                        flexDirection: 'column',
                        overflow: 'hidden'
                      }}>
                        <widget.component
                          chartTitle={widget.chartTitle || widget.name}
                          showLegend={widget.showLegend !== undefined ? widget.showLegend : true}
                          showLabel={widget.showLabel !== undefined ? widget.showLabel : true}
                          xAxis={widget.xAxis || 'Month'}
                          yAxis={widget.yAxis || 'Value'}
                          width="100%"
                          height="100%"
                        />
                      </Box>
                    )}
                  </CardContent>
                </Card>
              </Box>
            ))}
          </ResponsiveGridLayout>
        </Box>
      </Box>

      {/* Edit widget dialog */}
      <Dialog open={editModalOpen} onClose={() => setEditModalOpen(false)} maxWidth="sm" fullWidth>
  <DialogTitle>Edit {currentEditWidget?.name}</DialogTitle>
  <DialogContent dividers>
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
      <TextField
        label="Chart Title"
        fullWidth
        value={currentEditWidget?.chartTitle || ''}
        onChange={(e) =>
          setCurrentEditWidget((prev) => ({ ...prev, chartTitle: e.target.value }))
        }
      />
      <TextField
        label="X Axis Label"
        fullWidth
        value={currentEditWidget?.xAxis || ''}
        onChange={(e) =>
          setCurrentEditWidget((prev) => ({ ...prev, xAxis: e.target.value }))
        }
      />
      <TextField
        label="Y Axis Label"
        fullWidth
        value={currentEditWidget?.yAxis || ''}
        onChange={(e) =>
          setCurrentEditWidget((prev) => ({ ...prev, yAxis: e.target.value }))
        }
      />
      <FormControl>
        <FormControlLabel
          control={
            <Checkbox
              checked={currentEditWidget?.showLegend ?? true}
              onChange={(e) =>
                setCurrentEditWidget((prev) => ({ ...prev, showLegend: e.target.checked }))
              }
            />
          }
          label="Show Legend"
        />
        <FormControlLabel
          control={
            <Checkbox
              checked={currentEditWidget?.showLabel ?? true}
              onChange={(e) =>
                setCurrentEditWidget((prev) => ({ ...prev, showLabel: e.target.checked }))
              }
            />
          }
          label="Show Labels"
        />
      </FormControl>
    </Box>
  </DialogContent>
  <DialogActions>
    <Button onClick={() => setEditModalOpen(false)} color="secondary">
      Cancel
    </Button>
    <Button onClick={saveWidgetChanges} variant="contained" color="primary">
      Save Changes
    </Button>
  </DialogActions>
</Dialog>
</Box>
  );
};

export default EditNewDash;