import React from 'react';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import Tooltip from '@mui/material/Tooltip';
import { Link, useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
import { Settings } from '@mui/icons-material';
import DashboardLayout from '../components/dashboard/DashboardLayout';
import { useChat } from '../contexts/ChatContext';
import { usePermissionContext } from '../contexts/PermissionContext';
import { nextcloudApi } from '../services/nextcloud';
import { notificationsApi } from '../services/notifications';
import ChatRoomList from '../components/chat/ChatRoomList';
import ChatMessageView from '../components/chat/ChatMessageView';

const ChatContent: React.FC = () => {
  const { rooms, selectedRoomToken, connected } = useChat();
  const { hasPermission } = usePermissionContext();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const markedRoomsRef = React.useRef(new Set<string>());

  // Dismiss nextcloud_talk notifications when on this page
  React.useEffect(() => {
    notificationsApi.dismissByType('nextcloud_talk').then(() => {
      queryClient.invalidateQueries({ queryKey: ['notifications'] });
      queryClient.invalidateQueries({ queryKey: ['unreadNotificationCount'] });
    }).catch(() => {});
  }, [queryClient]);

  // Mark unread rooms as read when rooms data updates
  React.useEffect(() => {
    const unread = rooms.filter(
      (r) => r.unreadMessages > 0 && !markedRoomsRef.current.has(r.token),
    );
    if (unread.length === 0) return;
    unread.forEach((r) => markedRoomsRef.current.add(r.token));
    Promise.allSettled(unread.map((r) => nextcloudApi.markAsRead(r.token))).then(() => {
      queryClient.invalidateQueries({ queryKey: ['nextcloud', 'rooms'] });
    });
  }, [rooms, queryClient]);

  // Mark selected room as read when a conversation is opened
  React.useEffect(() => {
    if (!selectedRoomToken) return;
    nextcloudApi.markAsRead(selectedRoomToken).then(() => {
      queryClient.invalidateQueries({ queryKey: ['nextcloud', 'rooms'] });
    }).catch(() => {});
  }, [selectedRoomToken, queryClient]);

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', height: 'calc(100vh - 112px)' }}>
      {hasPermission('nextcloud:configure') && (
        <Box sx={{ display: 'flex', justifyContent: 'flex-end', px: 1 }}>
          <Tooltip title="Einstellungen">
            <IconButton size="small" onClick={() => navigate('/admin/settings?tab=1&subtab=nextcloud')}>
              <Settings fontSize="small" />
            </IconButton>
          </Tooltip>
        </Box>
      )}
      <Box
        sx={{
          flex: 1,
          display: 'flex',
          border: 1,
          borderColor: 'divider',
          borderRadius: 1,
          overflow: 'hidden',
          minHeight: 0,
        }}
      >
      {!connected ? (
        <Box sx={{ p: 3, display: 'flex', alignItems: 'center' }}>
          <Typography variant="body1" color="text.secondary">
            Nextcloud nicht verbunden. Bitte verbinden Sie sich in den{' '}
            <Link to="/settings" style={{ color: 'inherit' }}>Einstellungen</Link>.
          </Typography>
        </Box>
      ) : (
        <>
          <Box
            sx={{
              width: 280,
              flexShrink: 0,
              borderRight: 1,
              borderColor: 'divider',
              display: 'flex',
              flexDirection: 'column',
              overflow: 'hidden',
            }}
          >
            <ChatRoomList />
          </Box>
          <Box sx={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
            {selectedRoomToken ? (
              <ChatMessageView />
            ) : (
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%' }}>
                <Typography variant="body1" color="text.secondary">
                  Wähle ein Gespräch aus, um zu beginnen.
                </Typography>
              </Box>
            )}
          </Box>
        </>
      )}
      </Box>
    </Box>
  );
};

const ChatPage: React.FC = () => {
  return (
    <DashboardLayout>
      <ChatContent />
    </DashboardLayout>
  );
};

export default ChatPage;
