import React, { useState, useMemo, useEffect } from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  Typography,
  Box,
  IconButton,
  Stack,
  Tooltip,
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import { ModuleFormData } from '@/shared/types/ModuleFormData';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { CustomTableSortLabel } from '@/shared/components/table/table-head-custom';
import SvgColor from '@/shared/components/svg-color';
import { ModulesRoleStyledRow, PermissionChip } from '../../styles';
import { CircuitStyledRow } from '@/shared/sections/contract/styles';
import VisibilityOutlinedIcon from '@mui/icons-material/VisibilityOutlined';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
import EditIcon from '@mui/icons-material/Edit';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPenToSquare, faTrash } from '@fortawesome/free-solid-svg-icons';

// Définir les icônes pour chaque type de permission avec un thème violet
const permissionIcons = {
  lire: {
    icon: <VisibilityOutlinedIcon fontSize="small" />,
    color: '#8270C4',
    bgColor: 'rgba(130, 112, 196, 0.1)',
    tooltip: 'Lire',
  },
  ecrire: {
    icon: <AddCircleOutlineIcon fontSize="small" />,
    color: '#6951BC',
    bgColor: 'rgba(105, 81, 188, 0.1)',
    tooltip: 'Écrire',
  },
  modifier: {
    icon: <EditOutlinedIcon fontSize="small" />,
    color: '#5638A9',
    bgColor: 'rgba(86, 56, 169, 0.1)',
    tooltip: 'Modifier',
  },
  supprimer: {
    icon: <DeleteOutlineIcon fontSize="small" />,
    color: '#3E238F',
    bgColor: 'rgba(62, 35, 143, 0.1)',
    tooltip: 'Supprimer',
  },
};
const HEAD_CELLS = [
  { id: 'module', label: 'Module', align: 'center' },
  { id: 'permissions', label: 'Permissions', align: 'center' },
  { id: 'actions', label: 'Actions', align: 'center' },
];
// Composant PermissionIcon
const PermissionIcon = ({ type }: { type: keyof typeof permissionIcons }) => {
  const { icon, color, bgColor, tooltip } = permissionIcons[type] || permissionIcons.lire;

  return (
    <Tooltip title={tooltip} arrow placement="bottom" componentsProps={{
      tooltip: {
        sx: {
          bgcolor: 'primary.main',
          color: 'white',
          '& .MuiTooltip-arrow': {
            color: 'primary.main',
          },
        },
      },
    }}>
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          borderRadius: '50%',
          p: 0.8,
          m: 0.2,
          border: '1px solid',
          borderColor: 'rgba(130, 112, 196, 0.2)',
          transition: 'all 0.2s ease',
          '&:hover': {
            backgroundColor: bgColor,
            color: color,
            border: `1px solid ${color}`,
          },
        }}
      >
        {icon}
      </Box>
    </Tooltip>
  );
};

