import { X, Loader2, CheckCircle2, XCircle } from 'lucide-react'

export interface BatchProgressItem {
  id: string
  filename: string
  status: 'pending' | 'processing' | 'success' | 'error'
  error?: string
}

interface BatchProgressModalProps {
  isOpen: boolean
  title: string
  items: BatchProgressItem[]
  onClose: () => void
  /** Allow closing while still processing */
  allowEarlyClose?: boolean
  /** Show a summary instead of all files when count is high */
  collapseLargeList?: boolean
  /** Threshold for collapsing (default: 20) */
  collapseThreshold?: number
}

export function BatchProgressModal({
  isOpen,
  title,
  items,
  onClose,
  allowEarlyClose = false,
  collapseLargeList = true,
  collapseThreshold = 20,
}: BatchProgressModalProps) {
  if (!isOpen) return null

  const completed = items.filter(f => f.status === 'success').length
  const failed = items.filter(f => f.status === 'error').length
  const pending = items.filter(f => f.status === 'pending').length
  const processing = items.filter(f => f.status === 'processing').length
  const total = items.length
  const isComplete = pending === 0 && processing === 0
  const progressPercent = total > 0 ? Math.round(((completed + failed) / total) * 100) : 0

  // Determine if we should show collapsed view
  const showCollapsed = collapseLargeList && total > collapseThreshold

  // Get items to display (errors first, then processing, then recent successes)
  const getDisplayItems = () => {
    if (!showCollapsed) return items

    const errors = items.filter(i => i.status === 'error')
    const processingItems = items.filter(i => i.status === 'processing')
    const successes = items.filter(i => i.status === 'success').slice(-3)
    const pendingItems = items.filter(i => i.status === 'pending').slice(0, 2)

    return [...errors, ...processingItems, ...pendingItems, ...successes]
  }

  const displayItems = getDisplayItems()
  const hiddenCount = showCollapsed ? total - displayItems.length : 0

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-white dark:bg-slate-800 rounded-lg shadow-xl max-w-lg w-full max-h-[80vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-slate-200 dark:border-slate-700">
          <h3 className="text-lg font-semibold text-slate-900 dark:text-slate-100">
            {title}
          </h3>
          {(isComplete || allowEarlyClose) && (
            <button
              onClick={onClose}
              className="p-1 rounded-md hover:bg-slate-100 dark:hover:bg-slate-700 text-slate-500 dark:text-slate-400"
            >
              <X className="w-5 h-5" />
            </button>
          )}
        </div>

        {/* Progress Bar */}
        <div className="px-4 py-3 border-b border-slate-200 dark:border-slate-700">
          <div className="flex items-center justify-between text-sm mb-2">
            <span className="text-slate-600 dark:text-slate-400">
              {isComplete ? 'Complete' : 'Processing...'}
            </span>
            <span className="font-medium text-slate-900 dark:text-slate-100">
              {completed + failed} / {total}
            </span>
          </div>
          <div className="h-2 bg-slate-200 dark:bg-slate-700 rounded-full overflow-hidden">
            <div
              className={`h-full transition-all duration-300 ${
                failed > 0 && isComplete
                  ? 'bg-gradient-to-r from-green-500 to-red-500'
                  : 'bg-blue-500'
              }`}
              style={{ width: `${progressPercent}%` }}
            />
          </div>

          {/* Status Summary */}
          <div className="flex items-center gap-4 mt-2 text-xs">
            {completed > 0 && (
              <span className="flex items-center gap-1 text-green-600 dark:text-green-400">
                <CheckCircle2 className="w-3.5 h-3.5" />
                {completed} succeeded
              </span>
            )}
            {failed > 0 && (
              <span className="flex items-center gap-1 text-red-600 dark:text-red-400">
                <XCircle className="w-3.5 h-3.5" />
                {failed} failed
              </span>
            )}
            {processing > 0 && (
              <span className="flex items-center gap-1 text-blue-600 dark:text-blue-400">
                <Loader2 className="w-3.5 h-3.5 animate-spin" />
                {processing} processing
              </span>
            )}
            {pending > 0 && (
              <span className="text-slate-500 dark:text-slate-400">
                {pending} waiting
              </span>
            )}
          </div>
        </div>

        {/* File List */}
        <div className="flex-1 overflow-auto p-4 space-y-2 min-h-0">
          {showCollapsed && hiddenCount > 0 && (
            <div className="text-xs text-slate-500 dark:text-slate-400 text-center py-1">
              Showing {displayItems.length} of {total} items
            </div>
          )}

          {displayItems.map((file) => (
            <div
              key={file.id}
              className={`flex items-center gap-3 p-2.5 rounded-lg transition-colors ${
                file.status === 'error'
                  ? 'bg-red-50 dark:bg-red-900/20'
                  : file.status === 'success'
                  ? 'bg-green-50 dark:bg-green-900/20'
                  : file.status === 'processing'
                  ? 'bg-blue-50 dark:bg-blue-900/20'
                  : 'bg-slate-50 dark:bg-slate-900/50'
              }`}
            >
              {/* Status Icon */}
              <div className="flex-shrink-0">
                {file.status === 'pending' && (
                  <div className="w-5 h-5 rounded-full border-2 border-slate-300 dark:border-slate-600" />
                )}
                {file.status === 'processing' && (
                  <Loader2 className="w-5 h-5 text-blue-500 animate-spin" />
                )}
                {file.status === 'success' && (
                  <CheckCircle2 className="w-5 h-5 text-green-500" />
                )}
                {file.status === 'error' && (
                  <XCircle className="w-5 h-5 text-red-500" />
                )}
              </div>

              {/* File Info */}
              <div className="flex-1 min-w-0">
                <p className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">
                  {file.filename}
                </p>
                {file.error && (
                  <p className="text-xs text-red-600 dark:text-red-400 mt-0.5 truncate">
                    {file.error}
                  </p>
                )}
              </div>
            </div>
          ))}
        </div>

        {/* Footer */}
        <div className="p-4 border-t border-slate-200 dark:border-slate-700 flex justify-end">
          {isComplete ? (
            <button
              onClick={onClose}
              className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
            >
              Done
            </button>
          ) : (
            <p className="text-sm text-slate-500 dark:text-slate-400">
              Please wait while processing completes...
            </p>
          )}
        </div>
      </div>
    </div>
  )
}

export default BatchProgressModal
