import React, { useState } from 'react';
import TableCell from '@mui/material/TableCell';
import { IRole } from '@/shared/types/role';
import TableActionColumn from '@/shared/components/table/table-action-column';
import SvgColor from '@/shared/components/svg-color';
import {
  TableRow,
  Stack,
  Box,
  IconButton,
  Checkbox,
  Collapse,
  Typography,
  Divider,
  Grid
} from '@mui/material';
import { TableColumn } from '@/shared/types/common';
import { formatDate } from '@/utils/format-time';
import StatusMenu from '@/shared/components/table/StatusMenu';
import { ROLE_STATUS } from '@/shared/_mock/_roles';
import { RoleStyledRow, StatusChip, PermissionChip } from '../../styles';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import { RoleStatus } from '@/shared/api/stores/roleStore';

type Props = {
  handleEditRole: (role: IRole) => void;
  handleDetailsRole: (role: IRole) => void;
  handleArchiveRole: (role: IRole) => void;
  selected: boolean;
  row: IRole;
  onSelectRow: VoidFunction;
  columns: TableColumn[];
  onStatusChange: (row: IRole, newStatus: RoleStatus) => void;
};

const TOOLTIP_TITLES = {
  edit: 'Modifier rôle',
  archive: 'Archiver rôle',
  active: 'Rôle actif',
  inactive: 'Rôle inactif',
};

export default function RoleTableRow({
  row,
  handleEditRole,
  handleDetailsRole,
  handleArchiveRole,
  selected,
  onSelectRow,
  columns,
  onStatusChange
}: Props) {
  const [expanded, setExpanded] = useState(false);

  const handleExpandClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    setExpanded(!expanded);
  };

  const renderCellContent = (columnId: string, value: any) => {
    switch (columnId) {
      case 'createdAt':
        return formatDate(value);
      case 'modules':
        return (
          <Stack direction="row" spacing={1} alignItems="center" justifyContent="center">
            <Box component="span" sx={{ fontWeight: 'medium' }}>
              {Array.isArray(row.modules) ? row.modules.length : 0} module(s)
            </Box>
            <IconButton
              size="small"
              onClick={handleExpandClick}
              sx={{
                color: expanded ? 'primary.main' : 'text.secondary',
                transition: 'transform 0.3s',
                transform: expanded ? 'rotate(180deg)' : 'rotate(0deg)',
              }}
            >
              <KeyboardArrowDownIcon />
            </IconButton>
          </Stack>
        );
      case 'status':
        return (
          <StatusMenu
            value={row.status}
            options={ROLE_STATUS}
            onChange={(newStatus) => onStatusChange(row, newStatus as RoleStatus)}
            chipComponent={StatusChip}
            sx={{
              width: '120px',
              '& .MuiSelect-select': {
                py: 0,
              },
            }}
          />
        );
      default:
        return value;
    }
  };

  const renderModulesExpanded = () => {
    if (!row.modules || row.modules.length === 0) {
      return (
        <Typography variant="body2" sx={{ py: 2, color: 'text.secondary', textAlign: 'center', backgroundColor: 'background.paper' }}>
          Aucun module associé à ce rôle
        </Typography>
      );
    }

    return (
      <Box sx={{ backgroundColor: 'background.paper', px: 2, borderRadius: '12px', py: 2 }}>
        {/* En-tête des colonnes */}
        <Grid container sx={{ mb: 1.5 }}>
          <Grid item xs={12} md={4}>
            <Typography variant="subtitle2" sx={{ color: 'primary.main', fontWeight: 600 }}>
              Module
            </Typography>
          </Grid>
          <Grid item xs={12} md={8}>
            <Typography variant="subtitle2" sx={{ color: 'primary.main', fontWeight: 600 }}>
              Permissions
            </Typography>
          </Grid>
        </Grid>

        <Divider sx={{ mb: 2, borderColor: 'rgba(130, 112, 196, 0.2)' }} />

        {row.modules.map((module, index) => (
          <Box key={`${module.module}-${index}`} sx={{ py: 1 }}>
            <Grid container>
              <Grid item xs={12} md={4}>
                <Typography variant="body2" sx={{ color: 'text.secondary', fontWeight: 500 }}>
                  {module.module}
                </Typography>
              </Grid>
              <Grid item xs={12} md={8}>
                <Stack direction="row" flexWrap="wrap" gap={0.75}>
                  {module.permissions.map((permission, idx) => (
                    <PermissionChip
                      key={`${permission}-${idx}`}
                      label={permission}
                      size="small"
                      sx={{
                        height: '24px',
                        fontSize: '0.75rem',
                        borderRadius: '12px',
                        bgcolor: 'rgba(130, 112, 196, 0.08)',
                        color: 'primary.main',
                        '& .MuiChip-label': {
                          px: 1.5,
                        }
                      }}
                    />
                  ))}
                </Stack>
              </Grid>
            </Grid>
            {index < (row.modules?.length ?? 0) - 1 && (
              <Divider sx={{ my: 1, borderStyle: 'dashed', borderColor: 'rgba(130, 112, 196, 0.2)' }} />
            )}
          </Box>
        ))}
      </Box>
    );
  };
  return (
    <>
      <RoleStyledRow hover selected={selected} style={{ cursor: 'pointer' }}>
        <TableCell
          style={{
            position: 'relative',
          }}
          sx={{
            width: '40px',
            verticalAlign: 'middle',
          }}
          padding="checkbox"
        >
          <SvgColor
            src="/assets/icons/ic_border.svg"
            sx={{
              position: 'absolute',
              top: 0,
              left: -4,
              height: '100%',
              color: row.status === RoleStatus.ENABLED ? 'rgb(34, 154, 22)' : 'rgb(183, 33, 54)',
            }}
          />
          <Checkbox
            size="small"
            checked={selected}
            onClick={onSelectRow}
            sx={{
              color: '#8270C4',
              '&.Mui-checked': {
                color: '#6951BC',
              },
            }}
          />
        </TableCell>
        {columns
          .filter((column) => column.id !== '')
          .map((column: any) => (
            <TableCell
              onDoubleClick={() => handleDetailsRole(row)}
              key={column.id}
              align={column.align}
              sx={{
                width: column.width || 'auto',
                whiteSpace: 'nowrap',
                py: column.id === 'status' ? 0 : 2,
                px: 2,
                verticalAlign: 'middle',
              }}
              padding="none"
            >
              {renderCellContent(column.id, row[column.id as keyof IRole])}
            </TableCell>
          ))}
        <TableCell align="center" sx={{ px: 1, whiteSpace: 'nowrap', py: 0 }}  >
          <TableActionColumn
            handleEdit={() => handleEditRole(row)}
            onToggle={(checked) => onStatusChange(row, checked ? RoleStatus.ENABLED : RoleStatus.DISABLED)}
            isActive={row.status === RoleStatus.ENABLED}
            tooltipTitles={TOOLTIP_TITLES}
          />
        </TableCell>
      </RoleStyledRow>
      <TableRow>
        <TableCell colSpan={columns.length + 2} sx={{ p: 0, border: 0 }}>
          <Collapse in={expanded} timeout="auto" unmountOnExit>
            <Box
              sx={{
                py: 2,
                px: 4,
                borderBottom: '1px solid rgba(130, 112, 196, 0.1)',
              }}
            >
              {renderModulesExpanded()}
            </Box>
          </Collapse>
        </TableCell>
      </TableRow>
    </>
  );
}