/**
 * Assistant Page
 * Full-page LLM trading copilot with conversation history and context
 */

import React, { useEffect, useRef, useCallback } from 'react';
import {
  SparklesIcon,
  Cog6ToothIcon,
  TrashIcon,
  ArrowPathIcon,
  Bars3Icon,
  XMarkIcon,
} from '@heroicons/react/24/outline';
import ChatMessage from '../components/ChatMessage';
import ChatInput from '../components/ChatInput';
import SignalCard, { TradingSignal } from '../components/SignalCard';
import ConversationHistory from '../components/ConversationHistory';
import ContextPanel from '../components/ContextPanel';
import { useChatStore } from '../../../stores/chatStore';
// TODO: Integrate with tradingStore for real watchlist data
// import { useTradingStore } from '../../../stores/tradingStore';

// Mock watchlist data (would come from tradingStore in production)
const mockWatchlist = [
  { symbol: 'BTC/USD', name: 'Bitcoin', price: 43250.00, change: 2.34 },
  { symbol: 'ETH/USD', name: 'Ethereum', price: 2280.50, change: -1.12 },
  { symbol: 'XAUUSD', name: 'Gold', price: 2045.30, change: 0.45 },
  { symbol: 'EURUSD', name: 'Euro/Dollar', price: 1.0875, change: -0.22 },
];

