/**
 * ConversationList -- Shows all workspace workflows/conversations.
 *
 * Features: filter, rename (double-click), delete, archive, create new,
 * pagination (20 per page), last-activity display.
 */

import React, { useState, useEffect, useCallback, useRef } from 'react';
import api from '../../../api';

const _PAGE_SIZE = 20;

interface Conversation {
  id: string;
  name: string;
  status: string;
  startedAt?: number;
  lastActivity?: number;
}

interface ConversationListProps {
  instanceId: string;
  activeWorkflowId: string | null;
  onSelect: (workflowId: string) => void;
  onCreateNew?: () => void;
  refreshTrigger?: number;
}

export const ConversationList: React.FC<ConversationListProps> = ({
  instanceId,
  activeWorkflowId,
  onSelect,
  onCreateNew,
  refreshTrigger,
}) => {
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [loading, setLoading] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editName, setEditName] = useState('');
  const [filterQuery, setFilterQuery] = useState('');
  const [page, setPage] = useState(0);
  const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
  const [viewMode, setViewMode] = useState<'active' | 'archived'>('active');
  const inputRef = useRef<HTMLInputElement>(null);

  const _loadConversations = useCallback(() => {
    if (!instanceId) return;
    setLoading(true);
    api.get(`/api/workspace/${instanceId}/workflows`, { params: { includeArchived: true } })
      .then(res => {
        const items = (res.data.workflows || res.data || [])
          .map((w: any) => ({
            id: w.id,
            name: w.name || w.label || 'Untitled',
            status: w.status || 'unknown',
            startedAt: w.startedAt || w.createdAt,
            lastActivity: w.lastActivity || w.updatedAt || w.startedAt,
          }))
          .sort((a: Conversation, b: Conversation) =>
            (b.lastActivity || 0) - (a.lastActivity || 0),
          );
        setConversations(items);
      })
      .catch(() => setConversations([]))
      .finally(() => setLoading(false));
  }, [instanceId]);

  useEffect(() => {
    _loadConversations();
  }, [_loadConversations]);

  useEffect(() => {
    if (refreshTrigger) _loadConversations();
  }, [refreshTrigger, _loadConversations]);

  useEffect(() => {
    if (activeWorkflowId && !conversations.find(c => c.id === activeWorkflowId)) {
      _loadConversations();
    }
  }, [activeWorkflowId, conversations, _loadConversations]);

  useEffect(() => {
    if (editingId && inputRef.current) {
      inputRef.current.focus();
      inputRef.current.select();
    }
  }, [editingId]);

  const _formatTime = (ts?: number): string => {
    if (!ts) return '';
    const d = new Date(ts * 1000);
    const now = new Date();
    const diffMs = now.getTime() - d.getTime();
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
    if (diffDays === 0) {
      return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    }
    if (diffDays === 1) return 'Gestern';
    if (diffDays < 7) return `vor ${diffDays}d`;
    return d.toLocaleDateString([], { month: 'short', day: 'numeric' });
  };

  const _formatDate = (ts?: number): string => {
    if (!ts) return '';
    const d = new Date(ts * 1000);
    return d.toLocaleDateString([], { day: '2-digit', month: '2-digit', year: 'numeric' })
      + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };

  const _startEditing = (conv: Conversation) => {
    setEditingId(conv.id);
    setEditName(conv.name);
  };

  const _commitRename = (convId: string) => {
    const trimmed = editName.trim();
    if (!trimmed) {
      setEditingId(null);
      return;
    }
    setConversations(prev =>
      prev.map(c => c.id === convId ? { ...c, name: trimmed } : c),
    );
    setEditingId(null);
    api.patch(`/api/workspace/${instanceId}/workflows/${convId}`, { name: trimmed })
      .catch(() => _loadConversations());
  };

  const _handleKeyDown = (e: React.KeyboardEvent, convId: string) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      _commitRename(convId);
    } else if (e.key === 'Escape') {
      setEditingId(null);
    }
  };

  const _handleDelete = (convId: string) => {
    setConversations(prev => prev.filter(c => c.id !== convId));
    if (activeWorkflowId === convId) onSelect('');
    api.delete(`/api/workspace/${instanceId}/workflows/${convId}`)
      .catch(() => _loadConversations());
  };

  const _handleArchive = (convId: string) => {
    setConversations(prev => prev.map(c =>
      c.id === convId ? { ...c, status: 'archived' } : c,
    ));
    api.patch(`/api/workspace/${instanceId}/workflows/${convId}`, { status: 'archived' })
      .catch(() => _loadConversations());
  };

  const _handleReactivate = (convId: string) => {
    setConversations(prev => prev.map(c =>
      c.id === convId ? { ...c, status: 'active' } : c,
    ));
    api.patch(`/api/workspace/${instanceId}/workflows/${convId}`, { status: 'active' })
      .catch(() => _loadConversations());
  };

  const _handleCreateNew = () => {
    if (onCreateNew) onCreateNew();
  };

  const _filtered = (items: Conversation[], query: string): Conversation[] => {
    if (!query.trim()) return items;
    const q = query.toLowerCase();
    return items.filter(c =>
      c.name.toLowerCase().includes(q) || c.status.toLowerCase().includes(q),
    );
  };

  const _byStatus = viewMode === 'archived'
    ? conversations.filter(c => c.status === 'archived')
    : conversations.filter(c => c.status !== 'archived');
  const filtered = _filtered(_byStatus, filterQuery);
  const totalPages = Math.ceil(filtered.length / _PAGE_SIZE);
  const paginated = filtered.slice(page * _PAGE_SIZE, (page + 1) * _PAGE_SIZE);

  const _archivedCount = conversations.filter(c => c.status === 'archived').length;
  const _activeCount = conversations.filter(c => c.status !== 'archived').length;

  useEffect(() => { setPage(0); }, [filterQuery, viewMode]);

  return (
    <div style={{ padding: 8 }}>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <span style={{ fontSize: 12, fontWeight: 600, color: '#666', textTransform: 'uppercase' }}>Conversations</span>
        <div style={{ display: 'flex', gap: 4 }}>
          <button
            onClick={_handleCreateNew}
            style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 14, color: '#1976d2' }}
            title="Neuer Chat"
          >
            +
          </button>
          <button
            onClick={_loadConversations}
            disabled={loading}
            style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 12, color: '#1976d2' }}
          >
            {loading ? '...' : '\u21BB'}
          </button>
        </div>
      </div>

      {/* View mode toggle */}
      <div style={{ display: 'flex', marginBottom: 8, borderRadius: 6, overflow: 'hidden', border: '1px solid #ddd' }}>
        <button
          onClick={() => setViewMode('active')}
          style={{
            flex: 1, padding: '5px 0', fontSize: 11, fontWeight: 600, border: 'none', cursor: 'pointer',
            background: viewMode === 'active' ? 'var(--primary-color, #1976d2)' : 'transparent',
            color: viewMode === 'active' ? '#fff' : '#888',
            transition: 'background 0.15s, color 0.15s',
          }}
        >
          Aktiv {_activeCount > 0 && <span style={{ fontWeight: 400 }}>({_activeCount})</span>}
        </button>
        <button
          onClick={() => setViewMode('archived')}
          style={{
            flex: 1, padding: '5px 0', fontSize: 11, fontWeight: 600, border: 'none', cursor: 'pointer',
            borderLeft: '1px solid #ddd',
            background: viewMode === 'archived' ? '#ff9800' : 'transparent',
            color: viewMode === 'archived' ? '#fff' : '#888',
            transition: 'background 0.15s, color 0.15s',
          }}
        >
          Archiv {_archivedCount > 0 && <span style={{ fontWeight: 400 }}>({_archivedCount})</span>}
        </button>
      </div>

      {/* Filter */}
      {filtered.length > 3 && (
        <input
          type="text"
          placeholder="Filter chats..."
          value={filterQuery}
          onChange={e => setFilterQuery(e.target.value)}
          style={{
            width: '100%', padding: '6px 10px', fontSize: 12, borderRadius: 4,
            border: '1px solid #ddd', marginBottom: 8, boxSizing: 'border-box',
          }}
        />
      )}

      {/* Empty state */}
      {filtered.length === 0 && !loading && (
        <div style={{ fontSize: 12, color: '#999', textAlign: 'center', padding: 16 }}>
          {viewMode === 'archived'
            ? 'Keine archivierten Chats.'
            : 'Noch keine Chats. Sende eine Nachricht oder klicke "+".'}
        </div>
      )}

      {/* List */}
      {paginated.map(conv => {
        const isActive = conv.id === activeWorkflowId;
        const isEditing = editingId === conv.id;
        return (
          <div
            key={conv.id}
            onClick={() => { if (!isEditing) onSelect(conv.id); }}
            style={{
              padding: '8px 10px',
              marginBottom: 4,
              borderRadius: 6,
              cursor: isEditing ? 'default' : 'pointer',
              background: isActive ? 'var(--primary-light, #e3f2fd)' : 'transparent',
              border: isActive ? '1px solid var(--primary-color, #1976d2)20' : '1px solid transparent',
              transition: 'background 0.15s',
              position: 'relative',
            }}
            onMouseEnter={e => {
              if (!isActive) e.currentTarget.style.background = '#f5f5f5';
              const actions = e.currentTarget.querySelector('[data-actions]') as HTMLElement;
              if (actions) actions.style.opacity = '1';
            }}
            onMouseLeave={e => {
              if (!isActive) e.currentTarget.style.background = 'transparent';
              const actions = e.currentTarget.querySelector('[data-actions]') as HTMLElement;
              if (actions) actions.style.opacity = '0';
              if (confirmDeleteId === conv.id) setConfirmDeleteId(null);
            }}
          >
            {/* Name row */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 4 }}>
              {isEditing ? (
                <input
                  ref={inputRef}
                  value={editName}
                  onChange={e => setEditName(e.target.value)}
                  onBlur={() => _commitRename(conv.id)}
                  onKeyDown={e => _handleKeyDown(e, conv.id)}
                  onClick={e => e.stopPropagation()}
                  style={{
                    flex: 1, minWidth: 0, fontSize: 13, fontWeight: 600,
                    padding: '1px 4px', borderRadius: 3,
                    border: '1px solid var(--primary-color, #1976d2)',
                    outline: 'none', background: '#fff',
                  }}
                />
              ) : (
                <>
                  <span
                    style={{ fontSize: 10, color: '#aaa', flexShrink: 0, marginRight: 6 }}
                    title={_formatDate(conv.lastActivity)}
                  >
                    {_formatTime(conv.lastActivity)}
                  </span>
                  <span
                    style={{
                      fontSize: 13,
                      fontWeight: isActive ? 600 : 400,
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                      flex: 1,
                      minWidth: 0,
                    }}
                    onDoubleClick={(e) => { e.stopPropagation(); _startEditing(conv); }}
                    title={conv.name}
                  >
                    {conv.name}
                  </span>
                </>
              )}

              {/* Action buttons (visible on hover) */}
              {!isEditing && (
                <span
                  data-actions=""
                  style={{ display: 'flex', gap: 2, opacity: 0, transition: 'opacity 0.15s', flexShrink: 0 }}
                >
                  <button
                    onClick={e => { e.stopPropagation(); _startEditing(conv); }}
                    style={_actionBtnStyle}
                    title="Umbenennen"
                  >
                    &#x270E;
                  </button>
                  {conv.status === 'archived' ? (
                    <button
                      onClick={e => { e.stopPropagation(); _handleReactivate(conv.id); }}
                      style={{ ..._actionBtnStyle, color: '#4caf50' }}
                      title="Reaktivieren"
                    >
                      &#x21A9;
                    </button>
                  ) : (
                    <button
                      onClick={e => { e.stopPropagation(); _handleArchive(conv.id); }}
                      style={_actionBtnStyle}
                      title="Archivieren"
                    >
                      &#x1F4E6;
                    </button>
                  )}
                  {confirmDeleteId === conv.id ? (
                    <span style={{
                      display: 'inline-flex', gap: 1, background: 'var(--color-secondary, #555)',
                      borderRadius: 12, padding: '1px 2px', alignItems: 'center',
                    }}>
                      <button
                        onClick={e => { e.stopPropagation(); setConfirmDeleteId(null); _handleDelete(conv.id); }}
                        style={{ ..._actionBtnStyle, color: '#fff', fontSize: 13 }}
                        title="Ja, loeschen"
                      >
                        &#x2713;
                      </button>
                      <button
                        onClick={e => { e.stopPropagation(); setConfirmDeleteId(null); }}
                        style={{ ..._actionBtnStyle, color: '#fff', fontSize: 13 }}
                        title="Abbrechen"
                      >
                        &#x2717;
                      </button>
                    </span>
                  ) : (
                    <button
                      onClick={e => { e.stopPropagation(); setConfirmDeleteId(conv.id); }}
                      style={{ ..._actionBtnStyle, color: '#d32f2f' }}
                      title="Loeschen"
                    >
                      &#x1F5D1;
                    </button>
                  )}
                </span>
              )}
            </div>

          </div>
        );
      })}

      {/* Pagination */}
      {totalPages > 1 && (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8, marginTop: 8, fontSize: 12 }}>
          <button
            onClick={() => setPage(p => Math.max(0, p - 1))}
            disabled={page === 0}
            style={{ ..._pageBtnStyle, opacity: page === 0 ? 0.3 : 1 }}
          >
            &lt;
          </button>
          <span style={{ color: '#888' }}>{page + 1} / {totalPages}</span>
          <button
            onClick={() => setPage(p => Math.min(totalPages - 1, p + 1))}
            disabled={page >= totalPages - 1}
            style={{ ..._pageBtnStyle, opacity: page >= totalPages - 1 ? 0.3 : 1 }}
          >
            &gt;
          </button>
        </div>
      )}
    </div>
  );
};

const _actionBtnStyle: React.CSSProperties = {
  background: 'none',
  border: 'none',
  cursor: 'pointer',
  fontSize: 11,
  color: '#999',
  padding: '0 2px',
};

const _pageBtnStyle: React.CSSProperties = {
  background: 'none',
  border: '1px solid #ddd',
  borderRadius: 4,
  cursor: 'pointer',
  padding: '2px 8px',
  color: '#666',
};
