import React, { useCallback, useMemo } from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import Chip from '@mui/material/Chip';
import { t } from '@lingui/macro';
import { useLingui } from '@lingui/react';

interface PermissionFlag {
  bit: number;
  label: string;
}

interface PermissionCategory {
  name: string;
  permissions: PermissionFlag[];
}

interface PermissionCheckboxGridProps {
  value: number;
  onChange: (newBitmask: number) => void;
  disabled?: boolean;
}

const PermissionCheckboxGrid: React.FC<PermissionCheckboxGridProps> = ({
  value,
  onChange,
  disabled = false,
}) => {
  const { i18n } = useLingui();

  const categories: PermissionCategory[] = useMemo(
    () => [
      {
        name: i18n._(t`Systemverwaltung`),
        permissions: [
          { bit: 0x80, label: i18n._(t`Systemzugang`) },
          { bit: 0x1000, label: i18n._(t`Administration`) },
          { bit: 0x1, label: i18n._(t`Benutzerverwaltung`) },
          { bit: 0x2, label: i18n._(t`Konfiguration`) },
          { bit: 0x400, label: i18n._(t`Datenadministration`) },
          { bit: 0x200, label: i18n._(t`Mobile Konfiguration`) },
        ],
      },
      {
        name: i18n._(t`Datenverwaltung`),
        permissions: [
          { bit: 0x8, label: i18n._(t`Daten anzeigen`) },
          { bit: 0x4, label: i18n._(t`Daten bearbeiten`) },
          { bit: 0x20, label: i18n._(t`Daten löschen`) },
        ],
      },
      {
        name: i18n._(t`Anwendungen`),
        permissions: [
          { bit: 0x40, label: i18n._(t`Dashboard`) },
          { bit: 0x100, label: i18n._(t`Kalender`) },
          { bit: 0x10, label: i18n._(t`Tasko App`) },
          { bit: 0x10000, label: i18n._(t`Kontakte`) },
          { bit: 0x40000, label: i18n._(t`Beschwerden`) },
        ],
      },
      {
        name: i18n._(t`Abteilungen`),
        permissions: [
          { bit: 0x2000, label: i18n._(t`Technik`) },
          { bit: 0x4000, label: i18n._(t`Betrieb`) },
          { bit: 0x8000, label: i18n._(t`Verwaltung`) },
          { bit: 0x800, label: i18n._(t`Reinigung`) },
        ],
      },
      {
        name: i18n._(t`Module`),
        permissions: [
          { bit: 0x80000, label: i18n._(t`BHB`) },
          { bit: 0x100000, label: i18n._(t`BHB Lesen`) },
          { bit: 0x200000, label: i18n._(t`LoRaWAN`) },
        ],
      },
      {
        name: i18n._(t`Zeiterfassung`),
        permissions: [
          { bit: 0x400000, label: i18n._(t`Zeiterfassung`) },
          { bit: 0x800000, label: i18n._(t`Zeiterfassung Planer`) },
          { bit: 0x1000000, label: i18n._(t`Zeiterfassung Admin`) },
        ],
      },
    ],
    [i18n],
  );

  const totalPermissions = useMemo(
    () => categories.reduce((sum, cat) => sum + cat.permissions.length, 0),
    [categories],
  );

  const activeCount = useMemo(() => {
    let count = 0;
    for (const cat of categories) {
      for (const perm of cat.permissions) {
        if ((value & perm.bit) !== 0) count++;
      }
    }
    return count;
  }, [value, categories]);

  const handleToggle = useCallback(
    (bit: number) => {
      if ((value & bit) !== 0) {
        onChange(value & ~bit);
      } else {
        onChange(value | bit);
      }
    },
    [value, onChange],
  );

  const handleToggleCategory = useCallback(
    (permissions: PermissionFlag[]) => {
      const allSet = permissions.every((p) => (value & p.bit) !== 0);
      let newValue = value;
      for (const p of permissions) {
        if (allSet) {
          newValue = newValue & ~p.bit;
        } else {
          newValue = newValue | p.bit;
        }
      }
      onChange(newValue);
    },
    [value, onChange],
  );

  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
        <Typography variant="body2" color="text.secondary">
          {i18n._(t`Berechtigungen`)}
        </Typography>
        <Chip
          label={`${activeCount} / ${totalPermissions}`}
          size="small"
          color={activeCount > 0 ? 'primary' : 'default'}
          variant="outlined"
        />
      </Box>

      <Box
        sx={{
          display: 'grid',
          gridTemplateColumns: {
            xs: '1fr',
            sm: '1fr 1fr',
            md: '1fr 1fr 1fr',
          },
          gap: 2,
        }}
      >
        {categories.map((category) => {
          const catActiveCount = category.permissions.filter(
            (p) => (value & p.bit) !== 0,
          ).length;
          const allSelected =
            catActiveCount === category.permissions.length;
          const someSelected = catActiveCount > 0 && !allSelected;

          return (
            <Box
              key={category.name}
              sx={{
                border: '1px solid',
                borderColor: 'divider',
                borderRadius: 1,
                p: 1.5,
              }}
            >
              <FormControlLabel
                control={
                  <Checkbox
                    checked={allSelected}
                    indeterminate={someSelected}
                    onChange={() =>
                      handleToggleCategory(category.permissions)
                    }
                    disabled={disabled}
                    size="small"
                  />
                }
                label={
                  <Typography variant="subtitle2" fontWeight={600}>
                    {category.name}
                    <Typography
                      component="span"
                      variant="caption"
                      color="text.secondary"
                      sx={{ ml: 0.5 }}
                    >
                      ({catActiveCount}/{category.permissions.length})
                    </Typography>
                  </Typography>
                }
                sx={{ ml: 0, mb: 0.5 }}
              />
              <Box
                sx={{ display: 'flex', flexDirection: 'column', pl: 1 }}
              >
                {category.permissions.map((perm) => (
                  <FormControlLabel
                    key={perm.bit}
                    control={
                      <Checkbox
                        checked={(value & perm.bit) !== 0}
                        onChange={() => handleToggle(perm.bit)}
                        disabled={disabled}
                        size="small"
                        sx={{ py: 0.25 }}
                      />
                    }
                    label={
                      <Typography variant="body2">
                        {perm.label}
                      </Typography>
                    }
                    sx={{ ml: 0, minHeight: 28 }}
                  />
                ))}
              </Box>
            </Box>
          );
        })}
      </Box>
    </Box>
  );
};

export default PermissionCheckboxGrid;
