import React, { useEffect, useState } from 'react';
import { Box, TextField, Button, Paper, Typography } from '@mui/material';
import { io, Socket } from 'socket.io-client';
import { useAuth } from '../hooks/useAuth';

interface Message {
  id: string;
  content: string;
  sender: string;
  timestamp: Date;
}

export const Chat: React.FC = () => {
  const [socket, setSocket] = useState<Socket | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [newMessage, setNewMessage] = useState('');
  const { user } = useAuth();

  useEffect(() => {
    const socket = io(process.env.NEXT_PUBLIC_API_URL!);
    setSocket(socket);

    socket.on('message', (message: Message) => {
      setMessages(prev => [...prev, message]);
    });

    return () => {
      socket.disconnect();
    };
  }, []);

  const sendMessage = () => {
    if (!socket || !newMessage.trim()) return;

    socket.emit('sendMessage', {
      content: newMessage,
      sender: user?.id,
    });

    setNewMessage('');
  };

  return (
    <Paper elevation={3} sx={{ p: 2, height: '500px', display: 'flex', flexDirection: 'column' }}>
      <Box sx={{ flexGrow: 1, overflow: 'auto', mb: 2 }}>
        {messages.map((message) => (
          <Box key={message.id} sx={{ mb: 1 }}>
            <Typography variant="subtitle2">{message.sender}</Typography>
            <Typography>{message.content}</Typography>
          </Box>
        ))}
      </Box>
      <Box sx={{ display: 'flex', gap: 1 }}>
        <TextField
          fullWidth
          value={newMessage}
          onChange={(e) => setNewMessage(e.target.value)}
          placeholder="Type a message"
        />
        <Button variant="contained" onClick={sendMessage}>Send</Button>
      </Box>
    </Paper>
  );
};