import React from 'react';
import Box from '@mui/material/Box';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import Badge from '@mui/material/Badge';
import Tooltip from '@mui/material/Tooltip';
import {
  Remove as MinimizeIcon,
  Close as CloseIcon,
  Call as CallIcon,
} from '@mui/icons-material';
import { ChatUser, CallType } from '../../types/chat';
import UserAvatar from '../UserAvatar';

interface ChatHeaderProps {
  participants: ChatUser[];
  currentUserId: number;
  conversationName?: string;
  isGroup?: boolean;
  minimized: boolean;
  unreadCount?: number;
  onlineUsers?: Set<number>;
  onMinimize: () => void;
  onClose: () => void;
  onExpand: () => void;
  onCall?: (type: CallType) => void;
}

const ChatHeader: React.FC<ChatHeaderProps> = ({
  participants,
  currentUserId,
  conversationName,
  isGroup = false,
  minimized,
  unreadCount = 0,
  onlineUsers,
  onMinimize,
  onClose,
  onExpand,
  onCall,
}) => {
  // Get the other participant for direct chats
  const otherParticipant = participants.find(p => p.id !== currentUserId);

  // Display name
  const displayName = isGroup
    ? conversationName || 'Gruppenchat'
    : otherParticipant?.name || 'Unbekannt';

  // Online status for direct chats - use onlineUsers set from WebSocket for real-time status
  const isOnline = !isGroup && otherParticipant && onlineUsers?.has(otherParticipant.id);

  // Get initials for avatar
  const getInitials = (name: string): string => {
    const parts = name.split(' ');
    if (parts.length >= 2) {
      return (parts[0][0] + parts[1][0]).toUpperCase();
    }
    return name.substring(0, 2).toUpperCase();
  };

  const handleClick = () => {
    if (minimized) {
      onExpand();
    }
  };

  return (
    <Box
      onClick={handleClick}
      sx={{
        display: 'flex',
        alignItems: 'center',
        gap: 1,
        px: 1.5,
        py: 0.75,
        backgroundColor: '#f8f9fa',
        borderBottom: minimized ? 'none' : '1px solid #dee2e6',
        borderRadius: minimized ? '8px' : '8px 8px 0 0',
        cursor: minimized ? 'pointer' : 'default',
        minHeight: 44,
        boxShadow: '0 1px 2px rgba(0,0,0,0.1)',
        '&:hover': minimized ? {
          backgroundColor: '#e9ecef',
        } : {},
      }}
    >
      {/* Avatar with online badge */}
      <Badge
        overlap="circular"
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        variant="dot"
        invisible={!isOnline}
        sx={{
          '& .MuiBadge-badge': {
            backgroundColor: '#4caf50',
            color: '#4caf50',
            boxShadow: '0 0 0 2px #f8f9fa',
            width: 10,
            height: 10,
            borderRadius: '50%',
          },
        }}
      >
        <UserAvatar
          photoUrl={isGroup ? null : otherParticipant?.avatar}
          initials={getInitials(displayName)}
          fullName={displayName}
          sx={{ width: 32, height: 32, fontSize: '14px' }}
        />
      </Badge>

      {/* Name and status */}
      <Box sx={{ flex: 1, minWidth: 0 }}>
        <Typography
          variant="subtitle2"
          sx={{
            fontWeight: 500,
            fontSize: '14px',
            lineHeight: 1.2,
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
          }}
        >
          {displayName}
        </Typography>
        {!minimized && (
          <Typography
            variant="caption"
            sx={{
              color: isOnline ? '#4caf50' : '#495057',
              fontSize: '11px',
              lineHeight: 1.2,
            }}
          >
            {isOnline ? 'Online' : (isGroup ? `${participants.length} Teilnehmer` : 'Offline')}
          </Typography>
        )}
      </Box>

      {/* Unread badge (for minimized state) */}
      {minimized && unreadCount > 0 && (
        <Box
          sx={{
            minWidth: 18,
            height: 18,
            borderRadius: '9px',
            backgroundColor: '#d32f2f',
            color: '#ffffff',
            fontSize: '11px',
            fontWeight: 600,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            px: 0.5,
            mr: 0.5,
          }}
        >
          {unreadCount > 99 ? '99+' : unreadCount}
        </Box>
      )}

      {/* Action buttons */}
      {!minimized && (
        <>
          {/* Call button - only for direct chats (audio only) */}
          {!isGroup && onCall && (
            <Tooltip title="Anrufen">
              <IconButton
                size="small"
                onClick={(e) => {
                  e.stopPropagation();
                  onCall('audio');
                }}
                sx={{
                  color: '#1976d2',
                  p: 0.5,
                  '&:hover': {
                    backgroundColor: 'rgba(25, 118, 210, 0.08)',
                  },
                }}
              >
                <CallIcon fontSize="small" />
              </IconButton>
            </Tooltip>
          )}
          <IconButton
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              onMinimize();
            }}
            sx={{
              color: '#495057',
              p: 0.5,
              '&:hover': {
                backgroundColor: 'rgba(0,0,0,0.08)',
              },
            }}
          >
            <MinimizeIcon fontSize="small" />
          </IconButton>
          <IconButton
            size="small"
            onClick={(e) => {
              e.stopPropagation();
              onClose();
            }}
            sx={{
              color: '#495057',
              p: 0.5,
              '&:hover': {
                backgroundColor: 'rgba(0,0,0,0.08)',
              },
            }}
          >
            <CloseIcon fontSize="small" />
          </IconButton>
        </>
      )}
    </Box>
  );
};

export default ChatHeader;
