import React, { useState, useMemo, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Grid,
  List,
  ListItem,
  Typography,
  Paper,
  Collapse,
  IconButton,
  alpha,
  useTheme,
} from '@mui/material';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import FormField from '@/shared/components/form/form-field';
import { ModuleFormData } from '@/shared/types/ModuleFormData';
import { moduleFormFields } from '../utils/form-fields-module';
import SvgColor from '@/shared/components/svg-color';
import { StyledTextField } from '@/shared/theme/css';
import PermissionDialog from './PermissionDialog';

const icon = (name: string, width: number = 22) => (
  <SvgColor
    src={`/assets/icons/menu/${name}.svg`}
    sx={{ width, height: width, mr: 1.5 }}
  />
);

const ICONS: any = {
  exploitation: icon('ic_exploitation'),
  configAdmin: icon('ic_config_admin'),
  facturationPaiement: icon('ic_facturation_paiement'),
  flottes: icon('ic_flottes'),
  geolocalisation: icon('ic_geolocalisation'),
  appelOffre: icon('ic_appel_offre'),
  planning: icon('ic_planning'),
  rh: icon('ic_rh'),
  staff: icon('ic_staff'),
};

interface ModuleSelectorProps {
  open: boolean;
  onClose: () => void;
  onSave: (moduleData: ModuleFormData) => void;
  menuItems: Record<string, any>;
  editModule?: ModuleFormData | null;
}

