import { Button, Empty, Input, List, Spin, Typography } from 'antd';
import type { ChatConversationSummary } from '../../mainChatPanel/types';
import { shouldShowPrimaryConversation } from '../../chatSessionRouting';

const { Text } = Typography;


type ConversationListPaneProps = {
  items: ChatConversationSummary[];
  isLoading: boolean;
  errorMessage: string;
  searchText: string;
  activeSessionId: string;
  onSearchChange: (value: string) => void;
  onSelectSession: (sessionId: string) => void;
  onCreateConversation: () => void;
};

export function ConversationListPane({
  items,
  isLoading,
  errorMessage,
  searchText,
  activeSessionId,
  onSearchChange,
  onSelectSession,
  onCreateConversation,
}: ConversationListPaneProps) {
  const visibleItems = items.filter((item) => shouldShowPrimaryConversation(item.sessionId));

  return (
    <section className="chat-v2__pane chat-v2__pane--list">
      <div className="chat-v2__pane-header">
        <div>
          <Text strong>채팅 목록</Text>
          <br />
          <Text type="secondary">{visibleItems.length}개 대화</Text>
        </div>
        <Button type="primary" onClick={onCreateConversation}>
          새 채팅
        </Button>
      </div>

      <Input.Search
        value={searchText}
        placeholder="채팅방 검색"
        allowClear
        onChange={(event) => {
          onSearchChange(event.target.value);
        }}
      />

      {isLoading ? (
        <div className="chat-v2__state">
          <Spin />
        </div>
      ) : errorMessage ? (
        <div className="chat-v2__state">
          <Text type="danger">{errorMessage}</Text>
        </div>
      ) : visibleItems.length === 0 ? (
        <div className="chat-v2__state">
          <Empty description="대화가 없습니다." />
        </div>
      ) : (
        <List
          className="chat-v2__conversation-list"
          dataSource={visibleItems}
          renderItem={(item) => (
            <List.Item>
              <button
                type="button"
                className={
                  item.sessionId === activeSessionId
                    ? 'chat-v2__conversation-item chat-v2__conversation-item--active'
                    : 'chat-v2__conversation-item'
                }
                onClick={() => {
                  onSelectSession(item.sessionId);
                }}
              >
                <span className="chat-v2__conversation-title">{item.title || item.sessionId}</span>
                <span className="chat-v2__conversation-preview">{item.lastMessagePreview || '대화가 아직 없습니다.'}</span>
              </button>
            </List.Item>
          )}
        />
      )}
    </section>
  );
}
