/**
 * ChatbotConversationsView
 * 
 * Chatbot interface with chat history sidebar and messages view.
 * Similar to trustee views but hardcoded for chatbot feature.
 */

import React, { useState, useCallback } from 'react';
import { useChatbot } from '../../../hooks/useChatbot';
import { useConfirm } from '../../../hooks/useConfirm';
import { TextField } from '../../../components/UiComponents/TextField';
import { Button } from '../../../components/UiComponents/Button';
import { AutoScroll } from '../../../components/UiComponents/AutoScroll';
import { ChatMessage } from '../../../components/UiComponents/Messages/ChatMessages/ChatMessage';
import { formatUnixTimestamp } from '../../../utils/time';
import { IoMdSend } from 'react-icons/io';
import { MdStop } from 'react-icons/md';
import { LuMessageSquare, LuTrash2 } from 'react-icons/lu';
import messagesStyles from '../../../components/UiComponents/Messages/Messages.module.css';
import styles from './ChatbotViews.module.css';

import { useLanguage } from '../../../providers/language/LanguageContext';

export const ChatbotConversationsView: React.FC = () => {
    const { t } = useLanguage();

  const {
    threads,
    selectedThreadId,
    loadingThreads,
    error,
    messages,
    loadingMessages,
    isStreaming,
    streamingStatus,
    currentWorkflowId,
    selectThread,
    createNewThread,
    sendMessage,
    stopStreaming,
    deleteThread,
    refreshThreads,
    inputValue,
    setInputValue
  } = useChatbot();
  
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const { confirm, ConfirmDialog } = useConfirm();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!inputValue.trim() || isStreaming) return;
    await sendMessage(inputValue);
  };
  
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    // Enter ohne Shift sendet die Nachricht
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (!inputValue.trim() || isStreaming) return;
      sendMessage(inputValue);
    }
  };
  
  const handleStop = async () => {
    console.log('Stop button clicked', { 
      isStreaming, 
      currentWorkflowId,
      selectedThreadId,
      hasMessages: messages.length > 0
    });
    if (isStreaming) {
      console.log('Calling stopStreaming...');
      try {
        await stopStreaming();
        console.log('stopStreaming completed');
      } catch (error) {
        console.error('Error in stopStreaming:', error);
      }
    } else {
      console.warn('Stop button clicked but not streaming');
    }
  };
  
  const handleDeleteThread = useCallback(async (e: React.MouseEvent, workflowId: string) => {
    e.stopPropagation();
    const ok = await confirm(t('Möchten Sie diese Konversation wirklich löschen?'), {
      title: t('Konversation löschen'),
      confirmLabel: t('Löschen'),
      variant: 'danger',
    });
    if (!ok) return;
    setDeletingId(workflowId);
    try {
      await deleteThread(workflowId);
    } finally {
      setDeletingId(null);
    }
  }, [confirm, deleteThread, t]);
  
  const formatDate = (timestamp?: number) => {
    if (!timestamp) return '';
    // Convert Unix timestamp (seconds) to milliseconds using the time utility logic
    const milliseconds = timestamp * 1000;
    const date = new Date(milliseconds);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);
    
    if (diffMins < 1) return t('Gerade eben');
    if (diffMins < 60) return t('Vor {n} Min', { n: diffMins });
    if (diffHours < 24) return t('Vor {n} Std', { n: diffHours });
    if (diffDays < 7) return t('Vor {n} Tagen', { n: diffDays });
    
    // For older dates, use the formatUnixTimestamp utility for consistent formatting
    const { time } = formatUnixTimestamp(timestamp, 'de-DE', { 
      day: '2-digit', 
      month: '2-digit', 
      year: 'numeric' 
    });
    return time;
  };
  
  const getThreadTitle = (thread: any) => {
    if (thread.name) return thread.name;
    // Try to get first message content as title
    return t('Neue Konversation');
  };
  
  return (
    <div className={styles.chatbotView}>
      {/* Chat History Sidebar */}
      <aside className={styles.chatHistory} aria-label={t('Konversationen')}>
        <div className={styles.chatHistoryHeader} style={{ justifyContent: 'flex-end' }}>
          <button
            className={styles.newChatButton}
            onClick={createNewThread}
            title={t('Neues Gespräch')}
          >
            <LuMessageSquare /> {t('Neu')}
          </button>
        </div>
        
        {loadingThreads ? (
          <div className={styles.loading}>
            <div className={styles.spinner} />
            <span>{t('Konversationen laden')}</span>
          </div>
        ) : error ? (
          <div className={styles.error}>
            <p>{error}</p>
            <button className={styles.retryButton} onClick={refreshThreads}>
              {t('Erneut versuchen')}
            </button>
          </div>
        ) : threads.length === 0 ? (
          <div className={styles.emptyState}>
            <LuMessageSquare className={styles.emptyIcon} />
            <p>{t('Noch keine Gespräche')}</p>
            <p className={styles.emptyHint}>{t('Starten Sie ein neues Gespräch, um loszulegen.')}</p>
          </div>
        ) : (
          <div className={styles.threadList}>
            {threads.map((thread) => (
              <div
                key={thread.id}
                className={`${styles.threadItem} ${selectedThreadId === thread.id ? styles.selected : ''}`}
                onClick={() => selectThread(thread.id)}
              >
                <div className={styles.threadContent}>
                  <div className={styles.threadTitle}>{getThreadTitle(thread)}</div>
                  <div className={styles.threadMeta}>
                    {formatDate(thread.lastActivity || thread.startedAt)}
                  </div>
                </div>
                <button
                  className={styles.deleteButton}
                  onClick={(e) => handleDeleteThread(e, thread.id)}
                  disabled={deletingId === thread.id}
                  title={t('Löschen')}
                >
                  {deletingId === thread.id ? (
                    <div className={styles.spinner} />
                  ) : (
                    <LuTrash2 />
                  )}
                </button>
              </div>
            ))}
          </div>
        )}
      </aside>
      
      {/* Main Chat Area */}
      <main className={styles.chatArea}>
        {/* Messages Area */}
        <div className={styles.messagesArea}>
          {loadingMessages && messages.length === 0 ? (
            <div className={styles.loading}>
              <div className={styles.spinner} />
              <span>{t('Nachrichten laden')}</span>
            </div>
          ) : messages.length === 0 ? (
            <div className={`${messagesStyles.messagesContainer} ${messagesStyles.emptyContainer}`}>
              <div className={messagesStyles.emptyState}>
                {t('Noch keine Nachrichten. Starte eine Konversation!')}
              </div>
            </div>
          ) : (
            <AutoScroll
              scrollDependency={messages.length + (isStreaming ? 1 : 0)}
            >
              <div className={messagesStyles.messagesContainer}>
                {messages.map((message) => (
                  <ChatMessage
                    key={message.id}
                    message={message}
                    showDocuments={true}
                  />
                ))}
                {isStreaming && (
                  <div className={styles.typingIndicator}>
                    <div className={styles.typingBubble}>
                      {streamingStatus ? (
                        <div className={styles.streamingStatus}>
                          <div className={styles.statusSpinner} />
                          <span className={styles.statusText}>{streamingStatus}</span>
                        </div>
                      ) : (
                        <div className={styles.typingDots}>
                          <span></span>
                          <span></span>
                          <span></span>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </AutoScroll>
          )}
        </div>
        
        {/* Input Form */}
        <form onSubmit={handleSubmit} className={styles.inputForm}>
          <TextField
            value={inputValue}
            onChange={setInputValue}
            onKeyDown={handleKeyDown}
            placeholder={t('Nachricht eingeben')}
            disabled={isStreaming}
            className={styles.inputField}
            size="md"
          />
          {isStreaming ? (
            <Button
              type="button"
              onClick={handleStop}
              variant="danger"
              size="md"
              icon={MdStop}
              disabled={!isStreaming}
            >
              Stoppen
            </Button>
          ) : (
            <Button
              type="submit"
              disabled={!inputValue.trim() || isStreaming}
              variant="primary"
              size="md"
              icon={IoMdSend}
            >
              Senden
            </Button>
          )}
        </form>
      </main>
      <ConfirmDialog />
    </div>
  );
};

export default ChatbotConversationsView;
