'use client';

import * as React from 'react';
import { ChatLayout } from '@/features/chat/chat-layout';
import { ConversationSidebar } from '@/features/chat/conversation-sidebar';
import { MessageBubble } from '@/features/chat/message-bubble';
import { ChatInput } from '@/features/chat/chat-input';
// EN: Lazy load typing indicator / VI: Lazy load typing indicator
const TypingIndicator = React.lazy(() => import('@/features/chat/typing-indicator').then(m => ({ default: m.TypingIndicator })));
import { LiveRegion } from '@/features/shared/components/accessibility/live-region';
import { useKeyboardShortcuts, CHAT_SHORTCUTS } from '@/shared/hooks/use-keyboard-shortcuts';
import { useChatStore, MessageSender } from '@/stores/chat-store';
import { useTranslations } from 'next-intl';

/**
 * EN: Chat page component - Main chat interface
 * VI: Component trang chat - Giao diện chat chính
 *
 * Features:
 * - Chat layout with sidebar and main area
 * - Message display with user/AI variants
 * - Chat input with auto-resize
 * - Typing indicator
 * - Keyboard shortcuts
 * - Screen reader announcements
 *
 * Tính năng:
 * - Layout chat với sidebar và khu vực chính
 * - Hiển thị tin nhắn với các biến thể user/AI
 * - Input chat với auto-resize
 * - Typing indicator
 * - Phím tắt bàn phím
 * - Thông báo screen reader
 */
export default function ChatPage() {
  // EN: Translation hook / VI: Hook translation
  const t = useTranslations();

  const [sidebarVisible, setSidebarVisible] = React.useState(true);
  const [announcement, setAnnouncement] = React.useState<string>('');

  // EN: Get chat state from store / VI: Lấy state chat từ store
  const {
    messages,
    conversations,
    currentConversationId,
    sendMessage,
    selectConversation,
    createConversation,
  } = useChatStore();

  // EN: Get current conversation messages / VI: Lấy tin nhắn của conversation hiện tại
  const currentMessages = React.useMemo(() => {
    if (!currentConversationId) return [];
    return messages[currentConversationId] || [];
  }, [messages, currentConversationId]);

  // EN: Handle send message / VI: Xử lý gửi tin nhắn
  const handleSend = async (content: string) => {
    let conversationId = currentConversationId;
    if (!conversationId) {
      // EN: Create new conversation if none selected / VI: Tạo conversation mới nếu chưa chọn
      conversationId = createConversation();
    }
    try {
      await sendMessage(conversationId, content);
      setAnnouncement(t('chat.messageSent'));
    } catch (error) {
      setAnnouncement(t('chat.messageSendFailed'));
    }
  };

  // EN: Handle new chat / VI: Xử lý chat mới
  const handleNewChat = () => {
    createConversation();
    setAnnouncement(t('chat.newConversationCreated'));
  };

  // EN: Handle select conversation / VI: Xử lý chọn conversation
  const handleSelectConversation = (conversationId: string) => {
    selectConversation(conversationId);
    setAnnouncement(t('chat.switchedToConversation'));
  };

  // EN: Keyboard shortcuts / VI: Phím tắt bàn phím
  useKeyboardShortcuts([
    {
      key: CHAT_SHORTCUTS.NEW_CHAT,
      handler: () => handleNewChat(),
      description: t('chat.newChat'),
      preventDefault: true,
    },
    {
      key: CHAT_SHORTCUTS.SEARCH,
      handler: () => {
        // EN: Focus search input / VI: Focus input tìm kiếm
        const searchInput = document.querySelector('input[type="search"]') as HTMLInputElement;
        searchInput?.focus();
      },
      description: t('chat.openSearch'),
      preventDefault: true,
    },
  ]);

  return (
    <>
      <LiveRegion message={announcement} priority="polite" />
      <ChatLayout
        sidebar={
          <ConversationSidebar
            conversations={conversations.map((conv) => ({
              id: conv.id,
              title: conv.title,
              lastMessage: conv.lastMessage?.content,
              lastMessageAt: conv.lastMessage ? new Date(conv.lastMessage.createdAt) : undefined,
              isSelected: conv.id === currentConversationId,
            }))}
            selectedConversationId={currentConversationId || undefined}
            onSelectConversation={handleSelectConversation}
            onNewChat={handleNewChat}
          />
        }
        sidebarVisible={sidebarVisible}
        onSidebarToggle={setSidebarVisible}
      >
        {/* EN: Messages container / VI: Container tin nhắn */}
        <div className="flex-1 overflow-y-auto p-4 space-y-4" role="log" aria-label={t('chat.messages')}>
          {currentMessages.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full text-center">
              <p className="text-text-tertiary text-lg mb-2">
                {t('chat.startConversation')}
              </p>
              <p className="text-text-tertiary text-sm">
                {t('chat.startConversationDesc')}
              </p>
            </div>
          ) : (
            currentMessages.map((message) => (
              <MessageBubble
                key={message.id}
                sender={message.sender === MessageSender.USER ? 'user' : message.sender === MessageSender.ASSISTANT ? 'ai' : 'system'}
                content={message.content}
                timestamp={new Date(message.createdAt)}
                showActions
                onCopy={() => {
                  navigator.clipboard.writeText(message.content);
                  setAnnouncement(t('chat.messageCopied'));
                }}
              />
            ))
          )}
          {/* EN: Typing indicator / VI: Typing indicator */}
          {(() => {
            const { typingUsers } = useChatStore.getState();
            return Object.values(typingUsers).some((typing) => typing) ? (
              <React.Suspense fallback={<div className="px-4 py-3" aria-label={t('chat.loadingTypingIndicator')} />}>
                <TypingIndicator />
              </React.Suspense>
            ) : null;
          })()}
        </div>

        {/* EN: Chat input / VI: Chat input */}
        <ChatInput
          onSend={handleSend}
          placeholder={t('chat.typeMessage')}
        />
      </ChatLayout>
    </>
  );
}
