"use client"

import React, { useState, useEffect } from "react"
import {
  Dialog,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Grid,
  List,
  ListItem,
  Typography,
  Paper,
  Collapse,
  IconButton,
  alpha,
  useTheme,
  Checkbox,
  Stepper,
  Step,
  StepLabel,
  FormGroup,
  FormControlLabel,
  Divider,
  Chip,
} from "@mui/material"
import ExpandMoreIcon from "@mui/icons-material/ExpandMore"
import ChevronRightIcon from "@mui/icons-material/ChevronRight"
import ArrowBackIcon from "@mui/icons-material/ArrowBack"
import type { ModuleFormData } from "@/shared/types/ModuleFormData"
import SvgColor from "@/shared/components/svg-color"
import PermissionDialog from "./PermissionDialog"

const icon = (name: string, width = 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"),
}

const DEFAULT_PERMISSIONS = ["Lire", "Écrire", "Modifier", "Supprimer"]

interface ModuleWithPermissions {
  module: string
  permissions: string[]
  customPermissions: string[]
}

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

export default function ModulePermissionSelector({
  open,
  onClose,
  onSave,
  menuItems,
  editModule = null,
}: ModulePermissionSelectorProps) {
  const [activeStep, setActiveStep] = useState(0)
  const [selectedModules, setSelectedModules] = useState<Set<string>>(new Set())
  const [expandedModules, setExpandedModules] = useState<string[]>([])
  const [modulePermissions, setModulePermissions] = useState<Map<string, ModuleWithPermissions>>(new Map())
  const [openPermissionDialog, setOpenPermissionDialog] = useState(false)
  const [currentModuleForPermission, setCurrentModuleForPermission] = useState<string>("")
  const theme = useTheme()

  const steps = ["Sélection des modules", "Configuration des permissions"]

  const getAllChildModules = (moduleKey: string, moduleData: any): string[] => {
    const children: string[] = []

    if (moduleData.children) {
      moduleData.children.forEach((child: any, index: number) => {
        const childPath = `${moduleData.title} > ${child.title}`
        children.push(childPath)

        if (child.children) {
          child.children.forEach((grandChild: any) => {
            children.push(`${childPath} > ${grandChild.title}`)
          })
        }
      })
    }

    return children
  }

  const areAllChildrenSelected = (moduleKey: string, moduleData: any): boolean => {
    const childModules = getAllChildModules(moduleKey, moduleData)
    return childModules.length > 0 && childModules.every((child) => selectedModules.has(child))
  }

  const areSomeChildrenSelected = (moduleKey: string, moduleData: any): boolean => {
    const childModules = getAllChildModules(moduleKey, moduleData)
    return childModules.some((child) => selectedModules.has(child))
  }

  const handleModuleSelect = (modulePath: string, moduleKey?: string, moduleData?: any) => {
    setSelectedModules((prev) => {
      const newSelected = new Set(prev)

      if (newSelected.has(modulePath)) {
        // Unselecting - remove this module and all its children
        newSelected.delete(modulePath)
        if (moduleKey && moduleData) {
          const childModules = getAllChildModules(moduleKey, moduleData)
          childModules.forEach((child) => newSelected.delete(child))
        }
      } else {
        // Selecting - add this module and all its children
        newSelected.add(modulePath)
        if (moduleKey && moduleData) {
          const childModules = getAllChildModules(moduleKey, moduleData)
          childModules.forEach((child) => newSelected.add(child))
        }
      }

      return newSelected
    })
  }

  const handleSelectAll = () => {
    const allModules = new Set<string>()

    Object.keys(menuItems).forEach((key) => {
      const moduleData = menuItems[key]
      allModules.add(moduleData.title)

      if (moduleData.children) {
        moduleData.children.forEach((child: any) => {
          allModules.add(`${moduleData.title} > ${child.title}`)

          if (child.children) {
            child.children.forEach((grandChild: any) => {
              allModules.add(`${moduleData.title} > ${child.title} > ${grandChild.title}`)
            })
          }
        })
      }
    })

    setSelectedModules(allModules)
  }

  const handleClearAll = () => {
    setSelectedModules(new Set())
  }

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

  const handleNext = () => {
    if (activeStep === 0 && selectedModules.size > 0) {
      const newModulePermissions = new Map<string, ModuleWithPermissions>()

      selectedModules.forEach((module) => {
        newModulePermissions.set(module, {
          module,
          permissions: ["Lire"], // Default permission
          customPermissions: [],
        })
      })

      setModulePermissions(newModulePermissions)
      setActiveStep(1)
    }
  }

  const handleBack = () => {
    setActiveStep(0)
  }

  const handlePermissionChange = (moduleName: string, permission: string, checked: boolean) => {
    setModulePermissions((prev) => {
      const newMap = new Map(prev)
      const moduleData = newMap.get(moduleName)

      if (moduleData) {
        const updatedPermissions = checked
          ? [...moduleData.permissions, permission]
          : moduleData.permissions.filter((p) => p !== permission)

        newMap.set(moduleName, {
          ...moduleData,
          permissions: updatedPermissions,
        })
      }

      return newMap
    })
  }

  const handleAddCustomPermission = (moduleName: string, permission: string) => {
    setModulePermissions((prev) => {
      const newMap = new Map(prev)
      const moduleData = newMap.get(moduleName)

      if (moduleData && !moduleData.customPermissions.includes(permission)) {
        newMap.set(moduleName, {
          ...moduleData,
          customPermissions: [...moduleData.customPermissions, permission],
          permissions: [...moduleData.permissions, permission],
        })
      }

      return newMap
    })
    setOpenPermissionDialog(false)
    setCurrentModuleForPermission("")
  }

  const handleRemoveCustomPermission = (moduleName: string, permission: string) => {
    setModulePermissions((prev) => {
      const newMap = new Map(prev)
      const moduleData = newMap.get(moduleName)

      if (moduleData) {
        newMap.set(moduleName, {
          ...moduleData,
          customPermissions: moduleData.customPermissions.filter((p) => p !== permission),
          permissions: moduleData.permissions.filter((p) => p !== permission),
        })
      }

      return newMap
    })
  }

  const handleSave = () => {
    const moduleDataArray: ModuleFormData[] = Array.from(modulePermissions.values()).map((moduleData) => ({
      module: moduleData.module,
      permissions: moduleData.permissions,
      date: new Date().toISOString(),
    }))

    onSave(moduleDataArray)
    onClose()
  }

  const handleClose = () => {
    setActiveStep(0)
    setSelectedModules(new Set())
    setModulePermissions(new Map())
    onClose()
  }

  useEffect(() => {
    if (editModule) {
      setSelectedModules(new Set([editModule.module]))
      const modulePermissionMap = new Map<string, ModuleWithPermissions>()
      modulePermissionMap.set(editModule.module, {
        module: editModule.module,
        permissions: editModule.permissions || ["Lire"],
        customPermissions: [],
      })
      setModulePermissions(modulePermissionMap)
      setActiveStep(1)
    } else {
      setActiveStep(0)
      setSelectedModules(new Set())
      setModulePermissions(new Map())
    }
  }, [editModule, open])

  const renderModuleItems = () => {
    return Object.keys(menuItems).map((key) => {
      const moduleData = menuItems[key]
      const isSelected = selectedModules.has(moduleData.title)
      const allChildrenSelected = areAllChildrenSelected(key, moduleData)
      const someChildrenSelected = areSomeChildrenSelected(key, moduleData)

      return (
        <React.Fragment key={key}>
          <ListItem
            sx={{
              py: 1,
              px: 1.5,
              borderRadius: 1,
              cursor: "pointer",
              mb: 0.5,
              backgroundColor: isSelected ? alpha(theme.palette.primary.main, 0.1) : "transparent",
              color: "primary.main",
              "&:hover": {
                backgroundColor: alpha(theme.palette.primary.main, 0.1),
                color: "primary.main",
              },
            }}
          >
            <Box
              sx={{
                display: "flex",
                alignItems: "center",
                width: "100%",
                justifyContent: "space-between",
              }}
            >
              <Box
                sx={{
                  display: "flex",
                  alignItems: "center",
                  flex: 1,
                }}
              >
                <Checkbox
                  checked={isSelected || allChildrenSelected}
                  indeterminate={!isSelected && !allChildrenSelected && someChildrenSelected}
                  onChange={() => handleModuleSelect(moduleData.title, key, moduleData)}
                  size="small"
                  sx={{ mr: 1, p: 0.5 }}
                />

                {ICONS[key] && <Box sx={{ mr: 1, display: "flex", alignItems: "center" }}>{ICONS[key]}</Box>}
                <Typography
                  variant="subtitle2"
                  sx={{
                    fontWeight: isSelected ? 600 : 500,
                    fontSize: "0.8rem",
                    color: "inherit",
                  }}
                  onClick={() => handleModuleSelect(moduleData.title, key, moduleData)}
                >
                  {moduleData.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) => {
                  const subModulePath = `${menuItems[key].title} > ${subModule.title}`
                  const isSubSelected = selectedModules.has(subModulePath)

                  return (
                    <React.Fragment key={`${key}-${subIndex}`}>
                      <ListItem
                        sx={{
                          py: 0.75,
                          px: 1.5,
                          borderRadius: 1,
                          cursor: "pointer",
                          mb: 0.5,
                          backgroundColor: isSubSelected ? alpha(theme.palette.primary.main, 0.1) : "transparent",
                          color: "primary.main",
                          "&:hover": {
                            backgroundColor: alpha(theme.palette.primary.main, 0.1),
                            color: "primary.main",
                          },
                        }}
                      >
                        <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",
                              flex: 1,
                            }}
                          >
                            <Checkbox
                              checked={isSubSelected}
                              onChange={() => handleModuleSelect(subModulePath)}
                              size="small"
                              sx={{ mr: 1, p: 0.5 }}
                            />

                            <Typography
                              variant="body2"
                              sx={{
                                flex: 1,
                                fontWeight: isSubSelected ? 600 : 400,
                                fontSize: "0.85rem",
                                color: "inherit",
                              }}
                              onClick={() => handleModuleSelect(subModulePath)}
                            >
                              {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) => {
                              const childModulePath = `${menuItems[key].title} > ${subModule.title} > ${childModule.title}`
                              const isChildSelected = selectedModules.has(childModulePath)

                              return (
                                <ListItem
                                  key={`${key}-${subIndex}-${childIndex}`}
                                  sx={{
                                    py: 0.75,
                                    px: 1.5,
                                    borderRadius: 1,
                                    cursor: "pointer",
                                    mb: 0.5,
                                    backgroundColor: isChildSelected
                                      ? alpha(theme.palette.primary.main, 0.1)
                                      : "transparent",
                                    color: "primary.main",
                                    "&:hover": {
                                      backgroundColor: alpha(theme.palette.primary.main, 0.1),
                                      color: "primary.main",
                                    },
                                  }}
                                >
                                  <Box
                                    sx={{
                                      pl: 0.5,
                                      borderLeft: "1px solid #DDD",
                                      ml: 0.5,
                                      display: "flex",
                                      alignItems: "center",
                                      width: "100%",
                                    }}
                                  >
                                    <Checkbox
                                      checked={isChildSelected}
                                      onChange={() => handleModuleSelect(childModulePath)}
                                      size="small"
                                      sx={{ mr: 1, p: 0.5 }}
                                    />

                                    <Typography
                                      variant="body2"
                                      sx={{
                                        fontSize: "0.8rem",
                                        fontWeight: isChildSelected ? 600 : 400,
                                        color: "inherit",
                                      }}
                                      onClick={() => handleModuleSelect(childModulePath)}
                                    >
                                      {childModule.title}
                                    </Typography>
                                  </Box>
                                </ListItem>
                              )
                            })}
                          </List>
                        </Collapse>
                      )}
                    </React.Fragment>
                  )
                })}
              </List>
            </Collapse>
          )}
        </React.Fragment>
      )
    })
  }

  const renderPermissionsStep = () => {
    return (
      <Box sx={{ maxHeight: "500px", overflowY: "auto", pr: 1 }}>
        {Array.from(modulePermissions.entries()).map(([moduleName, moduleData], index) => (
          <Paper
            key={moduleName}
            elevation={0}
            sx={{
              mb: 3,
              p: 3,
              backgroundColor: "rgba(130, 112, 196, 0.05)",
              border: "1px solid rgba(130, 112, 196, 0.2)",
              borderRadius: 2,
            }}
          >
            <Typography
              variant="h6"
              sx={{
                color: "primary.main",
                mb: 2,
                fontWeight: 600,
                fontSize: "1rem",
              }}
            >
              {moduleName}
            </Typography>

            <Typography
              variant="subtitle2"
              sx={{
                mb: 2,
                color: "text.secondary",
                fontWeight: 500,
              }}
            >
              Permissions disponibles:
            </Typography>

            <FormGroup>
              <Grid container spacing={1}>
                {DEFAULT_PERMISSIONS.map((permission) => (
                  <Grid item xs={6} sm={4} key={permission}>
                    <FormControlLabel
                      control={
                        <Checkbox
                          checked={moduleData.permissions.includes(permission)}
                          onChange={(e) => handlePermissionChange(moduleName, permission, e.target.checked)}
                          size="small"
                        />
                      }
                      label={
                        <Typography variant="body2" sx={{ fontSize: "0.85rem" }}>
                          {permission}
                        </Typography>
                      }
                    />
                  </Grid>
                ))}
              </Grid>
            </FormGroup>

            {moduleData.customPermissions.length > 0 && (
              <Box sx={{ mt: 2 }}>
                <Typography
                  variant="subtitle2"
                  sx={{
                    mb: 1,
                    color: "text.secondary",
                    fontWeight: 500,
                  }}
                >
                  Permissions personnalisées:
                </Typography>
                <Box sx={{ display: "flex", flexWrap: "wrap", gap: 1 }}>
                  {moduleData.customPermissions.map((permission) => (
                    <Chip
                      key={permission}
                      label={permission}
                      size="small"
                      onDelete={() => handleRemoveCustomPermission(moduleName, permission)}
                      sx={{
                        backgroundColor: "rgba(130, 112, 196, 0.1)",
                        color: "primary.main",
                      }}
                    />
                  ))}
                </Box>
              </Box>
            )}

            <Box sx={{ mt: 2 }}>
              <Button
                size="small"
                onClick={() => {
                  setCurrentModuleForPermission(moduleName)
                  setOpenPermissionDialog(true)
                }}
                sx={{
                  color: "#8270C4",
                  fontSize: "0.75rem",
                  "&:hover": {
                    backgroundColor: "rgba(130, 112, 196, 0.08)",
                  },
                }}
              >
                + Ajouter permission personnalisée
              </Button>
            </Box>

            {index < modulePermissions.size - 1 && <Divider sx={{ mt: 3 }} />}
          </Paper>
        ))}
      </Box>
    )
  }

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      maxWidth="lg"
      sx={{
        "& .MuiDialog-paper": {
          width: "900px",
          borderRadius: 2,
        },
      }}
    >
      <DialogContent sx={{ py: 3, px: 0 }}>
        <Box sx={{ px: 3, mb: 3 }}>
          <Stepper activeStep={activeStep} alternativeLabel>
            {steps.map((label) => (
              <Step key={label}>
                <StepLabel>{label}</StepLabel>
              </Step>
            ))}
          </Stepper>
        </Box>

        {activeStep === 0 && (
          <Grid container spacing={2}>
            <Grid item xs={6} sx={{ px: 3, borderRight: "1px solid #eee" }}>
              <Box sx={{ mb: 2, display: "flex", gap: 1 }}>
                <Button
                  size="small"
                  onClick={handleSelectAll}
                  sx={{
                    color: "#8270C4",
                    fontSize: "0.75rem",
                    "&:hover": {
                      backgroundColor: "rgba(130, 112, 196, 0.08)",
                    },
                  }}
                >
                  Sélectionner tout
                </Button>
                <Button
                  size="small"
                  onClick={handleClearAll}
                  sx={{
                    color: "#8270C4",
                    fontSize: "0.75rem",
                    "&:hover": {
                      backgroundColor: "rgba(130, 112, 196, 0.08)",
                    },
                  }}
                >
                  Tout désélectionner
                </Button>
              </Box>

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

            <Grid item xs={6} sx={{ px: 3 }}>
              {selectedModules.size > 0 && (
                <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,
                      }}
                    >
                      Modules sélectionnés ({selectedModules.size})
                    </Typography>
                    <Box sx={{ maxHeight: "150px", overflowY: "auto" }}>
                      {Array.from(selectedModules).map((module, index) => (
                        <Typography key={index} variant="body2" sx={{ mb: 0.5 }}>
                          • {module}
                        </Typography>
                      ))}
                    </Box>
                  </Paper>
                </Box>
              )}

              {selectedModules.size === 0 && (
                <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 ou plusieurs modules dans la liste
                  </Typography>
                </Box>
              )}
            </Grid>
          </Grid>
        )}

        {activeStep === 1 && (
          <Box sx={{ px: 3 }}>
            <Typography
              variant="h6"
              sx={{
                color: "primary.main",
                mb: 3,
                fontWeight: 600,
              }}
            >
              Configuration des permissions pour les modules sélectionnés
            </Typography>
            {renderPermissionsStep()}
          </Box>
        )}
      </DialogContent>

      <DialogActions sx={{ py: 2, px: 3, borderTop: "1px solid #eee" }}>
        {activeStep === 1 && (
          <Button
            onClick={handleBack}
            startIcon={<ArrowBackIcon />}
            sx={{
              color: "#8270C4",
              "&:hover": {
                backgroundColor: "rgba(130, 112, 196, 0.08)",
              },
            }}
          >
            Retour
          </Button>
        )}

        <Box sx={{ flex: 1 }} />

        <Button
          onClick={handleClose}
          sx={{
            color: "#8270C4",
            "&:hover": {
              backgroundColor: "rgba(130, 112, 196, 0.08)",
            },
          }}
        >
          Annuler
        </Button>

        {activeStep === 0 && (
          <Button
            onClick={handleNext}
            disabled={selectedModules.size === 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,
            }}
          >
            Suivant ({selectedModules.size})
          </Button>
        )}

        {activeStep === 1 && (
          <Button
            onClick={handleSave}
            sx={{
              backgroundColor: "#8270C4",
              color: "white",
              "&:hover": { backgroundColor: "#6951BC" },
              px: 3,
              py: 1,
              borderRadius: 2,
            }}
          >
            {editModule ? "Enregistrer" : "Ajouter"} ({modulePermissions.size})
          </Button>
        )}
      </DialogActions>

      <PermissionDialog
        open={openPermissionDialog}
        onClose={() => {
          setOpenPermissionDialog(false)
          setCurrentModuleForPermission("")
        }}
        onAdd={(permission : string) => handleAddCustomPermission(currentModuleForPermission, permission)}
      />
    </Dialog>
  )
}
