import { useState } from 'react'
import {
  X,
  Loader2,
  CheckCircle,
  XCircle,
  Copy,
  FileImage,
  FileVideo,
  Video,
  ChevronDown,
  ChevronUp,
  Download,
} from 'lucide-react'
import ThrottledImage from './ThrottledImage'

export interface ThumbnailProgressItem {
  id: string
  filename: string
  status: 'pending' | 'downloading' | 'processing' | 'success' | 'error' | 'duplicate'
  error?: string
  thumbnailUrl?: string
  localPreview?: string
  fileType?: 'image' | 'video'
}

interface ThumbnailProgressModalProps {
  isOpen: boolean
  title: string
  items: ThumbnailProgressItem[]
  statusText?: string
  downloadProgress?: { downloaded: number; total: number } | null
  onClose: () => void
}

function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`
}

export function ThumbnailProgressModal({
  isOpen,
  title,
  items,
  statusText,
  downloadProgress,
  onClose,
}: ThumbnailProgressModalProps) {
  const [showErrorsManual, setShowErrorsManual] = useState<boolean | null>(null)

  if (!isOpen) return null

  const successCount = items.filter(i => i.status === 'success').length
  const failedCount = items.filter(i => i.status === 'error').length
  const duplicateCount = items.filter(i => i.status === 'duplicate').length
  const downloadingCount = items.filter(i => i.status === 'downloading').length
  const processingCount = items.filter(i => i.status === 'processing').length
  const pendingCount = items.filter(i => i.status === 'pending').length
  const total = items.length
  const doneCount = successCount + failedCount + duplicateCount
  const isComplete = pendingCount === 0 && processingCount === 0 && downloadingCount === 0
  const progressPercent = total > 0 ? Math.round((doneCount / total) * 100) : 0

  const failedItems = items.filter(i => i.status === 'error')
  // Auto-expand errors when complete and there are failures
  const showErrors = showErrorsManual !== null ? showErrorsManual : (isComplete && failedItems.length > 0)

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
      <div className="w-full max-w-2xl bg-card rounded-xl shadow-2xl border border-border max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-4 sm:px-6 py-4 border-b border-border">
          <h2 className="text-lg font-semibold">{title}</h2>
          {isComplete && (
            <button
              onClick={onClose}
              className="p-2 rounded-lg hover:bg-secondary transition-colors"
            >
              <X className="w-5 h-5" />
            </button>
          )}
        </div>

        {/* Progress Bar */}
        <div className="px-4 sm:px-6 py-3 border-b border-border">
          <div className="flex items-center justify-between text-sm mb-2">
            <span className="text-muted-foreground">
              {isComplete ? 'Complete' : statusText || 'Processing...'}
            </span>
            <span className="font-medium">
              {doneCount} / {total}
            </span>
          </div>
          <div className="h-2 bg-secondary rounded-full overflow-hidden">
            <div
              className={`h-full transition-all duration-300 rounded-full ${
                failedCount > 0 && isComplete ? 'bg-amber-500' : 'bg-primary'
              }`}
              style={{ width: `${progressPercent}%` }}
            />
          </div>

          {/* Download progress */}
          {downloadProgress && downloadProgress.downloaded > 0 && !isComplete && (
            <div className="mt-2">
              <div className="flex items-center justify-between text-xs text-muted-foreground mb-1">
                <span className="flex items-center gap-1">
                  <Download className="w-3 h-3" />
                  {formatBytes(downloadProgress.downloaded)}
                  {downloadProgress.total > 0 && ` / ${formatBytes(downloadProgress.total)}`}
                </span>
                {downloadProgress.total > 0 && (
                  <span>{Math.round((downloadProgress.downloaded / downloadProgress.total) * 100)}%</span>
                )}
              </div>
              {downloadProgress.total > 0 && (
                <div className="h-1.5 bg-secondary rounded-full overflow-hidden">
                  <div
                    className="h-full bg-cyan-500 transition-all duration-300 rounded-full"
                    style={{ width: `${Math.min(100, Math.round((downloadProgress.downloaded / downloadProgress.total) * 100))}%` }}
                  />
                </div>
              )}
            </div>
          )}

          {/* Status Chips */}
          <div className="flex flex-wrap items-center gap-2 mt-2">
            {successCount > 0 && (
              <span className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600">
                <CheckCircle className="w-3 h-3" />
                {successCount} success
              </span>
            )}
            {failedCount > 0 && (
              <span className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-red-500/10 text-red-600">
                <XCircle className="w-3 h-3" />
                {failedCount} failed
              </span>
            )}
            {duplicateCount > 0 && (
              <span className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-amber-500/10 text-amber-600">
                <Copy className="w-3 h-3" />
                {duplicateCount} duplicate
              </span>
            )}
            {downloadingCount > 0 && (
              <span className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-cyan-500/10 text-cyan-600">
                <Download className="w-3 h-3 animate-pulse" />
                {downloadingCount} downloading
              </span>
            )}
            {processingCount > 0 && (
              <span className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-600">
                <Loader2 className="w-3 h-3 animate-spin" />
                {processingCount} processing
              </span>
            )}
            {pendingCount > 0 && (
              <span className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-secondary text-muted-foreground">
                {pendingCount} pending
              </span>
            )}
          </div>
        </div>

        {/* Thumbnail Grid */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-6 min-h-0">
          <div className="grid grid-cols-4 sm:grid-cols-5 md:grid-cols-6 gap-1.5 max-h-80 overflow-y-auto">
            {items.map((item) => (
              <div
                key={item.id}
                className="relative aspect-square rounded-lg overflow-hidden bg-secondary"
                title={item.filename}
              >
                {/* Thumbnail content */}
                {item.localPreview ? (
                  <img
                    src={item.localPreview}
                    alt={item.filename}
                    className="w-full h-full object-cover"
                  />
                ) : item.thumbnailUrl ? (
                  <ThrottledImage
                    src={item.thumbnailUrl}
                    alt={item.filename}
                    className="w-full h-full object-cover"
                    priority
                  />
                ) : (
                  <div className="w-full h-full flex flex-col items-center justify-center gap-1 p-1">
                    {item.fileType === 'video' ? (
                      <FileVideo className="w-8 h-8 text-foreground/40" />
                    ) : (
                      <FileImage className="w-8 h-8 text-foreground/40" />
                    )}
                    <p className="text-[9px] leading-tight text-foreground/50 text-center truncate w-full px-0.5">{item.filename.replace(/\.[^.]+$/, '')}</p>
                  </div>
                )}

                {/* Video badge */}
                {item.fileType === 'video' && (item.localPreview || item.thumbnailUrl) && (
                  <div className="absolute bottom-0.5 left-0.5 bg-black/70 rounded px-1">
                    <Video className="w-3 h-3 text-white" />
                  </div>
                )}

                {/* Status overlays */}
                {item.status === 'pending' && (
                  <div className="absolute inset-0 bg-black/40" />
                )}
                {item.status === 'downloading' && (
                  <div className="absolute inset-0 bg-cyan-500/20 flex items-center justify-center">
                    <Download className="w-5 h-5 text-cyan-500 animate-pulse" />
                  </div>
                )}
                {item.status === 'processing' && (
                  <div className="absolute inset-0 bg-blue-500/20 flex items-center justify-center">
                    <Loader2 className="w-5 h-5 text-blue-500 animate-spin" />
                  </div>
                )}
                {item.status === 'success' && (
                  <div className="absolute top-0.5 right-0.5">
                    <CheckCircle className="w-4 h-4 text-emerald-500 drop-shadow-md" />
                  </div>
                )}
                {item.status === 'error' && (
                  <div className="absolute inset-0 bg-red-500/20 flex items-center justify-center">
                    <XCircle className="w-5 h-5 text-red-500 drop-shadow-md" />
                  </div>
                )}
                {item.status === 'duplicate' && (
                  <div className="absolute inset-0 bg-amber-500/20 flex items-center justify-center">
                    <Copy className="w-4 h-4 text-amber-600 drop-shadow-md" />
                  </div>
                )}
              </div>
            ))}
          </div>

          {/* Error details */}
          {failedItems.length > 0 && (
            <div className="mt-4">
              <button
                onClick={() => setShowErrorsManual(!showErrors)}
                className="flex items-center gap-2 text-sm text-red-600 hover:text-red-700 transition-colors"
              >
                {showErrors ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                {failedItems.length} failed {failedItems.length === 1 ? 'file' : 'files'}
              </button>
              {showErrors && (
                <div className="mt-2 space-y-1.5">
                  {failedItems.map((item) => (
                    <div
                      key={item.id}
                      className="flex items-start gap-2 p-2 rounded-lg bg-red-500/10 text-sm"
                    >
                      <XCircle className="w-4 h-4 text-red-500 flex-shrink-0 mt-0.5" />
                      <div className="min-w-0">
                        <p className="font-medium text-red-600 truncate">{item.filename}</p>
                        <p className="text-red-500/80 text-xs">{item.error || 'Unknown error'}</p>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex justify-end px-4 sm:px-6 py-4 border-t border-border">
          {isComplete ? (
            <button
              onClick={onClose}
              className="px-4 py-2 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
            >
              Done
            </button>
          ) : (
            <p className="text-sm text-muted-foreground">
              Please wait while processing completes...
            </p>
          )}
        </div>
      </div>
    </div>
  )
}

export default ThumbnailProgressModal
