import React from 'react';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import Typography from '@mui/material/Typography';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Checkbox from '@mui/material/Checkbox';
import Paper from '@mui/material/Paper';
import { Trans, t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { MobileDeviceData } from '../../types';

interface FeatureMatrixTabProps {
  deviceData: MobileDeviceData;
  onDataChange: (updates: Partial<MobileDeviceData>) => void;
}

const FeatureMatrixTab: React.FC<FeatureMatrixTabProps> = ({
  deviceData,
  onDataChange,
}) => {
  const { i18n } = useLingui();

  const iconKeys = [
    { key: 'mcl_inf', pngKey: 'mcl_infpng' },
    { key: 'mcl_bst', pngKey: 'mcl_bstpng' },
    { key: 'mcl_str', pngKey: 'mcl_strpng' },
    { key: 'mcl_all', pngKey: 'mcl_allpng' },
    { key: 'mcl_i05', pngKey: 'mcl_i05png' },
    { key: 'mcl_i06', pngKey: 'mcl_i06png' },
  ];

  const features = [
    { key: 'BST', label: i18n._(t`Bestellung`) },
    { key: 'STR', label: i18n._(t`Störung`) },
    { key: 'INF', label: i18n._(t`Info`) },
    { key: 'INS', label: i18n._(t`Info Störung`) },
    { key: 'INB', label: i18n._(t`Info Bestellung`) },
    { key: 'BEM', label: i18n._(t`Bemerkung`) },
    { key: 'DYA', label: i18n._(t`To-Do`) },
    { key: 'DYN', label: i18n._(t`Aufgabe`) },
    { key: 'GRP', label: i18n._(t`Gruppierung`) },
    { key: 'MLD', label: i18n._(t`Meldung`) },
    { key: 'WTG', label: i18n._(t`Wartungen`) },
    { key: 'MWT', label: i18n._(t`Messwerte`) },
    { key: 'VBG', label: i18n._(t`Verbrauswerte`) },
    { key: 'DOC', label: i18n._(t`Documente`) },
  ];

  const isFeatureEnabled = (iconKey: string, featureKey: string): boolean => {
    const iconValue = deviceData.parameters?.[iconKey as keyof typeof deviceData.parameters];
    return typeof iconValue === 'string' && iconValue.includes(featureKey);
  };

  const handleFeatureToggle = (iconKey: string, featureKey: string, checked: boolean) => {
    if (!deviceData.parameters) return;

    const currentValue = deviceData.parameters[iconKey as keyof typeof deviceData.parameters] || '';
    const currentFeatures = currentValue ? currentValue.split('|').filter(f => f) : [];
    let newFeatures: string[];

    if (checked) {
      if (!currentFeatures.includes(featureKey)) {
        newFeatures = [...currentFeatures, featureKey];
      } else {
        newFeatures = currentFeatures;
      }
    } else {
      newFeatures = currentFeatures.filter(f => f !== featureKey);
    }

    const newValue = newFeatures.join('|');

    onDataChange({
      parameters: {
        ...deviceData.parameters,
        [iconKey]: newValue,
      },
    });
  };

  const getIconSrc = (pngKey: string): string => {
    const iconFile = deviceData.parameters?.[pngKey as keyof typeof deviceData.parameters];
    return iconFile ? `/imgtasko/icons/${iconFile}` : '';
  };

  return (
    <Box>
      <TableContainer
            component={Paper}
            elevation={0}
            sx={{
              border: '1px solid #e0e0e0',
              borderRadius: '8px',
              overflowX: 'auto',
            }}
          >
            <Table sx={{ minWidth: 560 }} size="small">
              <TableHead>
                <TableRow sx={{ backgroundColor: '#f8f9fa' }}>
                  <TableCell sx={{ fontWeight: 600, minWidth: '140px', position: 'sticky', left: 0, backgroundColor: '#f8f9fa', zIndex: 1, py: 0.7, px: 1.5, fontSize: '0.85rem' }}>
                    <Trans>Funktion</Trans>
                  </TableCell>
                  {iconKeys.map((icon) => {
                    const iconSrc = getIconSrc(icon.pngKey);
                    return (
                      <TableCell
                        key={icon.key}
                        align="center"
                        sx={{
                          fontWeight: 600,
                          minWidth: '70px',
                          borderLeft: '1px dotted #dee2e6',
                          py: 0.5,
                          px: 0.8,
                        }}
                      >
                        {iconSrc && (
                          <Box
                            component="img"
                            src={iconSrc}
                            alt={icon.key}
                            sx={{
                              width: 28,
                              height: 28,
                              objectFit: 'contain',
                              mb: 0.5,
                            }}
                          />
                        )}
                      </TableCell>
                    );
                  })}
                </TableRow>
              </TableHead>
              <TableBody>
                {features.map((feature, featureIndex) => (
                  <TableRow
                    key={feature.key}
                    sx={{
                      '&:hover': { backgroundColor: '#f8f9fa' },
                      transition: 'background-color 0.2s ease',
                    }}
                  >
                    <TableCell
                      sx={{
                        fontWeight: 500,
                        position: 'sticky',
                        left: 0,
                        backgroundColor: 'white',
                        zIndex: 1,
                        borderBottom: featureIndex !== features.length - 1 ? '1px dotted #dee2e6' : undefined,
                        py: 0.5,
                        px: 1.5,
                        fontSize: '0.85rem',
                      }}
                    >
                      {feature.label}
                    </TableCell>
                    {iconKeys.map((icon) => (
                      <TableCell
                        key={`${icon.key}_${feature.key}`}
                        align="center"
                        sx={{
                          borderLeft: '1px dotted #dee2e6',
                          borderBottom: featureIndex !== features.length - 1 ? '1px dotted #dee2e6' : undefined,
                          py: 0.3,
                          px: 0.5,
                        }}
                      >
                        <Checkbox
                          size="small"
                          checked={isFeatureEnabled(icon.key, feature.key)}
                          onChange={(e) => handleFeatureToggle(icon.key, feature.key, e.target.checked)}
                          sx={{
                            color: '#6c757d',
                            padding: '4px',
                            '&.Mui-checked': {
                              color: '#02AEE4',
                            },
                            '& .MuiSvgIcon-root': {
                              fontSize: '1.2rem',
                            },
                          }}
                        />
                      </TableCell>
                    ))}
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>

          <Box sx={{ mt: 2, p: 1.5, backgroundColor: '#f8f9fa', borderRadius: '8px' }}>
            <Typography variant="body2" color="text.secondary" sx={{ fontSize: '0.8rem' }}>
              <i className="fas fa-info-circle" style={{ marginRight: '0.4rem', fontSize: '0.8rem' }} />
              <Trans>
                Wählen Sie für jedes Icon die Funktionen aus, die in der mobilen Ansicht verfügbar sein sollen.
                Die Funktionen werden dann im entsprechenden Icon-Menü angezeigt.
              </Trans>
            </Typography>
      </Box>
    </Box>
  );
};

export default FeatureMatrixTab;