const Assistant: React.FC = () => {
  // Chat store
  const {
    sessions,
    currentSessionId,
    messages,
    loading,
    error,
    loadSessions,
    loadSession,
    createNewSession,
    sendMessage,
    deleteSession,
    clearError,
  } = useChatStore();

  // UI State
  const [showSidebar, setShowSidebar] = React.useState(true);
  const [showContext, setShowContext] = React.useState(true);
  const [signal, setSignal] = React.useState<TradingSignal | null>(null);
  const [riskProfile, setRiskProfile] = React.useState<'conservative' | 'moderate' | 'aggressive'>('moderate');
  const [isStreaming, setIsStreaming] = React.useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // Load sessions on mount
  useEffect(() => {
    loadSessions();
  }, [loadSessions]);

  // Scroll to bottom on new messages
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // Handle send message
  const handleSendMessage = useCallback(async (content: string) => {
    if (!content.trim()) return;
    await sendMessage(content);
  }, [sendMessage]);

  // Stop streaming (for future SSE implementation)
  const stopStreaming = useCallback(() => {
    setIsStreaming(false);
  }, []);

  // Clear current conversation
  const clearConversation = useCallback(() => {
    createNewSession();
    setSignal(null);
  }, [createNewSession]);

  // Handle trade from signal card
  const handleTrade = useCallback((sig: TradingSignal) => {
    window.location.href = `/trading?symbol=${sig.symbol}&signal=${sig.signal_id}`;
  }, []);

  // Handle session selection
  const handleSelectSession = useCallback((sessionId: string) => {
    loadSession(sessionId);
  }, [loadSession]);

  // Handle session deletion
  const handleDeleteSession = useCallback((sessionId: string) => {
    deleteSession(sessionId);
  }, [deleteSession]);

  // Convert store messages to component format
  const displayMessages = messages.map((msg) => ({
    id: msg.id,
    role: msg.role,
    content: msg.content,
    timestamp: new Date(msg.timestamp),
    tools_used: msg.toolsUsed,
  }));

  // Add welcome message if no messages
  const allMessages = displayMessages.length === 0
    ? [{
        id: 'welcome',
        role: 'assistant' as const,
        content: 'Hola! Soy tu asistente de trading OrbiQuant AI. Puedo ayudarte con:\n\n- **Analisis de mercado**: Senales y analisis para cualquier simbolo\n- **Tu portfolio**: Revisa tus posiciones y P&L\n- **Educacion**: Aprende sobre indicadores, patrones y estrategias\n- **Fases AMD**: Entiende los ciclos del mercado\n\nQue te gustaria saber?',
        timestamp: new Date(),
        tools_used: [],
      }]
    : displayMessages;

  return (
    <div className="h-[calc(100vh-64px)] flex bg-gray-50 dark:bg-gray-900">
      {/* Sidebar - Conversation History */}
      <div
        className={`${
          showSidebar ? 'w-72' : 'w-0'
        } transition-all duration-300 overflow-hidden bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 flex-shrink-0`}
      >
        <ConversationHistory
          sessions={sessions}
          currentSessionId={currentSessionId}
          loading={loading}
          onSelectSession={handleSelectSession}
          onCreateSession={createNewSession}
          onDeleteSession={handleDeleteSession}
        />
      </div>

      {/* Main Chat Area */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* Header */}
        <div className="flex items-center justify-between px-4 py-3 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-3">
            <button
              onClick={() => setShowSidebar(!showSidebar)}
              className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors lg:hidden"
            >
              {showSidebar ? (
                <XMarkIcon className="w-5 h-5" />
              ) : (
                <Bars3Icon className="w-5 h-5" />
              )}
            </button>
            <div className="w-10 h-10 rounded-full bg-gradient-to-r from-cyan-500 to-blue-500 flex items-center justify-center">
              <SparklesIcon className="w-6 h-6 text-white" />
            </div>
            <div>
              <h1 className="font-bold text-gray-900 dark:text-white">OrbiQuant AI</h1>
              <p className="text-xs text-gray-500">Trading Copilot</p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setShowSidebar(!showSidebar)}
              className="hidden lg:flex p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              title={showSidebar ? 'Ocultar historial' : 'Mostrar historial'}
            >
              <Bars3Icon className="w-5 h-5" />
            </button>
            <button
              onClick={() => setShowContext(!showContext)}
              className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              title={showContext ? 'Ocultar contexto' : 'Mostrar contexto'}
            >
              <Cog6ToothIcon className="w-5 h-5" />
            </button>
            <button
              onClick={clearConversation}
              className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              title="Nueva conversacion"
            >
              <TrashIcon className="w-5 h-5" />
            </button>
            <button
              className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
              title="Regenerar respuesta"
            >
              <ArrowPathIcon className="w-5 h-5" />
            </button>
          </div>
        </div>

        {/* Error Banner */}
        {error && (
          <div className="mx-4 mt-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg flex items-center justify-between">
            <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
            <button
              onClick={clearError}
              className="text-red-500 hover:text-red-700 p-1"
            >
              <XMarkIcon className="w-4 h-4" />
            </button>
          </div>
        )}

        {/* Messages Area */}
        <div className="flex-1 overflow-y-auto">
          <div className="max-w-3xl mx-auto p-4">
            {/* Context Panel (collapsible) */}
            {showContext && (
              <div className="mb-4">
                <ContextPanel
                  watchlist={mockWatchlist}
                  riskProfile={riskProfile}
                  preferredSymbols={['BTC/USD', 'XAUUSD', 'EURUSD']}
                  onRiskProfileChange={setRiskProfile}
                />
              </div>
            )}

            {/* Messages */}
            {allMessages.map((message) => (
              <ChatMessage
                key={message.id}
                message={message}
              />
            ))}

            {/* Loading indicator */}
            {loading && (
              <div className="flex justify-start mb-4">
                <div className="bg-gray-100 dark:bg-gray-800 rounded-2xl rounded-bl-sm px-4 py-3">
                  <div className="flex items-center gap-2">
                    <div className="flex gap-1">
                      <span className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0ms' }} />
                      <span className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
                      <span className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
                    </div>
                    <span className="text-sm text-gray-500">Pensando...</span>
                  </div>
                </div>
              </div>
            )}

            {/* Signal Card (if present) */}
            {signal && (
              <div className="my-4">
                <SignalCard signal={signal} onTrade={handleTrade} />
              </div>
            )}

            <div ref={messagesEndRef} />
          </div>
        </div>

        {/* Input */}
        <ChatInput
          onSendMessage={handleSendMessage}
          onStopStreaming={stopStreaming}
          isLoading={loading}
          isStreaming={isStreaming}
          placeholder={`Pregunta sobre ${mockWatchlist[0]?.symbol || 'cualquier simbolo'}...`}
        />
      </div>
    </div>
  );
};

export default Assistant;
