import React from 'react'
import { Loader2 } from 'lucide-react'
import { HistoryCard } from './HistoryCard'
import type { QueryHistorySummary } from '../types'

interface HistoryListProps {
  items: QueryHistorySummary[]
  hasMore: boolean
  onLoadMore: () => void
  isLoadingMore: boolean
  onDelete: (id: number) => void
  isDeleting: boolean
  onClearAll: () => void
  isClearing: boolean
}

export const HistoryList: React.FC<HistoryListProps> = ({
  items,
  hasMore,
  onLoadMore,
  isLoadingMore,
  onDelete,
  isDeleting,
  onClearAll,
  isClearing,
}) => {
  const handleClearAll = () => {
    if (window.confirm('Are you sure you want to clear all query history? This cannot be undone.')) {
      onClearAll()
    }
  }

  return (
    <div className="space-y-4">
      {items.length > 0 && (
        <div className="flex justify-end">
          <button
            type="button"
            onClick={handleClearAll}
            disabled={isClearing}
            className="px-3 py-1.5 text-sm font-medium text-red-600 border border-red-300 rounded hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
          >
            {isClearing ? 'Clearing...' : 'Clear All'}
          </button>
        </div>
      )}

      <div className="space-y-3">
        {items.map((item) => (
          <HistoryCard
            key={item.id}
            item={item}
            onDelete={onDelete}
            isDeleting={isDeleting}
          />
        ))}
      </div>

      {hasMore && (
        <div className="flex justify-center pt-4">
          <button
            type="button"
            onClick={onLoadMore}
            disabled={isLoadingMore}
            className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
          >
            {isLoadingMore && <Loader2 className="w-4 h-4 animate-spin" />}
            {isLoadingMore ? 'Loading...' : 'Load More'}
          </button>
        </div>
      )}
    </div>
  )
}
