import {ArrowLeft, MessageSquare, PanelLeftClose, Plus, Search, X} from 'lucide-react'
import {Link} from 'react-router-dom'
import {useEffect, useState} from 'react'
import {type Conversation, conversationApi, type ConversationListItem} from '../api/conversation'
import {type Character, characterApi} from '../api/character'

interface SidebarProps {
  currentConversationId?: number
  onConversationChange: (conversation: Conversation) => void
  onClose?: () => void
}

export default function Sidebar({ currentConversationId, onConversationChange, onClose }: SidebarProps) {
  const [conversations, setConversations] = useState<ConversationListItem[]>([])
  const [characters, setCharacters] = useState<Character[]>([])
  const [showCharacterModal, setShowCharacterModal] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [loading, setLoading] = useState(true)

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

  const loadConversations = async () => {
    try {
      const response = await conversationApi.getConversationList({ page: 1, pageSize: 50 })
      setConversations(response.data.list || [])
    } catch (err) {
      console.error('加载对话列表失败:', err)
    } finally {
      setLoading(false)
    }
  }

  const loadCharacters = async () => {
    try {
      const response = await characterApi.getCharacterList({ page: 1, pageSize: 50 })
      setCharacters(response.data.list || [])
    } catch (err) {
      console.error('加载角色列表失败:', err)
    }
  }

  const filteredCharacters = characters.filter(char =>
    char.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
    char.description.toLowerCase().includes(searchQuery.toLowerCase())
  )

  const handleStartChat = async (character: Character) => {
    try {
      const response = await conversationApi.createConversation({
        characterId: character.id,
        title: `与 ${character.name} 的对话`,
      })
      setShowCharacterModal(false)
      onConversationChange(response.data)
      await loadConversations()
    } catch (err) {
      console.error('创建对话失败:', err)
      alert('创建对话失败，请重试')
    }
  }

  const handleConversationClick = async (conv: ConversationListItem) => {
    try {
      // 获取完整的对话信息
      const response = await conversationApi.getConversationById(conv.id)
      onConversationChange(response.data)
    } catch (err) {
      console.error('加载对话失败:', err)
      alert('加载对话失败，请重试')
    }
  }

  const formatTime = (dateString: string) => {
    const date = new Date(dateString)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const minutes = Math.floor(diff / 60000)
    const hours = Math.floor(diff / 3600000)
    const days = Math.floor(diff / 86400000)

    if (minutes < 1) return '刚刚'
    if (minutes < 60) return `${minutes}分钟前`
    if (hours < 24) return `${hours}小时前`
    if (days < 7) return `${days}天前`
    return date.toLocaleDateString('zh-CN')
  }

  return (
    <>
      <div className="w-80 glass border-r border-white/10 flex flex-col">
        <div className="p-4 border-b border-white/10">
          <div className="flex items-center gap-3 mb-4">
            <Link to="/" className="p-2 glass-hover rounded-lg cursor-pointer group" title="返回首页">
              <ArrowLeft className="w-5 h-5 group-hover:text-primary transition-colors" />
            </Link>
            <h1 className="flex-1 text-xl font-semibold bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent">
              对话
            </h1>
            <button
              onClick={() => setShowCharacterModal(true)}
              className="p-2 glass-hover rounded-lg cursor-pointer"
              title="新建对话"
            >
              <Plus className="w-5 h-5" />
            </button>
            {onClose && (
              <button
                onClick={onClose}
                className="p-2 glass-hover rounded-lg cursor-pointer"
                title="隐藏侧边栏"
              >
                <PanelLeftClose className="w-5 h-5" />
              </button>
            )}
          </div>

          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/40" />
            <input
              type="text"
              placeholder="搜索对话..."
              className="w-full pl-10 pr-4 py-2 glass rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/50 transition-all"
            />
          </div>
        </div>

        <div className="flex-1 overflow-y-auto p-2">
          {loading ? (
            <div className="text-center py-8 text-white/60">加载中...</div>
          ) : conversations.length === 0 ? (
            <div className="text-center py-8 text-white/60">
              <p className="mb-2">还没有对话</p>
              <button
                onClick={() => setShowCharacterModal(true)}
                className="text-sm text-primary hover:text-secondary transition-colors cursor-pointer"
              >
                创建第一个对话
              </button>
            </div>
          ) : (
            conversations.map((conv) => (
              <button
                key={conv.id}
                onClick={() => handleConversationClick(conv)}
                className={`w-full p-3 glass-hover rounded-lg mb-2 text-left cursor-pointer group ${
                  currentConversationId === conv.id ? 'ring-2 ring-primary/50' : ''
                }`}
              >
                <div className="flex items-start gap-3">
                  <div className="p-2 bg-primary/20 rounded-lg group-hover:bg-primary/30 transition-colors">
                    <MessageSquare className="w-4 h-4 text-primary" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between mb-1">
                      <h3 className="font-medium text-sm truncate">{conv.title}</h3>
                      <span className="text-xs text-white/40">{formatTime(conv.updatedAt)}</span>
                    </div>
                    <p className="text-xs text-white/60">消息: {conv.messageCount}</p>
                  </div>
                </div>
              </button>
            ))
          )}
        </div>
      </div>

      {showCharacterModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="glass rounded-3xl p-6 max-w-2xl w-full max-h-[80vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-2xl font-bold">选择角色开始对话</h2>
              <button
                onClick={() => setShowCharacterModal(false)}
                className="p-2 glass-hover rounded-lg cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="relative mb-4">
              <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-white/40" />
              <input
                type="text"
                placeholder="搜索角色..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-12 pr-4 py-3 glass rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/50"
              />
            </div>

            <div className="flex-1 overflow-y-auto pr-2">
              {filteredCharacters.length === 0 ? (
                <div className="text-center py-12 text-white/60">
                  <p className="mb-4">没有找到角色</p>
                  <Link
                    to="/characters"
                    onClick={() => setShowCharacterModal(false)}
                    className="text-primary hover:text-secondary transition-colors cursor-pointer"
                  >
                    去创建角色卡 →
                  </Link>
                </div>
              ) : (
                <div className="grid md:grid-cols-2 gap-4">
                  {filteredCharacters.map((char) => (
                    <button
                      key={char.id}
                      onClick={() => handleStartChat(char)}
                      className="glass-hover rounded-2xl p-4 text-left cursor-pointer group"
                    >
                      <div className="flex items-start gap-3">
                        {char.avatar && (
                          <img
                            src={char.avatar}
                            alt={char.name}
                            className="w-12 h-12 rounded-full object-cover"
                          />
                        )}
                        <div className="flex-1 min-w-0">
                          <h3 className="font-semibold mb-1 group-hover:text-primary transition-colors">
                            {char.name}
                          </h3>
                          <p className="text-xs text-white/40 line-clamp-2">{char.description}</p>
                        </div>
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </div>

            <div className="mt-4 pt-4 border-t border-white/10">
              <Link
                to="/characters"
                onClick={() => setShowCharacterModal(false)}
                className="text-sm text-primary hover:text-secondary transition-colors cursor-pointer"
              >
                管理我的角色卡 →
              </Link>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