export default function ModuleSelector({
  open,
  onClose,
  onSave,
  menuItems,
  editModule = null,
}: ModuleSelectorProps) {
  const [selectedModule, setSelectedModule] = useState<string>('');
  const [expandedModules, setExpandedModules] = useState<string[]>([]);
  const theme = useTheme();
  const [formData, setFormData] = useState<ModuleFormData>({
    module: '',
    permissions: [],
    date: '',
  });
  const [openPermissionDialog, setOpenPermissionDialog] = useState(false);


  const handleInputChange = (name: string, value: any) => {

    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleModuleSelect = (modulePath: string) => {
    setSelectedModule(modulePath);
    setFormData((prev) => ({
      ...prev,
      module: modulePath,
    }));
  };

  const handleToggleExpand = (moduleKey: string) => {
    setExpandedModules((prev) => {
      if (prev.includes(moduleKey)) {
        return prev.filter((key) => key !== moduleKey);
      } else {
        return [...prev, moduleKey];
      }
    });
  };

  const handleSave = () => {
    if (selectedModule && formData.permissions.length > 0) {
      onSave(formData);
      onClose();
    }
  };

  const handleAddCustomPermission = (permissionValue: string) => {
    if (!permissionValue.trim() || formData.permissions.includes(permissionValue)) {
      setOpenPermissionDialog(false);
      return;
    }
    setFormData((prev) => ({
      ...prev,
      permissions: [...prev.permissions, permissionValue],
    }));

    setOpenPermissionDialog(false);
  };
  useEffect(() => {
    if (editModule) {
      setSelectedModule(editModule.module);
      setFormData({
        module: editModule.module,
        permissions: [...editModule.permissions],
        date: editModule.date || '',
      });
    } else {
      setSelectedModule('');
      setFormData({
        module: '',
        permissions: [],
        date: '',
      });
    }
  }, [editModule, open]);

  const renderModuleItems = () => {
    return Object.keys(menuItems).map((key) => (
      <React.Fragment key={key}>
        <ListItem
          sx={{
            py: 1,
            px: 1.5,
            borderRadius: 1,
            cursor: 'pointer',
            mb: 0.5,
            backgroundColor: selectedModule === menuItems[key].title ? alpha(theme.palette.primary.main, 0.1) : 'transparent',
            color: 'primary.main',
            '&:hover': {
              backgroundColor: alpha(theme.palette.primary.main, 0.1),
              color: 'primary.main',
            },
          }}
          onClick={() => {
            handleModuleSelect(menuItems[key].title);
            if (menuItems[key].children) {
              handleToggleExpand(key);
            }
          }}
        >
          <Box sx={{
            display: 'flex',
            alignItems: 'center',
            width: '100%',
            justifyContent: 'space-between',
          }}>
            <Box sx={{
              display: 'flex',
              alignItems: 'center',
            }}>
              {ICONS[key] && (
                <Box sx={{ mr: 1, display: 'flex', alignItems: 'center' }}>
                  {ICONS[key]}
                </Box>
              )}
              <Typography
                variant="subtitle2"
                sx={{
                  fontWeight: selectedModule === menuItems[key].title ? 600 : 500,
                  fontSize: '0.8rem',
                  color: 'inherit',
                }}
              >
                {menuItems[key].title}
              </Typography>
            </Box>

            {menuItems[key].children && (
              <IconButton
                size="small"
                sx={{
                  p: 0.2,
                  color: 'primary.main',

                }}
                onClick={(e) => {
                  e.stopPropagation();
                  handleToggleExpand(key);
                }}
              >
                {expandedModules.includes(key) ? (
                  <ExpandMoreIcon fontSize="small" />
                ) : (
                  <ChevronRightIcon fontSize="small" />
                )}
              </IconButton>
            )}
          </Box>
        </ListItem>

        {menuItems[key].children && (
          <Collapse in={expandedModules.includes(key)} timeout="auto" unmountOnExit>
            <List component="div" disablePadding sx={{ pl: 3 }}>
              {menuItems[key].children.map((subModule: any, subIndex: number) => (
                <React.Fragment key={`${key}-${subIndex}`}>
                  <ListItem
                    sx={{
                      py: 0.75,
                      px: 1.5,
                      borderRadius: 1,
                      cursor: 'pointer',
                      mb: 0.5,
                      backgroundColor: selectedModule === `${menuItems[key].title} > ${subModule.title}` ? alpha(theme.palette.primary.main, 0.1) : 'transparent',
                      color: 'primary.main',
                      '&:hover': {
                        backgroundColor: alpha(theme.palette.primary.main, 0.1),
                        color: 'primary.main',
                      },
                    }}
                    onClick={() => {
                      handleModuleSelect(`${menuItems[key].title} > ${subModule.title}`);
                      if (subModule.children) {
                        handleToggleExpand(`${key}-${subIndex}`);
                      }
                    }}
                  >
                    <Box
                      sx={{
                        display: 'flex',
                        alignItems: 'center',
                        width: '100%',
                        justifyContent: 'space-between',
                        pl: 0.5,
                        borderLeft: '1px solid #DDD',
                        ml: 0.5,
                      }}
                    >
                      <Box sx={{
                        display: 'flex',
                        alignItems: 'center',
                        color: 'inherit'
                      }}>
                        <Typography
                          variant="body2"
                          sx={{
                            flex: 1,
                            fontWeight: selectedModule === `${menuItems[key].title} > ${subModule.title}` ? 600 : 400,
                            fontSize: '0.85rem',
                            color: 'inherit'
                          }}
                        >
                          {subModule.title}
                        </Typography>
                      </Box>

                      {subModule.children && (
                        <IconButton
                          size="small"
                          sx={{
                            ml: 'auto',
                            p: 0.3,
                            color: 'inherit'
                          }}
                          onClick={(e) => {
                            e.stopPropagation();
                            handleToggleExpand(`${key}-${subIndex}`);
                          }}
                        >
                          {expandedModules.includes(`${key}-${subIndex}`) ? (
                            <ExpandMoreIcon fontSize="small" />
                          ) : (
                            <ChevronRightIcon fontSize="small" />
                          )}
                        </IconButton>
                      )}
                    </Box>
                  </ListItem>

                  {subModule.children && (
                    <Collapse in={expandedModules.includes(`${key}-${subIndex}`)} timeout="auto" unmountOnExit>
                      <List component="div" disablePadding sx={{ pl: 3 }}>
                        {subModule.children.map((childModule: any, childIndex: number) => (
                          <ListItem
                            key={`${key}-${subIndex}-${childIndex}`}
                            sx={{
                              py: 0.75,
                              px: 1.5,
                              borderRadius: 1,
                              cursor: 'pointer',
                              mb: 0.5,
                              backgroundColor: selectedModule === `${menuItems[key].title} > ${subModule.title}` ? alpha(theme.palette.primary.main, 0.1) : 'transparent',
                              color: 'primary.main',
                              '&:hover': {
                                backgroundColor: alpha(theme.palette.primary.main, 0.1),
                                color: 'primary.main',
                              },

                            }}
                            onClick={() => handleModuleSelect(`${menuItems[key].title} > ${subModule.title} > ${childModule.title}`)}
                          >
                            <Box
                              sx={{
                                pl: 0.5,
                                borderLeft: '1px solid #DDD',
                                ml: 0.5,
                              }}
                            >
                              <Typography
                                variant="body2"
                                sx={{
                                  fontSize: '0.8rem',
                                  fontWeight: selectedModule === `${menuItems[key].title} > ${subModule.title} > ${childModule.title}` ? 600 : 400,
                                  color: 'inherit'
                                }}
                              >
                                {childModule.title}
                              </Typography>
                            </Box>
                          </ListItem>
                        ))}
                      </List>
                    </Collapse>
                  )}
                </React.Fragment>
              ))}
            </List>
          </Collapse>
        )}
      </React.Fragment>
    ));
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      maxWidth="md"
      sx={{
        '& .MuiDialog-paper': {
          width: '800px',
          borderRadius: 2,
        }
      }}
    >


      <DialogContent sx={{ py: 3, px: 0 }}>
        <Grid container spacing={2}>
          <Grid item xs={6} sx={{ px: 3, borderRight: '1px solid #eee' }}>
            <Box

              sx={{
                maxHeight: '400px',
                overflowY: 'auto',
                pr: 1,
                '&::-webkit-scrollbar': {
                  width: '6px',
                  backgroundColor: 'transparent',
                },
                '&::-webkit-scrollbar-thumb': {
                  backgroundColor: 'transparent',
                  borderRadius: '4px',
                },
                '&:hover::-webkit-scrollbar-thumb': {
                  backgroundColor: 'rgba(200, 200, 200, 0.6)',
                },
                scrollbarWidth: 'thin',
                scrollbarColor: 'transparent transparent',
                '&:hover': {
                  scrollbarColor: 'rgba(200, 200, 200, 0.6) transparent',
                },
              }}
            >
              <List sx={{ p: 0 }}>
                {renderModuleItems()}
              </List>
            </Box>
          </Grid>

          {/* Formulaire */}
          <Grid item xs={6} sx={{ px: 3 }}>
            {selectedModule && (
              <Box>
                <Paper
                  elevation={0}
                  sx={{
                    mt: 2,
                    p: 2,
                    backgroundColor: 'rgba(130, 112, 196, 0.08)',
                    mb: 3,
                    borderRadius: 2,
                    border: '1px solid rgba(130, 112, 196, 0.2)',
                  }}
                >
                  <Typography
                    variant="subtitle1"
                    sx={{
                      color: 'primary.main',
                      mb: 0.5,
                      fontWeight: 600
                    }}
                  >
                    Module sélectionné
                  </Typography>
                  <Typography variant="body2">{selectedModule}</Typography>
                </Paper>

                <Typography
                  variant="subtitle1"
                  sx={{
                    mb: 2,
                    fontWeight: 600,
                    color: 'text.primary',
                  }}
                >
                  Permissions
                </Typography>

                {moduleFormFields
                  .filter(field => field.name === 'permissions')
                  .map(field => (
                    <FormField
                      key={field.name}
                      field={field}
                      value={formData.permissions}
                      onChange={handleInputChange}
                      isReadOnly={false}
                    />
                  ))}
              </Box>
            )}

            {!selectedModule && (
              <Box sx={{
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                p: 4,
              }}>
                <Typography
                  variant="body1"
                  sx={{
                    color: 'text.secondary',
                    textAlign: 'center',
                  }}
                >
                  Veuillez sélectionner un module dans la liste pour définir ses permissions
                </Typography>
              </Box>
            )}
          </Grid>
        </Grid>
      </DialogContent>

      <DialogActions sx={{ py: 2, px: 3, borderTop: '1px solid #eee' }}>
        <Button
          onClick={onClose}
          sx={{
            color: '#8270C4',
            '&:hover': {
              backgroundColor: 'rgba(130, 112, 196, 0.08)'
            }
          }}
        >
          Annuler
        </Button>
        <Button
          onClick={handleSave}
          disabled={!selectedModule || formData.permissions.length === 0}
          sx={{
            backgroundColor: '#8270C4',
            color: 'white',
            '&:hover': { backgroundColor: '#6951BC' },
            '&.Mui-disabled': {
              backgroundColor: 'rgba(130, 112, 196, 0.3)',
              color: 'white',
            },
            px: 3,
            py: 1,
            borderRadius: 2,
          }}
        >
          {editModule ? 'Enregistrer' : 'Ajouter'}
        </Button>
      </DialogActions>
      <PermissionDialog
        open={openPermissionDialog}
        onClose={() => setOpenPermissionDialog(false)}
        onAdd={handleAddCustomPermission}
      />
    </Dialog>
  );
}