import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  Card,
  CardContent,
  Checkbox,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  FormControl,
  FormControlLabel,
  IconButton,
  TextField,
  Typography,
  useTheme
} from '@mui/material';
import {
  DragIndicator as DragIndicatorIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Add as AddIcon,
  Cancel as CancelIcon,
  Save as SaveIcon,
  ArrowBack as ArrowBackIcon
} from '@mui/icons-material';
import { Responsive, WidthProvider } from 'react-grid-layout';
import { useNavigate, useParams } from 'react-router-dom';
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 ResponsiveGridLayout = WidthProvider(Responsive);

const EditNewDash = () => {
  const { id } = useParams();
  const theme = useTheme();
  const navigate = useNavigate();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [currentEditWidget, setCurrentEditWidget] = useState({});
  const [dashboardName, setDashboardName] = useState('');
  const [dashboardLine, setDashboardLine] = useState([]);
  const [dashboardlineId, setDashboardlineId] = useState(null);
  const [dashboardWidgets, setDashboardWidgets] = useState([]);

  const availableWidgets = [
    { 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' },
  ];

  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
  };

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

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

  const fetchDashboardData = async () => {
    try {
      const response = await DashboardBuilderService.getById(id);
      setDashboardlineId(response.dashbord1_Line[0].id);
      setDashboardName(response.dashboard_name);
      setDashboardLine(response.dashbord1_Line);

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

        const transformedWidgets = Array.isArray(parsedModel.dashboard) 
          ? parsedModel.dashboard.map((widget, index) => {
              const widgetId = widget.i || `widget-${index}`;
              const typeIdentifier = widget.type || 
                (widget.component && typeof widget.component === 'string' 
                  ? componentNameToIdentifier[widget.component] || widget.component.toLowerCase().replace(' ', '_')
                  : 'unknown');
              
              const componentRef = componentMap[typeIdentifier] || null;
              
              return {
                i: widgetId,
                x: widget.x || 0,
                y: widget.y || 0,
                w: widget.cols || 6,
                h: widget.rows || 8,
                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
              };
            }) 
          : [];
          
        setDashboardWidgets(transformedWidgets);
      }
    } catch (error) {
      console.error("Error fetching dashboard data:", error);
    }
  };

  const onDragStart = (e, widget) => {
    e.dataTransfer.setData('widgetType', widget.identifier);
  };

  const onDragOver = (e) => {
    e.preventDefault();
  };

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

    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;

    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,
      chartTitle: widgetName,
      showLegend: true,
      showLabel: true,
      xAxis: 'Month',
      yAxis: 'Value'
    };

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

  const onLayoutChange = (layout) => {
    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);
  };

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

  const editWidget = (widget) => {
    setCurrentEditWidget(widget);
    setEditModalOpen(true);
  };

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

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

  const saveDashboard = async () => {
    try {
      if (!dashboardWidgets || dashboardWidgets.length === 0) {
        console.warn("No widgets to save.");
        return;
      }
  
      const dashboardData = {
        dashboard: dashboardWidgets.map(widget => ({
          i: widget.i,
          x: widget.x ?? 0,
          y: widget.y ?? 0,
          w: widget.w ?? 6,
          h: widget.h ?? 8,
          type: widget.type,
          name: widget.name || "Unknown",
          chartTitle: widget.chartTitle,
          showLegend: widget.showLegend,
          showLabel: widget.showLabel,
          xAxis: widget.xAxis,
          yAxis: widget.yAxis
        })),
      };
  
      const dashbord1_Line = {
        model: JSON.stringify(dashboardData)
      };
      
      const response = await DashboardBuilderService.updateLineData(dashboardlineId, dashbord1_Line);
  
      if (response) {
        navigate('/dashboard/dashboard-new-all');
      }
    } catch (error) {
      console.error("Error saving dashboard:", error);
    }
  };

  return (
    <Box sx={{
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      padding: 3,
      backgroundColor: theme.palette.background.default
    }}>
      {/* Toolbar */}
      <Box sx={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: '100%',
        marginBottom: 3
      }}>
        <Button
          variant="contained"
          startIcon={<AddIcon />}
          onClick={() => setSidebarOpen(!sidebarOpen)}
          sx={{ mr: 2 }}
        >
          {sidebarOpen ? 'Hide Components' : 'Add Components'}
        </Button>

        <Typography variant="h5" color="text.primary">
          {dashboardName}
        </Typography>

        <Box>
          <Button
            variant="outlined"
            startIcon={<ArrowBackIcon />}
            onClick={goBack}
            sx={{ mr: 2 }}
          >
            Cancel
          </Button>
          <Button
            variant="contained"
            color="primary"
            startIcon={<SaveIcon />}
            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: theme.palette.background.paper,
            padding: 2,
            overflowY: 'auto',
            borderRight: `1px solid ${theme.palette.divider}`,
            boxShadow: theme.shadows[2]
          }}>
            <Typography variant="h6" sx={{ marginBottom: 2 }}>
              Available Components
            </Typography>
            <Box sx={{
              display: 'grid',
              gap: 1
            }}>
              {availableWidgets.map(widget => (
                <Card
                  key={widget.identifier}
                  sx={{
                    cursor: 'move',
                    '&:hover': {
                      backgroundColor: theme.palette.action.hover
                    }
                  }}
                  draggable
                  onDragStart={(e) => onDragStart(e, widget)}
                >
                  <CardContent sx={{
                    display: 'flex',
                    alignItems: 'center',
                    padding: '8px !important'
                  }}>
                    <DragIndicatorIcon sx={{ mr: 1, color: theme.palette.text.secondary }} />
                    <Typography variant="body2">{widget.name}</Typography>
                  </CardContent>
                </Card>
              ))}
            </Box>
          </Box>
        )}

        {/* Dashboard grid */}
        <Box
          sx={{
            flex: 1,
            padding: 2,
            overflow: 'auto',
            backgroundColor: theme.palette.background.default
          }}
          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: theme.shadows[2]
                }}>
                  <Box sx={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    padding: 1,
                    borderBottom: `1px solid ${theme.palette.divider}`,
                    backgroundColor: theme.palette.background.paper
                  }}>
                    <Typography variant="subtitle1" sx={{ fontWeight: 'bold' }}>
                      {widget.name}
                    </Typography>
                    <Box>
                      <IconButton
                        size="small"
                        onClick={(e) => {
                          e.stopPropagation();
                          editWidget(widget);
                        }}
                      >
                        <EditIcon fontSize="small" />
                      </IconButton>
                      <IconButton
                        size="small"
                        color="error"
                        onClick={(e) => {
                          e.stopPropagation();
                          removeWidget(widget.i);
                        }}
                        sx={{ ml: 1 }}
                      >
                        <DeleteIcon fontSize="small" />
                      </IconButton>
                    </Box>
                  </Box>
                  <CardContent sx={{
                    flex: 1,
                    padding: 2,
                    overflow: 'hidden',
                    display: 'flex',
                    flexDirection: 'column',
                    height: 'calc(100% - 50px)'
                  }}>
                    {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, pt: 1 }}>
            <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)} startIcon={<CancelIcon />}>
            Cancel
          </Button>
          <Button 
            onClick={saveWidgetChanges} 
            variant="contained" 
            color="primary"
            startIcon={<SaveIcon />}
          >
            Save Changes
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default EditNewDash;