'use client';

import { useState, useEffect, useRef } from 'react';

interface ChatMessage {
  id: string;
  username: string;
  message: string;
  timestamp: Date;
}

export default function ChatSidebar() {
  const [messages, setMessages] = useState<ChatMessage[]>([
    {
      id: '1',
      username: 'CyberUser',
      message: 'Welcome to AeThex Live!',
      timestamp: new Date(),
    },
    {
      id: '2',
      username: 'TechFan',
      message: 'This stream is amazing!',
      timestamp: new Date(),
    },
  ]);
  const [inputMessage, setInputMessage] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    // Simulate new messages
    const interval = setInterval(() => {
      const randomUsers = ['NeuralNet', 'DataStream', 'QuantumBit', 'CyberPunk'];
      const randomMessages = [
        'Great content!',
        'Love the vibe',
        '🔥🔥🔥',
        'Keep it up!',
        'Amazing quality',
      ];

      const newMessage: ChatMessage = {
        id: Date.now().toString(),
        username: randomUsers[Math.floor(Math.random() * randomUsers.length)],
        message: randomMessages[Math.floor(Math.random() * randomMessages.length)],
        timestamp: new Date(),
      };

      setMessages((prev) => [...prev.slice(-49), newMessage]);
    }, 10000);

    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const handleSendMessage = (e: React.FormEvent) => {
    e.preventDefault();
    if (!inputMessage.trim()) return;

    const newMessage: ChatMessage = {
      id: Date.now().toString(),
      username: 'You',
      message: inputMessage,
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, newMessage]);
    setInputMessage('');
  };

  return (
    <div className="flex flex-col h-full bg-black/50 backdrop-blur-sm border-l border-cyan-500/30">
      <div className="p-4 border-b border-cyan-500/30">
        <h2 className="text-cyan-400 font-mono font-semibold flex items-center gap-2">
          <svg
            className="w-5 h-5"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
            />
          </svg>
          Live Chat
        </h2>
      </div>

      <div className="flex-1 overflow-y-auto p-4 space-y-3">
        {messages.map((msg) => (
          <div key={msg.id} className="animate-fade-in">
            <div className="flex items-start gap-2">
              <span className="text-cyan-400 font-mono text-xs font-semibold">
                {msg.username}:
              </span>
              <span className="text-white/90 text-xs flex-1 break-words">
                {msg.message}
              </span>
            </div>
          </div>
        ))}
        <div ref={messagesEndRef} />
      </div>

      <form onSubmit={handleSendMessage} className="p-4 border-t border-cyan-500/30">
        <div className="flex gap-2">
          <input
            type="text"
            value={inputMessage}
            onChange={(e) => setInputMessage(e.target.value)}
            placeholder="Type a message..."
            className="flex-1 bg-black/50 border border-cyan-500/30 rounded-lg px-3 py-2 text-white text-sm font-mono placeholder-cyan-400/40 focus:outline-none focus:ring-2 focus:ring-cyan-500/50"
          />
          <button
            type="submit"
            className="bg-cyan-500 hover:bg-cyan-600 text-black font-mono font-semibold px-4 py-2 rounded-lg transition-colors text-sm"
          >
            Send
          </button>
        </div>
      </form>
    </div>
  );
}
