'use client';

import { useState, useEffect } from 'react';
import { X, Trash2, MessageSquare, Loader2 } from 'lucide-react';
import { useTranslation } from '@/hooks/useTranslation';
import { aiAssistantApi, type Conversation } from '@/lib/api/ai-assistant';
import { useConfirm } from '@/components/common/feedback/ConfirmProvider';

interface HistoryPanelProps {
  onSelect: (conversation: Conversation) => void;
  onClose: () => void;
  currentConversationId: string | null;
}

/**
 * 历史对话面板
 */
export function HistoryPanel({ onSelect, onClose, currentConversationId }: HistoryPanelProps) {
  const { t } = useTranslation();
  const confirm = useConfirm();
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(false);

  // 加载对话列表
  useEffect(() => {
    loadConversations();
  }, []);

  const loadConversations = async (pageNum: number = 1) => {
    setIsLoading(true);
    try {
      const response: any = await aiAssistantApi.getConversations({ page: pageNum, limit: 20 });
      const items = response.data.items || [];
      
      if (pageNum === 1) {
        setConversations(items);
      } else {
        setConversations(prev => [...prev, ...items]);
      }
      
      setHasMore(response.data.hasNext);
      setPage(pageNum);
    } catch (err) {
      console.error('Failed to load conversations:', err);
    } finally {
      setIsLoading(false);
    }
  };

  // 删除对话
  const handleDelete = async (e: React.MouseEvent, id: string) => {
    e.stopPropagation();
    
    const confirmed = await confirm({
      title: t.common.confirmDelete || 'Are you sure?',
      variant: 'danger',
    });
    if (!confirmed) return;

    try {
      await aiAssistantApi.deleteConversation(id);
      setConversations(prev => prev.filter(c => c.id !== id));
    } catch (err) {
      console.error('Failed to delete conversation:', err);
    }
  };

  // 格式化时间
  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (days === 0) {
      return 'Today';
    } else if (days === 1) {
      return 'Yesterday';
    } else {
      return date.toLocaleDateString();
    }
  };

  // 分组对话
  const groupedConversations = conversations.reduce((groups, conv) => {
    const dateKey = formatTime(conv.createdAt);
    if (!groups[dateKey]) {
      groups[dateKey] = [];
    }
    groups[dateKey].push(conv);
    return groups;
  }, {} as Record<string, Conversation[]>);

  return (
    <div className="absolute inset-0 bg-white z-10 flex flex-col">
      {/* 头部 */}
      <div className="flex items-center justify-between px-4 py-3 border-b">
        <h3 className="font-medium text-gray-900">
          {'Conversation History'}
        </h3>
        <button
          onClick={onClose}
          className="p-1 hover:bg-gray-100 rounded-lg transition-colors"
        >
          <X className="w-4 h-4" />
        </button>
      </div>

      {/* 对话列表 */}
      <div className="flex-1 overflow-y-auto">
        {isLoading && conversations.length === 0 ? (
          <div className="flex items-center justify-center h-32">
            <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
          </div>
        ) : conversations.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-32 text-gray-500">
            <MessageSquare className="w-8 h-8 mb-2 text-gray-300" />
            <p className="text-sm">{'No history'}</p>
          </div>
        ) : (
          <div className="divide-y">
            {Object.entries(groupedConversations).map(([date, convs]) => (
              <div key={date}>
                <div className="px-4 py-2 bg-gray-50 text-xs text-gray-500 font-medium">
                  {date}
                </div>
                {convs.map((conv) => (
                  <button
                    key={conv.id}
                    onClick={() => onSelect(conv)}
                    className={`w-full flex items-center justify-between px-4 py-3 hover:bg-gray-50 transition-colors ${
                      conv.id === currentConversationId ? 'bg-blue-50' : ''
                    }`}
                  >
                    <div className="flex-1 text-left min-w-0">
                      <p className="text-sm font-medium text-gray-900 truncate">
                        {conv.title || 'New Chat'}
                      </p>
                      <div className="flex items-center gap-2 mt-0.5">
                        <span className="text-xs text-gray-500">
                          {new Date(conv.createdAt).toLocaleTimeString([], { 
                            hour: '2-digit', 
                            minute: '2-digit' 
                          })}
                        </span>
                        {conv.messageCount && (
                          <span className="text-xs text-gray-400">
                            {conv.messageCount} messages
                          </span>
                        )}
                      </div>
                    </div>
                    <button
                      onClick={(e) => handleDelete(e, conv.id)}
                      className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </button>
                ))}
              </div>
            ))}

            {/* 加载更多 */}
            {hasMore && (
              <button
                onClick={() => loadConversations(page + 1)}
                disabled={isLoading}
                className="w-full py-3 text-sm text-blue-600 hover:bg-gray-50 disabled:opacity-50"
              >
                {isLoading ? (
                  <Loader2 className="w-4 h-4 animate-spin mx-auto" />
                ) : (
                  'Load More'
                )}
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

export default HistoryPanel;
