import React, { useState } from 'react';
import Box from '@mui/material/Box';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import Avatar from '@mui/material/Avatar';
import Badge from '@mui/material/Badge';
import Typography from '@mui/material/Typography';
import Fab from '@mui/material/Fab';
import AddIcon from '@mui/icons-material/Add';
import { useQueryClient } from '@tanstack/react-query';
import { useChat } from '../../contexts/ChatContext';
import NewChatDialog from './NewChatDialog';

const ChatRoomList: React.FC = () => {
  const { rooms, selectedRoomToken, selectRoom } = useChat();
  const queryClient = useQueryClient();
  const [dialogOpen, setDialogOpen] = useState(false);

  return (
    <Box sx={{ overflow: 'auto', flex: 1, position: 'relative' }}>
      <Box sx={{ px: 1.5, py: 0.75, borderBottom: 1, borderColor: 'divider' }}>
        <Typography variant="caption" sx={{ fontWeight: 600, opacity: 0.6, letterSpacing: '0.05em' }}>
          GESPRÄCHE
        </Typography>
      </Box>
      <List disablePadding>
        {rooms.map((room) => {
          const isSelected = room.token === selectedRoomToken;
          return (
            <ListItem key={room.token} disablePadding>
              <ListItemButton
                selected={isSelected}
                onClick={() => selectRoom(room.token)}
                sx={{
                  py: 1,
                  px: 1.5,
                  '&.Mui-selected': {
                    backgroundColor: 'primary.light',
                    color: 'primary.contrastText',
                    '&:hover': {
                      backgroundColor: 'primary.main',
                    },
                    '& .MuiListItemIcon-root': {
                      color: 'primary.contrastText',
                    },
                    '& .MuiListItemText-secondary': {
                      color: 'primary.contrastText',
                      opacity: 0.7,
                    },
                  },
                }}
              >
                <ListItemIcon sx={{ minWidth: 40 }}>
                  <Badge
                    badgeContent={room.unreadMessages}
                    color="primary"
                    invisible={room.unreadMessages === 0}
                  >
                    <Avatar
                      sx={{
                        width: 32,
                        height: 32,
                        fontSize: '0.75rem',
                        bgcolor: isSelected ? 'primary.main' : 'action.hover',
                        color: isSelected ? 'primary.contrastText' : 'text.primary',
                      }}
                    >
                      {room.displayName.substring(0, 2).toUpperCase()}
                    </Avatar>
                  </Badge>
                </ListItemIcon>
                <ListItemText
                  primary={room.displayName}
                  primaryTypographyProps={{ noWrap: true, variant: 'subtitle2' }}
                  secondary={
                    room.lastMessage
                      ? `${room.lastMessage.author}: ${room.lastMessage.text}`
                      : undefined
                  }
                  secondaryTypographyProps={{ noWrap: true, variant: 'caption' }}
                />
              </ListItemButton>
            </ListItem>
          );
        })}
      </List>
      {/* Sticky FAB at bottom-right */}
      <Box sx={{ position: 'sticky', bottom: 16, display: 'flex', justifyContent: 'flex-end', pr: 2, mt: 1, pointerEvents: 'none' }}>
        <Fab
          size="small"
          color="primary"
          aria-label="Neues Gespräch"
          onClick={() => setDialogOpen(true)}
          sx={{ pointerEvents: 'auto' }}
        >
          <AddIcon />
        </Fab>
      </Box>
      <NewChatDialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        onRoomCreated={(token) => {
          queryClient.invalidateQueries({ queryKey: ['nextcloud', 'rooms'] });
          selectRoom(token);
          setDialogOpen(false);
        }}
      />
    </Box>
  );
};

export default ChatRoomList;