export default function ModulesRoleList({ modules, menuItems, onEdit, onDelete, isReadOnly = false }: any) {
  useEffect(() => {
    console.log(modules);
  }, [])
  const [order, setOrder] = useState<'asc' | 'desc'>('asc');
  const [orderBy, setOrderBy] = useState<keyof ModuleFormData>('module');

  const handleSort = (property: keyof ModuleFormData) => {
    setOrder((prev) => (orderBy === property && prev === 'asc' ? 'desc' : 'asc'));
    setOrderBy(property);
  };

  const sortedData = useMemo(() =>
    [...modules].sort((a, b) => {
      if (orderBy) {
        const aValue = a[orderBy];
        const bValue = b[orderBy];
        return (aValue < bValue ? -1 : 1) * (order === 'asc' ? 1 : -1);
      }
      return 0;
    }),
    [modules, order, orderBy]
  );

  const displayedColumns = useMemo(() => {
    return HEAD_CELLS.filter(cell => isReadOnly ? cell.id !== 'actions' : true);
  }, [isReadOnly]);

  const renderModuleContent = (moduleTitle: string) => (
    <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <SvgColor
        src="/assets/icons/menu/ic_menu.svg"
        sx={{ width: 15, color: 'primary.main', mr: 1 }}
      />
      {moduleTitle}
    </Box>
  );

  const renderPermissionsContent = (permissions: string[]) => (
    <Stack direction="row" spacing={0.5} justifyContent="center" alignItems="center" flexWrap="wrap">
      {permissions.map((permission, idx) => (
        <PermissionChip key={idx} label={permission} />
      ))}
    </Stack>
  );

  return (
    <Box sx={{ width: '100%', mb: '20px', mt: 4 }}>
      <Typography
        variant="h5"
        sx={{
          my: 2,
          color: 'primary.main',
          fontWeight: (theme) => theme.typography.fontWeightBold,
        }}
      >
        Modules et Permissions
      </Typography>
      <TableContainer>
        <Table sx={{ minWidth: 960, borderRadius: '12px' }}>
          <TableHead sx={{ backgroundColor: 'white' }}>
            <CircuitStyledRow>
              {displayedColumns.map((headCell) => (
                <TableCell
                  key={headCell.id}
                  align={"center"}
                  sx={{ px: { xs: 1, xl: 2 }, py: 1.5 }}
                  sortDirection={orderBy === headCell.id ? order : false}
                >
                  <CustomTableSortLabel
                    active={orderBy === headCell.id}
                    direction={orderBy === headCell.id ? order : 'asc'}
                    orderBy={orderBy}
                    order={order}
                    onSort={() => handleSort(headCell.id as keyof ModuleFormData)}
                  >
                    {headCell.label}
                  </CustomTableSortLabel>
                </TableCell>
              ))}
            </CircuitStyledRow>
          </TableHead>
          <TableBody>
            <ConditionalComponent
              isValid={sortedData.length > 0}
              defaultComponent={
                <ModulesRoleStyledRow>
                  <TableCell
                    colSpan={displayedColumns.length}
                    align="center"
                    sx={{ py: 3 }}
                  >
                    Aucun module associé à ce rôle
                  </TableCell>
                </ModulesRoleStyledRow>
              }
            >
              {sortedData.map((module, index) => (
                <ModulesRoleStyledRow key={index}>
                  <TableCell align="center" sx={{
                    py: 2, px: { xs: 1, xl: 2 },
                    '&:hover': {
                      border: '1px solid primary.main',
                    },
                  }}>
                    {renderModuleContent(module.module)}
                  </TableCell>
                  <TableCell align="center" sx={{ py: 2, px: { xs: 1, xl: 2 } }}>
                    {renderPermissionsContent(module.permissions)}
                  </TableCell>

                  <ConditionalComponent isValid={!isReadOnly}>
                    <TableCell align="center" sx={{ py: 2, px: { xs: 1, xl: 2 } }}>
                      <Stack direction="row" spacing={1} justifyContent="center">
                        <Tooltip
                          title="Modifier le module"
                          arrow
                          componentsProps={{
                            tooltip: {
                              sx: {
                                bgcolor: 'primary.main',
                                color: 'white',
                                '& .MuiTooltip-arrow': {
                                  color: 'primary.main',
                                },
                              },
                            },
                          }}
                        >
                          <IconButton
                            onClick={() => onEdit(index, module)}
                            sx={{
                              '&:hover': {
                                color: 'primary.main',
                              },
                            }}
                          >
                            <FontAwesomeIcon style={{ fontSize: '1rem' }} icon={faPenToSquare} size="sm" />
                          </IconButton>
                        </Tooltip>
                        <Tooltip
                          title="Supprimer le module"
                          arrow
                          componentsProps={{
                            tooltip: {
                              sx: {
                                bgcolor: 'primary.main',
                                color: 'white',
                                '& .MuiTooltip-arrow': {
                                  color: 'primary.main',
                                },
                              },
                            },
                          }}
                        >
                          <IconButton
                            sx={{
                              '&:hover': {
                                color: 'primary.main',
                              },
                            }}
                            onClick={() => onDelete(index)}
                            size="medium"
                          >
                            <FontAwesomeIcon
                              icon={faTrash}
                              size="sm"
                              style={{ fontSize: '1rem' }}
                            />
                          </IconButton>
                        </Tooltip>
                      </Stack>
                    </TableCell>
                  </ConditionalComponent>
                </ModulesRoleStyledRow>
              ))}
            </ConditionalComponent>
          </TableBody>
        </Table>
      </TableContainer>
    </Box>
  );
}