import { useRef, useEffect } from 'react';
import { MessageBubble } from './MessageBubble';
import { InputArea } from './InputArea';
import { TypingIndicator } from './TypingIndicator';
import { AgentStatusIndicator } from './AgentStatusIndicator';
import { useChatStore } from '../stores/chatStore';
import { useChat } from '../hooks/useChat';
import { MessageSquare, Menu } from 'lucide-react';

export function ChatWindow() {
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const { messages, currentConversationId, isStreaming, streamContent, sidebarOpen, toggleSidebar } = useChatStore();
  const {
    sendMessage,
    pendingFiles,
    uploadProgress,
    isUploading,
    addFiles,
    removeFile,
  } = useChat();

  // Auto-scroll to bottom
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, streamContent]);

  const currentMessages = currentConversationId
    ? messages[currentConversationId] || []
    : [];

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <header className="flex items-center justify-between px-4 py-4 border-b border-secondary-200 bg-white">
        <div className="flex items-center gap-3">
          {/* Menu toggle button - shown when sidebar is closed */}
          {!sidebarOpen && (
            <button
              onClick={toggleSidebar}
              className="p-2 hover:bg-secondary-100 rounded-lg transition-colors"
            >
              <Menu className="w-5 h-5 text-secondary-600" />
            </button>
          )}
          <div className="w-10 h-10 rounded-full bg-primary-100 flex items-center justify-center">
            <MessageSquare className="w-5 h-5 text-primary-600" />
          </div>
          <div>
            <h1 className="font-semibold text-secondary-900">香港移民咨询</h1>
            <p className="text-sm text-secondary-500">专业顾问在线为您解答</p>
          </div>
        </div>
      </header>

      {/* Messages area */}
      <div className="flex-1 overflow-y-auto px-4 py-6">
        {currentMessages.length === 0 && !isStreaming ? (
          <WelcomeMessage />
        ) : (
          <div className="max-w-3xl mx-auto space-y-4">
            {currentMessages.map((message) => (
              <MessageBubble key={message.id} message={message} />
            ))}

            {isStreaming && streamContent && (
              <MessageBubble
                message={{
                  id: 'streaming',
                  role: 'assistant',
                  content: streamContent,
                  createdAt: new Date().toISOString(),
                }}
                isStreaming
              />
            )}

            {isStreaming && !streamContent && <TypingIndicator />}

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

      {/* Agent status + Input area */}
      <div className="border-t border-secondary-200 bg-white p-4">
        <AgentStatusIndicator />
        <div className="max-w-3xl mx-auto">
          <InputArea
            onSend={sendMessage}
            disabled={isStreaming}
            onFilesSelected={addFiles}
            pendingFiles={pendingFiles}
            onRemoveFile={removeFile}
            isUploading={isUploading}
            uploadProgress={uploadProgress}
          />
        </div>
      </div>
    </div>
  );
}

function WelcomeMessage() {
  return (
    <div className="max-w-2xl mx-auto text-center py-12">
      <div className="w-16 h-16 rounded-full bg-primary-100 flex items-center justify-center mx-auto mb-6">
        <MessageSquare className="w-8 h-8 text-primary-600" />
      </div>
      <h2 className="text-2xl font-bold text-secondary-900 mb-4">
        欢迎使用 iConsulting
      </h2>
      <p className="text-secondary-600 mb-8">
        我是您的专属香港移民咨询顾问，可以为您解答关于优才计划、专才计划、高才通、投资移民等各类香港移民政策问题。
      </p>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-left">
        <SuggestionCard
          title="了解移民类别"
          description="香港有哪些移民途径？"
        />
        <SuggestionCard
          title="高才通计划"
          description="高才通的申请条件是什么？"
        />
        <SuggestionCard
          title="优才计划"
          description="优才计划如何打分？"
        />
        <SuggestionCard
          title="移民评估"
          description="我适合哪种移民方式？"
        />
      </div>
    </div>
  );
}

function SuggestionCard({ title, description }: { title: string; description: string }) {
  const { sendMessage } = useChat();

  return (
    <button
      onClick={() => sendMessage(description)}
      className="p-4 rounded-xl border border-secondary-200 bg-white hover:border-primary-300 hover:shadow-sm transition-all text-left group"
    >
      <h3 className="font-medium text-secondary-900 group-hover:text-primary-600 mb-1">
        {title}
      </h3>
      <p className="text-sm text-secondary-500">{description}</p>
    </button>
  );
}
