/**
 * ChatPanel Component
 * Main chat interface panel that slides in from the right
 */

import React, { useEffect, useRef } from 'react';
import { X, Plus, AlertCircle } from 'lucide-react';
import { useChatStore } from '../../stores/chatStore';
import { ChatMessage } from './ChatMessage';
import { ChatInput } from './ChatInput';

export const ChatPanel: React.FC = () => {
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const {
    isOpen,
    messages,
    loading,
    error,
    currentSessionId,
    closeChat,
    sendMessage,
    createNewSession,
    clearError,
  } = useChatStore();

  // Auto-scroll to bottom when new messages arrive
  useEffect(() => {
    if (messagesEndRef.current && messages.length > 0) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages]);

  // Check if user is authenticated
  const isAuthenticated = !!localStorage.getItem('token');

  if (!isOpen) return null;

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 bg-black/50 z-40 md:hidden"
        onClick={closeChat}
      />

      {/* Panel */}
      <div
        className={`
          fixed top-0 right-0 h-full
          bg-gray-900 border-l border-gray-800
          shadow-2xl z-50
          flex flex-col
          transition-transform duration-300
          ${isOpen ? 'translate-x-0' : 'translate-x-full'}
          w-full md:w-[400px]
        `}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-4 py-3 border-b border-gray-800 bg-gray-950">
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
              <span className="text-white text-sm font-bold">OQ</span>
            </div>
            <div>
              <h2 className="text-white font-semibold text-sm">OrbiQuant Copilot</h2>
              <p className="text-gray-400 text-xs">AI Trading Assistant</p>
            </div>
          </div>

          <div className="flex items-center gap-2">
            {/* New conversation button */}
            {isAuthenticated && (
              <button
                onClick={createNewSession}
                disabled={loading}
                className="p-2 text-gray-400 hover:text-white hover:bg-gray-800 rounded-lg transition-colors"
                title="New conversation"
              >
                <Plus className="w-5 h-5" />
              </button>
            )}

            {/* Close button */}
            <button
              onClick={closeChat}
              className="p-2 text-gray-400 hover:text-white hover:bg-gray-800 rounded-lg transition-colors"
              title="Close chat"
            >
              <X className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Error banner */}
        {error && (
          <div className="mx-4 mt-4 p-3 bg-red-900/20 border border-red-900 rounded-lg flex items-start gap-2">
            <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
            <div className="flex-1">
              <p className="text-red-300 text-sm">{error}</p>
            </div>
            <button
              onClick={clearError}
              className="text-red-400 hover:text-red-300"
            >
              <X className="w-4 h-4" />
            </button>
          </div>
        )}

        {/* Not authenticated message */}
        {!isAuthenticated && (
          <div className="flex-1 flex items-center justify-center p-6">
            <div className="text-center">
              <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-gray-800 flex items-center justify-center">
                <AlertCircle className="w-8 h-8 text-gray-400" />
              </div>
              <h3 className="text-white font-medium mb-2">Authentication Required</h3>
              <p className="text-gray-400 text-sm mb-4">
                Please log in to chat with the AI copilot
              </p>
              <button
                onClick={() => (window.location.href = '/login')}
                className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                Go to Login
              </button>
            </div>
          </div>
        )}

        {/* Messages */}
        {isAuthenticated && (
          <>
            <div className="flex-1 overflow-y-auto">
              {messages.length === 0 ? (
                <div className="flex items-center justify-center h-full p-6">
                  <div className="text-center">
                    <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
                      <span className="text-white text-2xl">👋</span>
                    </div>
                    <h3 className="text-white font-medium mb-2">
                      Welcome to OrbiQuant Copilot
                    </h3>
                    <p className="text-gray-400 text-sm">
                      I&apos;m your AI trading assistant. Ask me about market analysis,
                      trading strategies, or anything trading-related!
                    </p>
                    <div className="mt-6 space-y-2 text-left">
                      <div className="text-xs text-gray-500 font-medium">Try asking:</div>
                      <div className="text-sm text-gray-400">
                        • &quot;What&apos;s the current trend for BTC?&quot;
                      </div>
                      <div className="text-sm text-gray-400">
                        • &quot;Analyze ETH/USDT for me&quot;
                      </div>
                      <div className="text-sm text-gray-400">
                        • &quot;What are good entry points for AAPL?&quot;
                      </div>
                    </div>
                  </div>
                </div>
              ) : (
                <div className="py-2">
                  {messages.map((message) => (
                    <ChatMessage key={message.id} message={message} />
                  ))}

                  {/* Loading indicator */}
                  {loading && (
                    <div className="flex gap-3 py-4 px-4">
                      <div className="flex-shrink-0 w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center">
                        <span className="text-white text-xs">AI</span>
                      </div>
                      <div className="flex-1">
                        <div className="bg-gray-800 rounded-lg px-4 py-3 inline-block">
                          <div className="flex gap-1">
                            <div className="w-2 h-2 bg-gray-500 rounded-full animate-bounce" />
                            <div
                              className="w-2 h-2 bg-gray-500 rounded-full animate-bounce"
                              style={{ animationDelay: '0.1s' }}
                            />
                            <div
                              className="w-2 h-2 bg-gray-500 rounded-full animate-bounce"
                              style={{ animationDelay: '0.2s' }}
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Scroll anchor */}
                  <div ref={messagesEndRef} />
                </div>
              )}
            </div>

            {/* Input */}
            <ChatInput
              onSendMessage={sendMessage}
              disabled={!currentSessionId && loading}
              loading={loading}
            />
          </>
        )}
      </div>
    </>
  );
};

export default ChatPanel;
