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 Switch from '@mui/material/Switch';
import { Trans } from '@lingui/macro';
import { MobileDevice } from '../types';

interface MobileDeviceCardProps {
  device: MobileDevice;
  currentVersion: string;
  onClick: () => void;
  onToggleActive: (deviceId: string, isActive: boolean) => void;
}

const MobileDeviceCard: React.FC<MobileDeviceCardProps> = ({
  device,
  currentVersion,
  onClick,
  onToggleActive,
}) => {
  const getVersionSeverity = (): 'red' | 'orange' | 'blue' | 'grey' | null => {
    const versionString = device.mcl_ver || '';
    const versionParts = versionString.split('--');
    const deviceVersionString = versionParts[0]?.trim() || '';

    const isAndroidOrIOS = versionString.toLowerCase().includes('android') || versionString.toLowerCase().includes('ios');

    if (!isAndroidOrIOS) {
      return 'blue';
    }

    const deviceVersionArray = deviceVersionString.split('.');
    const currentVersionArray = currentVersion.split('.');

    if (deviceVersionArray.length !== 3 || currentVersionArray.length !== 3) {
      return null;
    }

    const devMajor = parseInt(deviceVersionArray[0]);
    const devMinor = parseInt(deviceVersionArray[1]);
    const devPatch = parseInt(deviceVersionArray[2]);

    const currMajor = parseInt(currentVersionArray[0]);
    const currMinor = parseInt(currentVersionArray[1]);
    const currPatch = parseInt(currentVersionArray[2]);

    if (devMajor < currMajor) {
      return 'red';
    } else if (devMajor === currMajor) {
      if (devMinor < currMinor) {
        const minorDiff = currMinor - devMinor;
        if (minorDiff >= 2) {
          return 'red';
        } else if (minorDiff === 1) {
          return 'orange';
        }
      } else if (devMinor === currMinor && devPatch < currPatch) {
        return 'orange';
      }
    }

    return null;
  };

  const severity = getVersionSeverity();

  const getBackgroundColor = () => {
    switch (severity) {
      case 'red':
        return '#FF5C33';
      case 'orange':
        return '#FFA31A';
      case 'blue':
        return '#4285F4';
      default:
        return '#f9f9f9';
    }
  };

  const getTextColor = () => {
    return severity ? '#ffffff' : '#333';
  };

  const handleToggle = (e: React.ChangeEvent<HTMLInputElement>) => {
    e.stopPropagation();
    onToggleActive(device.mcl_cid, e.target.checked);
  };

  const iconSrc = device.mcl_type === 'MOBILE' ? '/imgtasko/pda.png' : '/imgtasko/rpi.png';

  return (
    <Card
      sx={{
        border: '1px solid #e3e3e3',
        borderRadius: '4px',
        backgroundColor: getBackgroundColor(),
        color: getTextColor(),
        cursor: 'pointer',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        transition: 'box-shadow 0.3s ease-in-out, background-color 0.3s ease-in-out',
        '&:hover': {
          boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
        },
      }}
      onClick={onClick}
    >
      <CardContent
        sx={{
          p: 2,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'space-between',
          flexGrow: 1,
          '&:last-child': {
            pb: 2,
          },
        }}
      >
        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            flexGrow: 1,
            width: '100%',
          }}
        >
          <Box
            component="img"
            src={iconSrc}
            alt={device.mcl_name}
            sx={{
              width: 100,
              height: 100,
              objectFit: 'contain',
              mb: 2,
            }}
          />
          <Box sx={{ textAlign: 'center', width: '100%', wordWrap: 'break-word' }}>
            <Typography variant="subtitle1" fontWeight="bold" sx={{ mb: 0.5 }}>
              {device.mcl_name}
            </Typography>
            <Typography variant="body2" sx={{ fontSize: '0.9em' }}>
              {device.mcl_bemerkung}
            </Typography>
            {device.mcl_usr_krzl && (
              <Typography
                variant="caption"
                sx={{ display: 'block', mt: 0.5, opacity: 0.85, fontSize: '0.75rem' }}
              >
                <Trans>Letzter Benutzer</Trans>:{' '}
                {device.mcl_usr_name
                  ? `${device.mcl_usr_name} (${device.mcl_usr_krzl})`
                  : device.mcl_usr_krzl}
              </Typography>
            )}
          </Box>
        </Box>

        <Box
          sx={{
            mt: 2,
            display: 'flex',
            justifyContent: 'center',
            width: '100%',
          }}
          onClick={(e) => e.stopPropagation()}
        >
          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              px: 1.5,
              py: 0.5,
              borderRadius: '20px',
              backgroundColor: device.mcl_aktiv ? '#28a745' : '#dc3545',
              color: 'white',
            }}
          >
            <Typography variant="caption" sx={{ fontSize: '0.75rem', fontWeight: 500 }}>
              {device.mcl_aktiv ? 'Aktiv' : 'Gesperrt'}
            </Typography>
            <Switch
              checked={Boolean(device.mcl_aktiv)}
              onChange={handleToggle}
              size="small"
              sx={{
                '& .MuiSwitch-switchBase': {
                  color: 'white',
                },
                '& .MuiSwitch-track': {
                  backgroundColor: 'rgba(255,255,255,0.3)',
                },
              }}
            />
          </Box>
        </Box>
      </CardContent>
    </Card>
  );
};

export default MobileDeviceCard;