import { useState, useEffect, useMemo } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Plus, Pin, Trash2, MessageCircle, Search } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ConfirmDialog } from '@/components/ui/confirm';
import { useAppStore } from '@/store';
import { api } from '@/lib/api';
import { useToast } from '@/hooks/useToast';
import { useConfirm } from '@/hooks/useConfirm';

export function MiddlePanel() {
  const { conversations, setConversations } = useAppStore();
  const [search, setSearch] = useState('');
  const navigate = useNavigate();
  const location = useLocation();
  const { toast } = useToast();
  const { confirmState, confirm, handleConfirm, handleCancel } = useConfirm();
  const [pendingDeleteId, setPendingDeleteId] = useState<string | null>(null);

  const conversationId = useMemo(() => {
    const match = location.pathname.match(/^\/chat\/(.+)$/);
    return match ? match[1] : null;
  }, [location.pathname]);

  const loadConversations = () => {
    api.listConversations().then(setConversations).catch(() => {});
  };

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

  const handleSearch = (value: string) => {
    setSearch(value);
    if (!value) {
      loadConversations();
      return;
    }
    const qs = `?search=${encodeURIComponent(value)}`;
    fetch(`/api/pipeline/conversations${qs}`)
      .then((r) => r.json())
      .then(setConversations)
      .catch(() => {});
  };

  const handleTogglePin = async (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    const conv = conversations.find((c) => c.id === id);
    if (!conv) return;
    await api.updateConversation(id, { pinned: !conv.pinned });
    loadConversations();
  };

  const handleDelete = async (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    if (!confirm('确定删除这个对话？')) return;
    await api.deleteConversation(id);
    loadConversations();
    toast('对话已删除', 'success');
    if (id === conversationId) navigate('/chat');
  };

  const formatDate = (d: string) => {
    const date = new Date(d);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    if (diff < 86400000) return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`;
    return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
  };

  return (
    <aside className="w-60 flex flex-col border-r border-zinc-100 bg-white">
      <div className="p-3 flex items-center gap-2 border-b border-zinc-100/80">
        <div className="relative flex-1">
          <Search size={13} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-zinc-300" />
          <Input
            placeholder="搜索对话..."
            className="h-8 text-xs bg-zinc-50/80 border-zinc-100 pl-8 focus:bg-white"
            value={search}
            onChange={(e) => handleSearch(e.target.value)}
          />
        </div>
        <button
          onClick={() => navigate('/chat')}
          className="flex items-center gap-1 px-3 py-1.5 rounded-lg bg-indigo-600 text-white text-xs font-medium hover:bg-indigo-700 transition-colors whitespace-nowrap shadow-sm shadow-indigo-200/50"
        >
          <Plus size={13} />
          新对话
        </button>
      </div>
      <ScrollArea className="flex-1">
        {conversations.map((conv) => (
          <div
            key={conv.id}
            onClick={() => navigate(`/chat/${conv.id}`)}
            className={`group w-full text-left px-3 py-2.5 transition-all duration-150 cursor-pointer
              ${conv.id === conversationId
                ? 'bg-indigo-50/60 border-l-2 border-l-indigo-500'
                : 'hover:bg-zinc-50/80 border-l-2 border-l-transparent'}`}
          >
            <div className="flex items-center gap-1.5">
              {conv.pinned ? <Pin size={11} className="text-indigo-400 flex-shrink-0" /> : null}
              <div className={`text-sm truncate flex-1 ${conv.id === conversationId ? 'text-indigo-700 font-medium' : 'text-zinc-600'}`}>
                {conv.title}
              </div>
              <div className="opacity-0 group-hover:opacity-100 flex gap-0.5 transition-opacity duration-150 flex-shrink-0">
                <button
                  onClick={(e) => handleTogglePin(conv.id, e)}
                  className={`p-1 rounded-md transition-colors ${conv.pinned ? 'text-indigo-400' : 'text-zinc-300 hover:text-zinc-500 hover:bg-zinc-100'}`}
                  title={conv.pinned ? '取消置顶' : '置顶'}
                >
                  <Pin size={12} />
                </button>
                <button
                  onClick={(e) => handleDelete(conv.id, e)}
                  className="p-1 rounded-md text-zinc-300 hover:text-red-500 hover:bg-red-50 transition-colors"
                  title="删除"
                >
                  <Trash2 size={12} />
                </button>
              </div>
            </div>
            <div className="mt-0.5">
              <span className="text-[10px] text-zinc-300">
                {formatDate(conv.updated_at)}
              </span>
            </div>
          </div>
        ))}
        {conversations.length === 0 && (
          <div className="flex flex-col items-center justify-center mt-16 text-zinc-300">
            <MessageCircle size={28} className="mb-3 opacity-30" strokeWidth={1.5} />
            <p className="text-xs text-zinc-400">暂无对话</p>
            <p className="text-[10px] mt-1 text-zinc-300">点击上方「新对话」开始</p>
          </div>
        )}
      </ScrollArea>
    </aside>
  );
}
