import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, MessageSquare, Trash2, ChevronLeft, User, Settings, LogOut, Phone } from 'lucide-react';
import { clsx } from 'clsx';
import { useChatStore } from '../stores/chatStore';
import { useChat } from '../hooks/useChat';

export function ChatSidebar() {
  const navigate = useNavigate();
  const { conversations, currentConversationId, userId, deleteConversation, toggleSidebar } = useChatStore();
  const { createConversation } = useChat();
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const handleNewChat = async () => {
    const conversationId = await createConversation();
    if (conversationId) {
      navigate(`/chat/${conversationId}`);
    }
  };

  const handleSelectConversation = (id: string) => {
    navigate(`/chat/${id}`);
  };

  const handleDeleteConversation = async (id: string) => {
    if (!userId || deletingId) return;

    setDeletingId(id);
    const success = await deleteConversation(userId, id);
    setDeletingId(null);

    if (success && currentConversationId === id) {
      navigate('/chat');
    }
  };

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="p-4 border-b border-secondary-200">
        <div className="flex items-center gap-2">
          <button
            onClick={handleNewChat}
            className="flex-1 flex items-center justify-center gap-2 btn-primary py-2.5"
          >
            <Plus className="w-4 h-4" />
            <span>新建对话</span>
          </button>
          <button
            onClick={toggleSidebar}
            className="hidden md:flex p-2.5 hover:bg-secondary-100 rounded-lg transition-colors"
            title="收起侧边栏"
          >
            <ChevronLeft className="w-5 h-5 text-secondary-500" />
          </button>
        </div>
      </div>

      {/* Conversation list */}
      <div className="flex-1 overflow-y-auto p-2">
        {conversations.length === 0 ? (
          <div className="text-center py-8 text-secondary-400">
            <MessageSquare className="w-8 h-8 mx-auto mb-2 opacity-50" />
            <p className="text-sm">暂无对话记录</p>
          </div>
        ) : (
          <div className="space-y-1">
            {conversations.map((conv) => (
              <ConversationItem
                key={conv.id}
                id={conv.id}
                title={conv.title || '新对话'}
                isActive={conv.id === currentConversationId}
                updatedAt={conv.updatedAt}
                isDeleting={deletingId === conv.id}
                onClick={() => handleSelectConversation(conv.id)}
                onDelete={() => handleDeleteConversation(conv.id)}
              />
            ))}
          </div>
        )}
      </div>

      {/* Footer - User Profile */}
      <div className="p-3 border-t border-secondary-200">
        <UserProfileMenu />
      </div>
    </div>
  );
}

function UserProfileMenu() {
  const navigate = useNavigate();
  const { userId } = useChatStore();
  const [menuOpen, setMenuOpen] = useState(false);

  const handleProfileClick = () => {
    setMenuOpen(false);
    navigate('/profile');
  };

  const handleBindPhone = () => {
    setMenuOpen(false);
    navigate('/bind-phone');
  };

  const handleLogout = () => {
    setMenuOpen(false);
    // 清除本地存储的用户信息
    localStorage.removeItem('userId');
    // 刷新页面以重新生成匿名用户
    window.location.href = '/chat';
  };

  // 检查用户是否已绑定手机（通过本地存储或其他方式）
  const isRegistered = localStorage.getItem('userPhone') !== null;

  return (
    <div className="relative">
      <button
        onClick={() => setMenuOpen(!menuOpen)}
        className="w-full flex items-center gap-3 px-3 py-2.5 rounded-lg hover:bg-secondary-50 transition-colors text-left"
      >
        <div className="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center">
          <User className="w-4 h-4 text-primary-600" />
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium text-secondary-700 truncate">
            {isRegistered ? '已注册用户' : '访客用户'}
          </p>
          <p className="text-xs text-secondary-400 truncate">
            {userId ? `ID: ${userId.slice(0, 8)}...` : '未登录'}
          </p>
        </div>
        <Settings className="w-4 h-4 text-secondary-400" />
      </button>

      {/* Dropdown menu */}
      {menuOpen && (
        <>
          {/* Backdrop */}
          <div
            className="fixed inset-0 z-10"
            onClick={() => setMenuOpen(false)}
          />
          {/* Menu */}
          <div className="absolute bottom-full left-0 right-0 mb-1 bg-white rounded-lg shadow-lg border border-secondary-200 overflow-hidden z-20">
            <button
              onClick={handleProfileClick}
              className="w-full flex items-center gap-3 px-4 py-3 hover:bg-secondary-50 transition-colors text-left"
            >
              <User className="w-4 h-4 text-secondary-500" />
              <span className="text-sm text-secondary-700">个人资料</span>
            </button>
            {!isRegistered && (
              <button
                onClick={handleBindPhone}
                className="w-full flex items-center gap-3 px-4 py-3 hover:bg-secondary-50 transition-colors text-left"
              >
                <Phone className="w-4 h-4 text-secondary-500" />
                <span className="text-sm text-secondary-700">绑定手机</span>
              </button>
            )}
            <div className="border-t border-secondary-100" />
            <button
              onClick={handleLogout}
              className="w-full flex items-center gap-3 px-4 py-3 hover:bg-red-50 transition-colors text-left"
            >
              <LogOut className="w-4 h-4 text-red-500" />
              <span className="text-sm text-red-600">退出登录</span>
            </button>
          </div>
        </>
      )}
    </div>
  );
}

interface ConversationItemProps {
  id: string;
  title: string;
  isActive: boolean;
  updatedAt: string;
  isDeleting: boolean;
  onClick: () => void;
  onDelete: () => void;
}

function ConversationItem({
  title,
  isActive,
  updatedAt,
  isDeleting,
  onClick,
  onDelete,
}: ConversationItemProps) {
  const formatTime = (dateStr: string) => {
    const date = new Date(dateStr);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

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

  return (
    <button
      onClick={onClick}
      disabled={isDeleting}
      className={clsx(
        'w-full flex items-center gap-3 px-3 py-2.5 rounded-lg text-left transition-colors group',
        isActive
          ? 'bg-primary-50 text-primary-700'
          : 'hover:bg-secondary-50 text-secondary-700',
        isDeleting && 'opacity-50 cursor-not-allowed',
      )}
    >
      <MessageSquare
        className={clsx(
          'w-4 h-4 flex-shrink-0',
          isActive ? 'text-primary-600' : 'text-secondary-400',
        )}
      />
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium truncate">{title}</p>
        <p className="text-xs text-secondary-400">{formatTime(updatedAt)}</p>
      </div>
      {isDeleting ? (
        <div className="w-4 h-4 border-2 border-secondary-400 border-t-transparent rounded-full animate-spin" />
      ) : (
        <button
          onClick={(e) => {
            e.stopPropagation();
            onDelete();
          }}
          className="opacity-0 group-hover:opacity-100 p-1 hover:bg-red-100 hover:text-red-600 rounded transition-all"
          title="删除对话"
        >
          <Trash2 className="w-3.5 h-3.5" />
        </button>
      )}
    </button>
  );
}
