import React from 'react';
import Box from '@mui/material/Box';
import Avatar from '@mui/material/Avatar';
import Typography from '@mui/material/Typography';
import Chip from '@mui/material/Chip';
import Divider from '@mui/material/Divider';
import PersonIcon from '@mui/icons-material/Person';
import WorkIcon from '@mui/icons-material/Work';
import CoffeeIcon from '@mui/icons-material/Coffee';
import WorkOffIcon from '@mui/icons-material/WorkOff';
import { Trans, t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { format } from 'date-fns';
import { de } from 'date-fns/locale';
import WidgetWrapper from './WidgetWrapper';
import { DashboardProfile } from '../../types/dashboard';

interface ProfileWidgetProps {
  profile: DashboardProfile | null;
  loading?: boolean;
  error?: string | null;
  onRefresh?: () => void;
}

const ProfileWidget: React.FC<ProfileWidgetProps> = ({
  profile,
  loading = false,
  error = null,
  onRefresh,
}) => {
  const { i18n } = useLingui();

  const getStatusIcon = () => {
    if (!profile) return <WorkOffIcon />;
    switch (profile.currentStatus.status) {
      case 'clocked_in':
        return <WorkIcon sx={{ color: 'success.main' }} />;
      case 'on_break':
        return <CoffeeIcon sx={{ color: 'warning.main' }} />;
      default:
        return <WorkOffIcon sx={{ color: 'text.secondary' }} />;
    }
  };

  const getStatusText = () => {
    if (!profile) return i18n._(t`Nicht eingestempelt`);
    switch (profile.currentStatus.status) {
      case 'clocked_in':
        return i18n._(t`Eingestempelt`);
      case 'on_break':
        return i18n._(t`Auf Pause`);
      default:
        return i18n._(t`Nicht eingestempelt`);
    }
  };

  const getStatusBorderColor = (): string => {
    if (!profile) return 'grey.300';
    switch (profile.currentStatus.status) {
      case 'clocked_in':
        return 'success.main';
      case 'on_break':
        return 'warning.main';
      default:
        return 'grey.300';
    }
  };

  const getStatusTextColor = (): string => {
    if (!profile) return 'text.secondary';
    switch (profile.currentStatus.status) {
      case 'clocked_in':
        return 'success.main';
      case 'on_break':
        return 'warning.main';
      default:
        return 'text.secondary';
    }
  };

  return (
    <WidgetWrapper
      title={i18n._(t`Mein Profil`)}
      icon={<PersonIcon />}
      loading={loading}
      error={error}
      empty={!profile}
      emptyMessage={i18n._(t`Profil konnte nicht geladen werden`)}
      onRefresh={onRefresh}
    >
      {profile && (
        <Box sx={{ p: 1.5 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 1.5 }}>
            {profile.userPhoto ? (
              <Avatar
                src={profile.userPhoto}
                alt={profile.userName}
                sx={{
                  width: 64,
                  height: 64,
                  border: '2px solid',
                  borderColor: getStatusBorderColor(),
                }}
              />
            ) : (
              <Avatar
                sx={{
                  width: 64,
                  height: 64,
                  bgcolor: 'primary.main',
                  fontSize: '1.5rem',
                  fontWeight: 600,
                  border: '2px solid',
                  borderColor: getStatusBorderColor(),
                }}
              >
                {profile.userInitials}
              </Avatar>
            )}
            <Box>
              <Typography variant="h6" sx={{ fontWeight: 600, lineHeight: 1.3 }}>
                {profile.userName}
              </Typography>
              {profile.departments.length > 0 && (
                <Typography variant="body2" sx={{ color: 'text.secondary', fontWeight: 500 }}>
                  {profile.departments.map((d) => d.ber_name).join(', ')}
                </Typography>
              )}
            </Box>
          </Box>

          {profile.roles && profile.roles.length > 0 && (
            <Box sx={{ mb: 1.5, display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
              {profile.roles.map((role) => (
                <Chip
                  key={role.roleId}
                  label={role.roleName}
                  size="small"
                  sx={{
                    bgcolor: role.roleColor,
                    color: getContrastColor(role.roleColor),
                    fontWeight: 500,
                    borderRadius: 1.5,
                  }}
                />
              ))}
            </Box>
          )}

          <Divider sx={{ my: 1.5, borderColor: 'grey.200' }} />

          <Box
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: 1.5,
              p: 1.5,
              borderRadius: 2,
              bgcolor: 'grey.50',
              borderLeft: '3px solid',
              borderLeftColor: getStatusBorderColor(),
            }}
          >
            {getStatusIcon()}
            <Box sx={{ flex: 1 }}>
              <Typography variant="body2" sx={{ fontWeight: 600, color: getStatusTextColor() }}>
                {getStatusText()}
              </Typography>
              {profile.currentStatus.clockInTime && (
                <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                  <Trans>seit</Trans>{' '}
                  {format(new Date(profile.currentStatus.clockInTime), 'HH:mm', { locale: de })}
                  {profile.currentStatus.shiftName && (
                    <> &bull; {profile.currentStatus.shiftName}</>
                  )}
                </Typography>
              )}
              {profile.currentStatus.status === 'on_break' &&
                profile.currentStatus.currentBreakStart && (
                  <Typography variant="caption" display="block" sx={{ color: 'warning.main' }}>
                    <Trans>Pause seit</Trans>{' '}
                    {format(new Date(profile.currentStatus.currentBreakStart), 'HH:mm', {
                      locale: de,
                    })}
                  </Typography>
                )}
            </Box>
          </Box>

          {profile.currentStatus.shiftStartTime && profile.currentStatus.shiftEndTime && (
            <Box sx={{ mt: 1.5 }}>
              <Typography variant="caption" sx={{ color: 'text.secondary', fontWeight: 500 }}>
                <Trans>Schicht:</Trans> {profile.currentStatus.shiftStartTime} -{' '}
                {profile.currentStatus.shiftEndTime}
              </Typography>
            </Box>
          )}
        </Box>
      )}
    </WidgetWrapper>
  );
};

function getContrastColor(hexColor: string): string {
  if (!hexColor) return '#000000';
  const r: number = parseInt(hexColor.slice(1, 3), 16);
  const g: number = parseInt(hexColor.slice(3, 5), 16);
  const b: number = parseInt(hexColor.slice(5, 7), 16);
  const luminance: number = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  return luminance > 0.5 ? '#000000' : '#FFFFFF';
}

export default ProfileWidget;
