"use client"

import React, { useState, useEffect } from "react"
import {
  Dialog,
  DialogContent,
  DialogActions,
  Button,
  Box,
  Grid,
  List,
  ListItem,
  Typography,
  Paper,
  Collapse,
  IconButton,
  alpha,
  useTheme,
  Checkbox,
} from "@mui/material"
import ExpandMoreIcon from "@mui/icons-material/ExpandMore"
import ChevronRightIcon from "@mui/icons-material/ChevronRight"
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"),
}

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 [selectedModules, setSelectedModules] = useState<Set<string>>(new Set())
  const [expandedModules, setExpandedModules] = useState<string[]>([])
  const theme = useTheme()
  const [formData, setFormData] = useState<ModuleFormData[]>([])
  const [openPermissionDialog, setOpenPermissionDialog] = useState(false)

  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 handleInputChange = (name: string, value: any) => {
    // This can be updated later for handling permissions per module
  }

  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 handleSave = () => {
    if (selectedModules.size > 0) {
      const moduleDataArray: ModuleFormData[] = Array.from(selectedModules).map((module) => ({
        module,
        permissions: ["Lire"], // Default permission
        date: "",
      }))
      if (selectedModules.size > 1) {
        for (let index = 0; index < moduleDataArray.length; index++) {
          onSave(moduleDataArray[index])
        }
      }

      if (selectedModules.size === 1) {
        onSave(moduleDataArray[0])
      }
      onClose()
    }
  }

  const handleAddCustomPermission = (permissionValue: string) => {
    // This can be updated later for handling permissions
    setOpenPermissionDialog(false)
  }

  useEffect(() => {
    if (editModule) {
      setSelectedModules(new Set([editModule.module]))
    } else {
      setSelectedModules(new Set())
    }
  }, [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>
      )
    })
  }

  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={{ 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>
      </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={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,
          }}
        >
          {editModule ? "Enregistrer" : "Ajouter"} ({selectedModules.size})
        </Button>
      </DialogActions>
      <PermissionDialog
        open={openPermissionDialog}
        onClose={() => setOpenPermissionDialog(false)}
        onAdd={handleAddCustomPermission}
      />
    </Dialog>
  )
}
