import React, { useState, useEffect } from 'react';
import { SearchHistoryItem, KnowledgeGroup } from '../types';
import { searchHistoryService } from '../services/searchHistoryService';
import { useToast } from '../contexts/ToastContext';
import { MessageCircle, Trash2, Clock, Users } from 'lucide-react';

interface SearchHistoryListProps {
  groups: KnowledgeGroup[];
  onSelectHistory: (historyId: string) => void;
  onDeleteHistory?: (historyId: string) => void;
}

export const SearchHistoryList: React.FC<SearchHistoryListProps> = ({
  groups,
  onSelectHistory,
  onDeleteHistory
}) => {
  const [histories, setHistories] = useState<SearchHistoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const { showToast } = useToast();

  const loadHistories = async (pageNum: number = 1, append: boolean = false) => {
    try {
      setLoading(true);
      const response = await searchHistoryService.getHistories(pageNum, 20);
      
      if (append) {
        setHistories(prev => [...prev, ...response.histories]);
      } else {
        setHistories(response.histories);
      }
      
      setHasMore(response.histories.length === 20);
      setPage(pageNum);
    } catch (error) {
      showToast('加载搜索历史失败', 'error');
    } finally {
      setLoading(false);
    }
  };

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

  const handleDelete = async (historyId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    
    if (!confirm('确定要删除这条对话历史吗？')) return;

    try {
      await searchHistoryService.deleteHistory(historyId);
      setHistories(prev => prev.filter(h => h.id !== historyId));
      onDeleteHistory?.(historyId);
      showToast('对话历史删除成功', 'success');
    } catch (error) {
      showToast('删除对话历史失败', 'error');
    }
  };

  const loadMore = () => {
    if (!loading && hasMore) {
      loadHistories(page + 1, true);
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffDays === 0) {
      return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    } else if (diffDays === 1) {
      return '昨天';
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return date.toLocaleDateString('zh-CN');
    }
  };

  const getGroupNames = (selectedGroups: string[] | null) => {
    if (!selectedGroups || selectedGroups.length === 0) {
      return '全部分组';
    }
    return selectedGroups
      .map(id => groups.find(g => g.id === id)?.name)
      .filter(Boolean)
      .join(', ');
  };

  if (loading && histories.length === 0) {
    return (
      <div className="flex items-center justify-center py-8">
        <div className="text-gray-500">加载中...</div>
      </div>
    );
  }

  if (histories.length === 0) {
    return (
      <div className="text-center py-8">
        <MessageCircle size={48} className="mx-auto text-gray-300 mb-4" />
        <div className="text-gray-500">暂无对话历史</div>
        <div className="text-sm text-gray-400 mt-1">开始一次对话来创建历史记录</div>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      {histories.map((history) => (
        <div
          key={history.id}
          onClick={() => onSelectHistory(history.id)}
          className="p-4 bg-white rounded-lg border hover:shadow-sm cursor-pointer transition-all group"
        >
          <div className="flex items-start justify-between">
            <div className="flex-1 min-w-0">
              <div className="font-medium text-gray-900 truncate mb-1">
                {history.title}
              </div>
              
              <div className="flex items-center space-x-4 text-sm text-gray-500 mb-2">
                <div className="flex items-center space-x-1">
                  <MessageCircle size={14} />
                  <span>{history.messageCount} 条消息</span>
                </div>
                <div className="flex items-center space-x-1">
                  <Clock size={14} />
                  <span>{formatDate(history.lastMessageAt)}</span>
                </div>
              </div>

              <div className="flex items-center space-x-1 text-xs text-gray-400">
                <Users size={12} />
                <span>{getGroupNames(history.selectedGroups)}</span>
              </div>
            </div>

            <button
              onClick={(e) => handleDelete(history.id, e)}
              className="opacity-0 group-hover:opacity-100 p-1 text-gray-400 hover:text-red-600 transition-all"
            >
              <Trash2 size={16} />
            </button>
          </div>
        </div>
      ))}

      {hasMore && (
        <button
          onClick={loadMore}
          disabled={loading}
          className="w-full py-3 text-center text-blue-600 hover:text-blue-700 disabled:opacity-50 transition-colors"
        >
          {loading ? '加载中...' : '加载更多'}
        </button>
      )}
    </div>
  );
};