import { useState } from 'react'
import { MessageSquare, Loader2, Pencil, Trash2, Check, X } from 'lucide-react'
import type { ConversationItem } from '@/hooks/useConversations'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'

interface ChatHistoryListProps {
  conversations: ConversationItem[]
  activeId: string | null
  onSelect: (id: string) => void
  onUpdateTitle?: (id: string, newTitle: string) => void
  onDelete?: (id: string) => void
  isLoading?: boolean
  collapsed?: boolean
}

export function ChatHistoryList({
  conversations,
  activeId,
  onSelect,
  onUpdateTitle,
  onDelete,
  isLoading,
  collapsed = false,
}: ChatHistoryListProps) {
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editTitle, setEditTitle] = useState<string>('')

  const handleStartEdit = (e: React.MouseEvent, session: ConversationItem) => {
    e.stopPropagation()
    setEditingId(session.id)
    setEditTitle(session.title || 'Cuộc trò chuyện mới')
  }

  const handleSaveEdit = async (id: string) => {
    if (editTitle.trim() && onUpdateTitle) {
      await onUpdateTitle(id, editTitle.trim())
    }
    setEditingId(null)
  }

  const handleDelete = async (e: React.MouseEvent, id: string) => {
    e.stopPropagation()
    if (onDelete) {
      await onDelete(id)
    }
  }

  if (isLoading && conversations.length === 0) {
    return (
      <div className="flex-1 flex items-center justify-center p-4 text-muted-foreground text-xs gap-2">
        <Loader2 className="w-4 h-4 animate-spin text-primary" />
        {!collapsed && <span>Đang tải hội thoại...</span>}
      </div>
    )
  }

  if (conversations.length === 0) {
    return (
      <div className="flex-1 p-4 text-center text-muted-foreground text-xs flex flex-col items-center justify-center gap-2">
        <MessageSquare className="w-6 h-6 text-muted-foreground/40" />
        {!collapsed && <span>Chưa có hội thoại nào</span>}
      </div>
    )
  }

  return (
    <TooltipProvider delayDuration={200}>
      <ScrollArea className="flex-1">
        <div className="space-y-1 pb-4 px-2 pt-1">
          {conversations.map((session) => {
            const isActive = session.id === activeId
            const isEditing = session.id === editingId

            if (collapsed) {
              return (
                <Tooltip key={session.id}>
                  <TooltipTrigger asChild>
                    <Button
                      onClick={() => onSelect(session.id)}
                      variant={isActive ? 'secondary' : 'ghost'}
                      size="icon"
                      className={cn(
                        'w-10 h-10 rounded-md mx-auto flex items-center justify-center transition-all',
                        isActive
                          ? 'bg-secondary text-foreground shadow-sm font-semibold'
                          : 'hover:bg-muted text-muted-foreground hover:text-foreground'
                      )}
                    >
                      <MessageSquare className={cn('w-4 h-4', isActive && 'text-primary')} />
                    </Button>
                  </TooltipTrigger>
                  <TooltipContent side="right" className="max-w-[200px]">
                    <p className="font-medium text-xs truncate">{session.title || 'Cuộc trò chuyện mới'}</p>
                  </TooltipContent>
                </Tooltip>
              )
            }

            return (
              <div
                key={session.id}
                onClick={() => !isEditing && onSelect(session.id)}
                className={cn(
                  'w-full flex items-center justify-between py-2 px-3 font-normal rounded-md transition-all duration-200 group relative cursor-pointer overflow-hidden',
                  isActive
                    ? 'bg-secondary text-foreground shadow-sm font-medium'
                    : 'hover:bg-muted/70 text-muted-foreground hover:text-foreground'
                )}
              >
                <div className="flex items-center gap-2.5 flex-1 min-w-0 overflow-hidden">
                  <MessageSquare
                    className={cn(
                      'w-4 h-4 shrink-0 transition-colors',
                      isActive ? 'text-primary' : 'group-hover:text-primary'
                    )}
                  />
                  {isEditing ? (
                    <div
                      className="flex items-center gap-1 flex-1 min-w-0"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <input
                        type="text"
                        value={editTitle}
                        onChange={(e) => setEditTitle(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter') handleSaveEdit(session.id)
                          if (e.key === 'Escape') setEditingId(null)
                        }}
                        onBlur={() => handleSaveEdit(session.id)}
                        autoFocus
                        className="w-full bg-background border border-input rounded px-2 py-0.5 text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary"
                      />
                      <button
                        type="button"
                        onClick={() => handleSaveEdit(session.id)}
                        className="p-1 text-primary hover:bg-muted rounded"
                        title="Lưu"
                      >
                        <Check className="w-3.5 h-3.5" />
                      </button>
                      <button
                        type="button"
                        onClick={() => setEditingId(null)}
                        className="p-1 text-muted-foreground hover:bg-muted rounded"
                        title="Hủy"
                      >
                        <X className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  ) : (
                    <div className="truncate text-xs font-medium leading-tight flex-1">
                      {session.title || 'Cuộc trò chuyện mới'}
                    </div>
                  )}
                </div>

                {!isEditing && (
                  <div
                    className={cn(
                      "absolute right-0 inset-y-0 flex items-center justify-end pr-2 pl-12 opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none group-hover:pointer-events-auto rounded-r-md",
                      isActive
                        ? "bg-gradient-to-l from-secondary via-secondary to-transparent"
                        : "bg-gradient-to-l from-muted via-muted/80 to-transparent"
                    )}
                  >
                    <div className="flex items-center gap-0.5">
                      {onUpdateTitle && (
                        <button
                          type="button"
                          onClick={(e) => handleStartEdit(e, session)}
                          className="p-1.5 hover:text-foreground text-muted-foreground transition-colors rounded-md hover:bg-background/60"
                          title="Đổi tên"
                        >
                          <Pencil className="w-3.5 h-3.5" />
                        </button>
                      )}
                      {onDelete && (
                        <button
                          type="button"
                          onClick={(e) => handleDelete(e, session.id)}
                          className="p-1.5 hover:text-destructive text-muted-foreground transition-colors rounded-md hover:bg-background/60"
                          title="Xóa"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                        </button>
                      )}
                    </div>
                  </div>
                )}
              </div>
            )
          })}
        </div>
      </ScrollArea>
    </TooltipProvider>
  )
}


