import React, { useState, useMemo } from 'react';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import TextField from '@mui/material/TextField';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemAvatar from '@mui/material/ListItemAvatar';
import ListItemText from '@mui/material/ListItemText';
import ListItemButton from '@mui/material/ListItemButton';
import Badge from '@mui/material/Badge';
import IconButton from '@mui/material/IconButton';
import InputAdornment from '@mui/material/InputAdornment';
import CircularProgress from '@mui/material/CircularProgress';
import { Close as CloseIcon, Search as SearchIcon } from '@mui/icons-material';
import { ChatUserWithConversation, ChatResponsiveSettings } from '../../types/chat';
import UserAvatar from '../UserAvatar';

interface ChatUserListProps {
  users: ChatUserWithConversation[];
  loading: boolean;
  currentUserId?: number;
  responsiveSettings: ChatResponsiveSettings;
  rightOffset: number;
  onSelectUser: (userId: number, existingConversationId?: string) => void;
  onClose: () => void;
  embedded?: boolean;
}

const ChatUserList: React.FC<ChatUserListProps> = ({
  users,
  loading,
  currentUserId,
  responsiveSettings,
  rightOffset,
  onSelectUser,
  onClose,
  embedded = false,
}) => {
  const [searchQuery, setSearchQuery] = useState('');
  const { boxWidth, boxHeight } = responsiveSettings;

  // Filter users by search query
  const filteredUsers = useMemo(() => {
    if (!searchQuery.trim()) return users;

    const query = searchQuery.toLowerCase();
    return users.filter(
      (user) =>
        user.name.toLowerCase().includes(query) ||
        (user.email && user.email.toLowerCase().includes(query))
    );
  }, [users, searchQuery]);

  // 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();
  };

  // Format last message preview
  const formatLastMessage = (
    user: ChatUserWithConversation
  ): string | undefined => {
    if (!user.lastMessage) return undefined;

    const isSentByMe = user.lastMessage.senderId === currentUserId;
    const prefix = isSentByMe ? 'Du: ' : '';
    const content = user.lastMessage.content;

    // Truncate if too long
    const maxLength = 30;
    const truncated =
      content.length > maxLength ? content.substring(0, maxLength) + '...' : content;

    return prefix + truncated;
  };

  // Format time for last message
  const formatTime = (timestamp: string): string => {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffDays === 0) {
      // Today - show time
      return date.toLocaleTimeString('de-DE', {
        hour: '2-digit',
        minute: '2-digit',
      });
    } else if (diffDays === 1) {
      return 'Gestern';
    } else if (diffDays < 7) {
      // This week - show day name
      return date.toLocaleDateString('de-DE', { weekday: 'short' });
    } else {
      // Older - show date
      return date.toLocaleDateString('de-DE', {
        day: '2-digit',
        month: '2-digit',
      });
    }
  };

  // Shared list content (search + user list)
  const listContent = (
    <>
      {/* Search */}
      <Box sx={{ p: 1, borderBottom: '1px solid', borderColor: 'divider' }}>
        <TextField
          fullWidth
          size="small"
          placeholder="Benutzer suchen..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          aria-label="Benutzer suchen"
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon sx={{ color: 'text.secondary', fontSize: 20 }} />
              </InputAdornment>
            ),
            sx: {
              fontSize: '14px',
              backgroundColor: 'action.hover',
              borderRadius: '20px',
              '& fieldset': { border: 'none' },
            },
          }}
        />
      </Box>

      {/* User list */}
      <Box sx={{ flex: 1, overflow: 'auto' }}>
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
            <CircularProgress size={32} />
          </Box>
        ) : filteredUsers.length === 0 ? (
          <Box sx={{ textAlign: 'center', py: 4, color: 'text.secondary' }}>
            <Typography variant="body2">
              {searchQuery ? 'Keine Benutzer gefunden' : 'Keine Benutzer verfügbar'}
            </Typography>
          </Box>
        ) : (
          <List disablePadding>
            {filteredUsers.map((user) => {
              const lastMessagePreview = formatLastMessage(user);
              const hasUnread = (user.unreadCount ?? 0) > 0;

              return (
                <ListItem key={user.id} disablePadding divider>
                  <ListItemButton
                    onClick={() => onSelectUser(user.id, user.conversationId)}
                    sx={{
                      py: 1,
                      px: 1.5,
                      '&:hover': {
                        backgroundColor: 'action.hover',
                      },
                    }}
                  >
                    <ListItemAvatar sx={{ minWidth: 44 }}>
                      <Badge
                        overlap="circular"
                        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
                        variant="dot"
                        invisible={!user.isOnline}
                        sx={{
                          '& .MuiBadge-badge': {
                            backgroundColor: 'success.main',
                            boxShadow: '0 0 0 2px #ffffff',
                            width: 10,
                            height: 10,
                            borderRadius: '50%',
                          },
                        }}
                      >
                        <UserAvatar
                          photoUrl={user.avatar}
                          initials={getInitials(user.name)}
                          fullName={user.name}
                          sx={{ width: 36, height: 36, fontSize: '14px' }}
                        />
                      </Badge>
                    </ListItemAvatar>
                    <ListItemText
                      primary={
                        <Box
                          sx={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                          }}
                        >
                          <Typography
                            component="span"
                            sx={{
                              fontSize: '14px',
                              fontWeight: hasUnread ? 600 : 500,
                            }}
                          >
                            {user.name}
                          </Typography>
                          {user.lastMessage && (
                            <Typography
                              component="span"
                              sx={{
                                fontSize: '11px',
                                color: hasUnread ? 'primary.main' : 'text.secondary',
                                fontWeight: hasUnread ? 600 : 400,
                              }}
                            >
                              {formatTime(user.lastMessage.timestamp)}
                            </Typography>
                          )}
                        </Box>
                      }
                      secondary={
                        lastMessagePreview ? (
                          <Box
                            sx={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                            }}
                          >
                            <Typography
                              component="span"
                              sx={{
                                fontSize: '12px',
                                color: hasUnread ? 'text.primary' : 'text.secondary',
                                fontWeight: hasUnread ? 500 : 400,
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                whiteSpace: 'nowrap',
                                flex: 1,
                              }}
                            >
                              {lastMessagePreview}
                            </Typography>
                            {hasUnread && (
                              <Badge
                                badgeContent={user.unreadCount}
                                color="primary"
                                sx={{
                                  ml: 1,
                                  '& .MuiBadge-badge': {
                                    fontSize: '10px',
                                    height: 18,
                                    minWidth: 18,
                                  },
                                }}
                              />
                            )}
                          </Box>
                        ) : user.isOnline ? (
                          'Online'
                        ) : undefined
                      }
                      primaryTypographyProps={{
                        component: 'div',
                      }}
                      secondaryTypographyProps={{
                        component: 'div',
                        sx: !lastMessagePreview
                          ? {
                              fontSize: '12px',
                              color: 'success.main',
                            }
                          : undefined,
                      }}
                    />
                  </ListItemButton>
                </ListItem>
              );
            })}
          </List>
        )}
      </Box>
    </>
  );

  // Embedded mode: render only search + list (parent provides the wrapper)
  if (embedded) {
    return listContent;
  }

  // Standalone mode: render with Paper wrapper and header
  return (
    <Paper
      elevation={4}
      sx={{
        position: 'fixed',
        bottom: 0,
        right: rightOffset,
        width: boxWidth,
        height: boxHeight,
        borderRadius: '8px 8px 0 0',
        overflow: 'hidden',
        display: 'flex',
        flexDirection: 'column',
        zIndex: 1300,
        transition: 'right 0.2s ease-in-out',
      }}
    >
      {/* Header */}
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          p: 1.5,
          backgroundColor: 'background.default',
          borderBottom: '1px solid',
          borderColor: 'divider',
        }}
      >
        <Typography variant="subtitle1" sx={{ fontWeight: 500 }}>
          Neue Nachricht
        </Typography>
        <IconButton size="small" onClick={onClose}>
          <CloseIcon fontSize="small" />
        </IconButton>
      </Box>

      {listContent}
    </Paper>
  );
};

export default ChatUserList;
