import React, { useState } from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import Chip from '@mui/material/Chip';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import Tooltip from '@mui/material/Tooltip';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import CircularProgress from '@mui/material/CircularProgress';
import WarningIcon from '@mui/icons-material/Warning';
import PhoneIcon from '@mui/icons-material/Phone';
import EmailIcon from '@mui/icons-material/Email';
import PersonOffIcon from '@mui/icons-material/PersonOff';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import { Trans, t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { formatDistanceToNow } from 'date-fns';
import { de } from 'date-fns/locale';
import WidgetWrapper from './WidgetWrapper';
import { AttendanceAlert } from '../../types/dashboard';

interface AttendanceWidgetProps {
  alerts: AttendanceAlert[];
  loading?: boolean;
  error?: string | null;
  onRefresh?: () => void;
  onMarkAbsent?: (alertId: string, userId: number) => Promise<void>;
  onResolve?: (alertId: string, resolution: string) => Promise<void>;
}

const alertBorderColor: Record<string, string> = {
  no_show: 'error.main',
  very_late: 'error.main',
  late: 'warning.main',
};

const AttendanceWidget: React.FC<AttendanceWidgetProps> = ({
  alerts,
  loading = false,
  error = null,
  onRefresh,
  onMarkAbsent,
  onResolve,
}) => {
  const { i18n } = useLingui();
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [contactDialog, setContactDialog] = useState<AttendanceAlert | null>(null);

  const alertsByDepartment = alerts.reduce((acc, alert) => {
    if (!alert.resolved) {
      const key = `${alert.departmentId}-${alert.shiftName}`;
      if (!acc[key]) {
        acc[key] = {
          departmentName: alert.departmentName,
          shiftName: alert.shiftName,
          shiftStartTime: alert.shiftStartTime,
          alerts: [],
        };
      }
      acc[key].alerts.push(alert);
    }
    return acc;
  }, {} as Record<string, { departmentName: string; shiftName: string; shiftStartTime: string; alerts: AttendanceAlert[] }>);

  const unresolvedCount: number = alerts.filter((a) => !a.resolved).length;

  const getAlertColor = (alertType: string): 'error' | 'warning' => {
    switch (alertType) {
      case 'no_show':
      case 'very_late':
        return 'error';
      default:
        return 'warning';
    }
  };

  const getAlertLabel = (alert: AttendanceAlert): string => {
    if (alert.alertType === 'no_show') {
      return i18n._(t`Nicht erschienen`);
    }
    return `${Math.round(alert.minutesLate)} min ${i18n._(t`zu spät`)}`;
  };

  const handleMarkAbsent = async (alert: AttendanceAlert): Promise<void> => {
    if (!onMarkAbsent) return;
    setActionLoading(alert.id);
    try {
      await onMarkAbsent(alert.id, alert.userId);
    } finally {
      setActionLoading(null);
    }
  };

  const handleContact = (alert: AttendanceAlert): void => {
    setContactDialog(alert);
  };

  return (
    <>
      <WidgetWrapper
        title={i18n._(t`Anwesenheitswarnungen`)}
        icon={<WarningIcon />}
        loading={loading}
        error={error}
        empty={unresolvedCount === 0}
        emptyMessage={i18n._(t`Alle Mitarbeiter sind pünktlich`)}
        emptyIcon={<CheckCircleIcon sx={{ fontSize: 48, color: 'success.main' }} />}
        onRefresh={onRefresh}
        badge={unresolvedCount > 0 ? unresolvedCount : undefined}
        badgeColor="error"
      >
        <Box sx={{ overflow: 'auto' }}>
          {Object.entries(alertsByDepartment).map(([key, group]) => (
            <Box key={key}>
              <Box
                sx={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 1,
                  px: 2,
                  py: 1,
                  borderLeft: '3px solid',
                  borderColor: 'primary.main',
                }}
              >
                <Typography variant="body2" fontWeight={600} sx={{ fontSize: '0.8rem', color: 'text.primary' }}>
                  {group.departmentName}
                </Typography>
                <Typography variant="caption" sx={{ color: 'text.secondary', fontSize: '0.75rem', fontWeight: 500 }}>
                  {group.shiftName} ({group.shiftStartTime})
                </Typography>
                <Chip
                  size="small"
                  label={group.alerts.length}
                  color="error"
                  sx={{ ml: 'auto', height: 20, fontSize: '0.7rem', fontWeight: 600 }}
                />
              </Box>

              <List dense disablePadding>
                {group.alerts.map((alert, index) => {
                  const isLast: boolean = index === group.alerts.length - 1;
                  const color: string = alertBorderColor[alert.alertType] || 'warning.main';

                  return (
                    <ListItem
                      key={alert.id}
                      sx={{
                        px: 2,
                        py: 1.25,
                        transition: 'background-color 0.15s ease',
                        '&:hover': { bgcolor: 'action.hover' },
                        ...(!isLast && {
                          borderBottom: '1px solid',
                          borderColor: 'divider',
                        }),
                      }}
                    >
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, width: '100%' }}>
                        <Box
                          sx={{
                            width: 3,
                            alignSelf: 'stretch',
                            borderRadius: 1.5,
                            bgcolor: color,
                            flexShrink: 0,
                          }}
                        />

                        {alert.userPhoto ? (
                          <Avatar
                            src={alert.userPhoto}
                            alt={alert.userName}
                            sx={{ width: 32, height: 32, flexShrink: 0 }}
                          />
                        ) : (
                          <Avatar
                            sx={{
                              width: 32,
                              height: 32,
                              fontSize: '0.75rem',
                              fontWeight: 600,
                              bgcolor: `${getAlertColor(alert.alertType)}.main`,
                              flexShrink: 0,
                            }}
                          >
                            {alert.userInitials}
                          </Avatar>
                        )}

                        <Box sx={{ flex: 1, minWidth: 0 }}>
                          <Typography
                            variant="body2"
                            fontWeight={600}
                            sx={{ fontSize: '0.8rem', color: 'text.primary', lineHeight: 1.4 }}
                          >
                            {alert.userName}
                          </Typography>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75, mt: 0.25 }}>
                            <Chip
                              size="small"
                              icon={<AccessTimeIcon sx={{ fontSize: 12 }} />}
                              label={getAlertLabel(alert)}
                              color={getAlertColor(alert.alertType)}
                              sx={{ height: 18, fontSize: '0.65rem', fontWeight: 500 }}
                            />
                            <Typography
                              variant="caption"
                              sx={{ color: 'text.disabled', fontSize: '0.7rem', lineHeight: 1.3 }}
                            >
                              {formatDistanceToNow(new Date(alert.detectedAt), {
                                addSuffix: true,
                                locale: de,
                              })}
                            </Typography>
                          </Box>
                        </Box>

                        <Box sx={{ display: 'flex', gap: 0.75, flexShrink: 0 }}>
                          <Tooltip title={<Trans>Kontaktieren</Trans>}>
                            <IconButton
                              size="small"
                              onClick={() => handleContact(alert)}
                              sx={{
                                width: 28,
                                height: 28,
                                bgcolor: 'primary.main',
                                color: '#fff',
                                '&:hover': { bgcolor: 'primary.dark' },
                              }}
                            >
                              <PhoneIcon sx={{ fontSize: 16 }} />
                            </IconButton>
                          </Tooltip>
                          <Tooltip title={<Trans>Als abwesend markieren</Trans>}>
                            <IconButton
                              size="small"
                              onClick={() => handleMarkAbsent(alert)}
                              disabled={actionLoading === alert.id}
                              sx={{
                                width: 28,
                                height: 28,
                                bgcolor: 'error.main',
                                color: '#fff',
                                '&:hover': { bgcolor: 'error.dark' },
                                '&.Mui-disabled': { bgcolor: 'grey.300', color: 'grey.500' },
                              }}
                            >
                              {actionLoading === alert.id ? (
                                <CircularProgress size={14} sx={{ color: '#fff' }} />
                              ) : (
                                <PersonOffIcon sx={{ fontSize: 16 }} />
                              )}
                            </IconButton>
                          </Tooltip>
                        </Box>
                      </Box>
                    </ListItem>
                  );
                })}
              </List>
            </Box>
          ))}

          {Object.keys(alertsByDepartment).length === 0 && !loading && (
            <Box
              sx={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                gap: 1,
                p: 3,
                color: 'success.main',
              }}
            >
              <CheckCircleIcon />
              <Typography variant="body2" fontWeight={500} sx={{ fontSize: '0.8rem' }}>
                <Trans>Alle Mitarbeiter sind pünktlich erschienen</Trans>
              </Typography>
            </Box>
          )}
        </Box>
      </WidgetWrapper>

      <Dialog
        open={!!contactDialog}
        onClose={() => setContactDialog(null)}
        maxWidth="xs"
        fullWidth
        PaperProps={{ sx: { borderRadius: 3 } }}
      >
        <DialogTitle sx={{ fontWeight: 600, fontSize: '1rem' }}>
          <Trans>Mitarbeiter kontaktieren</Trans>
        </DialogTitle>
        <DialogContent>
          {contactDialog && (
            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
                <Avatar
                  src={contactDialog.userPhoto || undefined}
                  sx={{ width: 40, height: 40 }}
                >
                  {contactDialog.userInitials}
                </Avatar>
                <Box>
                  <Typography variant="body2" fontWeight={600} sx={{ fontSize: '0.8rem' }}>
                    {contactDialog.userName}
                  </Typography>
                  <Typography variant="caption" sx={{ color: 'text.secondary', fontSize: '0.75rem', fontWeight: 500 }}>
                    {getAlertLabel(contactDialog)}
                  </Typography>
                </Box>
              </Box>

              {contactDialog.userPhone && (
                <Button
                  variant="contained"
                  disableElevation
                  startIcon={<PhoneIcon />}
                  href={`tel:${contactDialog.userPhone}`}
                  fullWidth
                  sx={{ textTransform: 'none', borderRadius: 1.5, fontWeight: 500, fontSize: '0.8rem' }}
                >
                  {contactDialog.userPhone}
                </Button>
              )}

              {contactDialog.userEmail && (
                <Button
                  variant="contained"
                  disableElevation
                  startIcon={<EmailIcon />}
                  href={`mailto:${contactDialog.userEmail}`}
                  fullWidth
                  sx={{ textTransform: 'none', borderRadius: 1.5, fontWeight: 500, fontSize: '0.8rem' }}
                >
                  {contactDialog.userEmail}
                </Button>
              )}

              {!contactDialog.userPhone && !contactDialog.userEmail && (
                <Typography variant="body2" sx={{ color: 'text.secondary', textAlign: 'center', fontSize: '0.8rem' }}>
                  <Trans>Keine Kontaktdaten verfügbar</Trans>
                </Typography>
              )}
            </Box>
          )}
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button
            variant="contained"
            disableElevation
            onClick={() => setContactDialog(null)}
            sx={{ textTransform: 'none', borderRadius: 1.5, fontWeight: 500, fontSize: '0.8rem' }}
          >
            <Trans>Schliessen</Trans>
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};

export default AttendanceWidget;
