import { useState, useRef, useCallback, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useBreadcrumb } from '../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../config/breadcrumbConfig'
import { Upload, FileImage, FileVideo, Check, X, AlertCircle, Trash2, Play, Calendar, User, FolderInput } from 'lucide-react'
import { api } from '../lib/api'
import { isVideoFile } from '../lib/utils'
import { notificationManager } from '../lib/notificationManager'
import ThumbnailProgressModal, { ThumbnailProgressItem } from '../components/ThumbnailProgressModal'

interface ImportService {
  name: string
  platform: string
  content_type: string
  filename_pattern: string
  destination: string
  enabled: boolean
  parse_filename: boolean
  use_ytdlp?: boolean
}

interface UploadedFile {
  filename: string
  temp_path: string
  size: number
  parsed: {
    valid: boolean
    username: string | null
    datetime: string | null
    media_id: string | null
    error: string | null
  }
  // For manual override when parse_filename is false
  manual_datetime?: string
  manual_username?: string
}

interface ImportConfig {
  enabled: boolean
  temp_dir: string
  services: ImportService[]
  preset_patterns: Record<string, { name: string; pattern: string; example: string }>
}

export default function ManualImport() {
  useBreadcrumb(breadcrumbConfig['/import'])
  const queryClient = useQueryClient()
  const fileInputRef = useRef<HTMLInputElement>(null)
  const dropZoneRef = useRef<HTMLDivElement>(null)

  const [selectedService, setSelectedService] = useState<string>('')
  const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([])
  const [isDragging, setIsDragging] = useState(false)
  const [isUploading, setIsUploading] = useState(false)
  const [showProgress, setShowProgress] = useState(false)
  const [progressItems, setProgressItems] = useState<ThumbnailProgressItem[]>([])
  const [currentJobId, setCurrentJobId] = useState<string | null>(null)
  // Helper to get current datetime in datetime-local format
  const getCurrentDatetime = () => {
    const now = new Date()
    // Format: YYYY-MM-DDTHH:MM
    return now.toISOString().slice(0, 16)
  }

  const [globalDatetime, setGlobalDatetime] = useState<string>(getCurrentDatetime())
  const [globalUsername, setGlobalUsername] = useState<string>('')

  // Fetch import configuration
  const { data: config, isLoading } = useQuery<ImportConfig>({
    queryKey: ['manual-import-services'],
    queryFn: async () => (await api.getManualImportServices()) as ImportConfig
  })

  const enabledServices = config?.services?.filter((s: ImportService) => s.enabled) || []
  const currentService = enabledServices.find((s: ImportService) => s.name === selectedService)

  // Helper: Check if service needs manual date entry (no parsing AND no yt-dlp)
  const needsManualEntry = (service: ImportService | undefined) => {
    if (!service) return false
    return service.parse_filename === false && !service.use_ytdlp
  }

  // Upload mutation
  const uploadMutation = useMutation({
    mutationFn: async (files: File[]) => {
      setIsUploading(true)
      return api.uploadFilesForImport(files, selectedService)
    },
    onSuccess: (data: { session_id: string; files: UploadedFile[] }) => {
      setUploadedFiles(data.files)
      setIsUploading(false)
      notificationManager.success('Upload Complete', `Uploaded ${data.files.length} files`)
    },
    onError: (error: Error) => {
      setIsUploading(false)
      notificationManager.error('Upload Failed', error.message)
    }
  })

  // Process mutation - now returns a job ID for background processing
  type ProcessResponse = { job_id: string; status: string; total_files: number; message: string }

  const processMutation = useMutation({
    mutationFn: async (): Promise<ProcessResponse> => {
      const filesToProcess = uploadedFiles.map(f => ({
        temp_path: f.temp_path,
        filename: f.filename,
        // Include manual overrides - use global values as fallback
        manual_datetime: f.manual_datetime || globalDatetime || undefined,
        manual_username: f.manual_username || globalUsername || undefined
      }))
      return await api.processImportedFiles(filesToProcess, selectedService)
    },
    onSuccess: (data: ProcessResponse) => {
      // Start polling the job status
      setCurrentJobId(data.job_id)
    },
    onError: (error: Error) => {
      setShowProgress(false)
      setCurrentJobId(null)
      notificationManager.error('Processing Failed', error.message)
    }
  })

  // Poll job status when we have a job ID
  useEffect(() => {
    if (!currentJobId) return

    const pollInterval = setInterval(async () => {
      try {
        const status = await api.getImportJobStatus(currentJobId)

        // Update progress items from job results
        setProgressItems(prev => prev.map(item => {
          const result = status.results.find(r => r.filename === item.filename)
          if (result) {
            return {
              ...item,
              status: result.status === 'success' ? 'success' : result.status === 'error' ? 'error' : 'processing',
              error: result.error
            }
          }
          // If the file is being processed (current_file)
          if (status.current_file === item.filename) {
            return { ...item, status: 'processing' }
          }
          return item
        }))

        // Check if job is complete
        if (status.status === 'completed') {
          clearInterval(pollInterval)
          setCurrentJobId(null)

          setTimeout(() => {
            setShowProgress(false)
            setUploadedFiles([])
            notificationManager.success('Processing Complete', `Processed ${status.success_count} files, ${status.failed_count} failed`)
            queryClient.invalidateQueries({ queryKey: ['media'] })
            queryClient.invalidateQueries({ queryKey: ['file-inventory'] })
          }, 1000)
        }
      } catch (error) {
        console.error('Error polling job status:', error)
        // Don't stop polling on error, the job might still be running
      }
    }, 500) // Poll every 500ms

    return () => clearInterval(pollInterval)
  }, [currentJobId, queryClient])

  // Handle file selection
  const handleFiles = useCallback((files: FileList | null) => {
    if (!files || files.length === 0) return
    if (!selectedService) {
      notificationManager.error('No Service Selected', 'Please select a service first')
      return
    }

    const fileArray = Array.from(files)
    uploadMutation.mutate(fileArray)
  }, [selectedService, uploadMutation])

  // Drag and drop handlers
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(true)
  }, [])

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(false)
  }, [])

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsDragging(false)
    handleFiles(e.dataTransfer.files)
  }, [handleFiles])

  // Process files
  const handleProcess = () => {
    if (uploadedFiles.length === 0) return

    // Initialize progress items with thumbnails from temp paths
    setProgressItems(uploadedFiles.map(f => {
      const fileType = isVideoFile(f.filename) ? 'video' as const : 'image' as const
      return {
        id: f.temp_path,
        filename: f.filename,
        status: 'pending' as const,
        fileType,
        thumbnailUrl: api.getMediaThumbnailUrl(f.temp_path, fileType),
      }
    }))
    setShowProgress(true)

    // Mark all as processing
    setProgressItems(prev => prev.map(item => ({ ...item, status: 'processing' as const })))

    processMutation.mutate()
  }

  // Clear uploaded files
  const handleClear = async () => {
    try {
      await api.clearImportTemp()
      setUploadedFiles([])
      notificationManager.success('Files Cleared', 'Cleared uploaded files')
    } catch (error) {
      notificationManager.error('Clear Failed', 'Failed to clear files')
    }
  }

  // Remove single file
  const removeFile = (index: number) => {
    setUploadedFiles(prev => prev.filter((_, i) => i !== index))
  }

  // Update manual datetime for a file
  const updateManualDatetime = (index: number, datetime: string) => {
    setUploadedFiles(prev => prev.map((f, i) =>
      i === index ? { ...f, manual_datetime: datetime } : f
    ))
  }

  // Update manual username for a file
  const updateManualUsername = (index: number, username: string) => {
    setUploadedFiles(prev => prev.map((f, i) =>
      i === index ? { ...f, manual_username: username } : f
    ))
  }

  // Format file size
  const formatSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      </div>
    )
  }

  if (!config?.enabled) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <FolderInput className="w-8 h-8 text-orange-500" />
            Manual Import
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1">
            Upload and import media files from external sources
          </p>
        </div>
        <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-6 text-center">
          <AlertCircle className="w-12 h-12 text-yellow-500 mx-auto mb-4" />
          <h2 className="text-lg font-semibold text-yellow-800 dark:text-yellow-200 mb-2">
            Manual Import Not Configured
          </h2>
          <p className="text-yellow-700 dark:text-yellow-300 mb-4">
            Please configure Manual Import services in the Configuration page first.
          </p>
          <a
            href="/config"
            className="inline-block px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700"
          >
            Go to Configuration
          </a>
        </div>
      </div>
    )
  }

  if (enabledServices.length === 0) {
    return (
      <div className="space-y-6">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <FolderInput className="w-8 h-8 text-orange-500" />
            Manual Import
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1">
            Upload and import media files from external sources
          </p>
        </div>
        <div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-6 text-center">
          <AlertCircle className="w-12 h-12 text-yellow-500 mx-auto mb-4" />
          <h2 className="text-lg font-semibold text-yellow-800 dark:text-yellow-200 mb-2">
            No Services Enabled
          </h2>
          <p className="text-yellow-700 dark:text-yellow-300 mb-4">
            Please enable at least one import service in the Configuration page.
          </p>
          <a
            href="/config"
            className="inline-block px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700"
          >
            Go to Configuration
          </a>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
          <FolderInput className="w-8 h-8 text-orange-500" />
          Manual Import
        </h1>
        <p className="text-slate-600 dark:text-slate-400 mt-1">
          Upload and import media files from external sources
        </p>
      </div>

      {/* Service Selection */}
      <div className="card-glass-hover rounded-xl p-6">
        <h2 className="text-lg font-semibold mb-4 text-foreground">Select Service</h2>
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {enabledServices.map((service: ImportService) => (
            <button
              key={service.name}
              onClick={() => {
                setSelectedService(service.name)
                setUploadedFiles([])
              }}
              className={`p-4 rounded-xl border-2 text-left transition-all hover:scale-[1.02] ${
                selectedService === service.name
                  ? 'border-primary bg-primary/10'
                  : 'border-border hover:border-primary/50 hover:bg-secondary/50'
              }`}
            >
              <div className="font-medium text-foreground">{service.name}</div>
              <div className="text-sm text-muted-foreground">{service.platform}</div>
              <div className="text-xs text-muted-foreground/70 mt-1">
                {service.use_ytdlp ? 'Auto-fetch from YouTube' : service.parse_filename !== false ? 'Auto-parse filename' : 'Manual date entry'}
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* Upload Zone */}
      {selectedService && (
        <div className="card-glass-hover rounded-xl p-6">
          <h2 className="text-lg font-semibold mb-4 text-foreground">Upload Files</h2>

          <div
            ref={dropZoneRef}
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
            onClick={() => fileInputRef.current?.click()}
            className={`border-2 border-dashed rounded-xl p-12 text-center cursor-pointer transition-all ${
              isDragging
                ? 'border-primary bg-primary/10'
                : 'border-border hover:border-primary/50 hover:bg-secondary/30'
            }`}
          >
            <input
              ref={fileInputRef}
              type="file"
              multiple
              accept="image/*,video/*"
              onChange={(e) => handleFiles(e.target.files)}
              className="hidden"
            />

            {isUploading ? (
              <div className="flex flex-col items-center">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mb-4"></div>
                <p className="text-muted-foreground">Uploading files...</p>
              </div>
            ) : (
              <>
                <Upload className="w-12 h-12 text-muted-foreground/50 mx-auto mb-4" />
                <p className="text-muted-foreground mb-2">
                  Drag and drop files here, or click to browse
                </p>
                <p className="text-sm text-muted-foreground/70">
                  Supports images and videos
                </p>
              </>
            )}
          </div>

          {currentService && (
            <div className="mt-4 p-4 bg-secondary/50 rounded-xl">
              {!needsManualEntry(currentService) ? (
                <>
                  <div className="text-sm text-muted-foreground">
                    {currentService.use_ytdlp ? (
                      <><strong>Mode:</strong> Auto-fetch metadata from YouTube</>
                    ) : (
                      <><strong>Pattern:</strong> <code className="bg-secondary px-2 py-1 rounded">{currentService.filename_pattern}</code></>
                    )}
                  </div>
                  <div className="text-sm text-muted-foreground mt-1">
                    <strong>Destination:</strong> {currentService.destination}
                  </div>
                </>
              ) : (
                <>
                  <div className="text-sm text-muted-foreground mb-3">
                    <strong>Manual Entry Mode</strong> - Set the date/time for uploaded files
                  </div>
                  <div className="flex flex-wrap gap-4 items-end">
                    <div>
                      <label className="block text-xs text-muted-foreground mb-1">Date/Time for all files</label>
                      <input
                        type="datetime-local"
                        value={globalDatetime}
                        onChange={(e) => setGlobalDatetime(e.target.value)}
                        className="px-3 py-2 border border-border rounded-lg bg-background text-foreground"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-muted-foreground mb-1">Username for all files (optional)</label>
                      <input
                        type="text"
                        value={globalUsername}
                        onChange={(e) => setGlobalUsername(e.target.value)}
                        placeholder="e.g., evalongoria"
                        className="px-3 py-2 border border-border rounded-lg bg-background text-foreground w-48"
                      />
                    </div>
                  </div>
                  <div className="text-sm text-muted-foreground mt-3">
                    <strong>Destination:</strong> {currentService.destination}
                  </div>
                </>
              )}
            </div>
          )}
        </div>
      )}

      {/* Uploaded Files Preview */}
      {uploadedFiles.length > 0 && (
        <div className="card-glass-hover rounded-xl p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-foreground">
              Uploaded Files ({uploadedFiles.length})
            </h2>
            <div className="flex gap-2">
              <button
                onClick={handleClear}
                className="px-4 py-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-xl flex items-center gap-2 transition-colors"
              >
                <Trash2 className="w-4 h-4" />
                Clear All
              </button>
              <button
                onClick={handleProcess}
                disabled={processMutation.isPending}
                className="px-4 py-2 bg-primary hover:bg-primary/90 text-primary-foreground rounded-xl disabled:opacity-50 flex items-center gap-2 transition-colors"
              >
                <Play className="w-4 h-4" />
                Process All
              </button>
            </div>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="text-left text-sm text-muted-foreground border-b border-border">
                  <th className="pb-3 pr-4">File</th>
                  <th className="pb-3 pr-4">Size</th>
                  <th className="pb-3 pr-4">Username</th>
                  <th className="pb-3 pr-4">Date/Time</th>
                  <th className="pb-3 pr-4">Status</th>
                  <th className="pb-3"></th>
                </tr>
              </thead>
              <tbody>
                {uploadedFiles.map((file, index) => (
                  <tr key={index} className="border-b border-border table-row-hover-stripe">
                    <td className="py-3 pr-4">
                      <div className="flex items-center gap-2">
                        {isVideoFile(file.filename) ? (
                          <FileVideo className="w-5 h-5 text-purple-500" />
                        ) : (
                          <FileImage className="w-5 h-5 text-blue-500" />
                        )}
                        <span className="text-sm text-foreground truncate max-w-xs" title={file.filename}>
                          {file.filename}
                        </span>
                      </div>
                    </td>
                    <td className="py-3 pr-4 text-sm text-muted-foreground">
                      {formatSize(file.size)}
                    </td>
                    <td className="py-3 pr-4">
                      {!needsManualEntry(currentService) ? (
                        <div className="flex items-center gap-1">
                          <User className="w-4 h-4 text-muted-foreground" />
                          <span className={`text-sm ${file.parsed.username ? 'text-foreground' : 'text-muted-foreground'}`}>
                            {file.parsed.username || (currentService?.use_ytdlp ? 'From YouTube' : 'Unknown')}
                          </span>
                        </div>
                      ) : (
                        <input
                          type="text"
                          value={file.manual_username || ''}
                          onChange={(e) => updateManualUsername(index, e.target.value)}
                          placeholder="Enter username"
                          className="text-sm px-2 py-1 border border-border rounded-lg bg-background text-foreground w-32"
                        />
                      )}
                    </td>
                    <td className="py-3 pr-4">
                      {!needsManualEntry(currentService) ? (
                        <div className="flex items-center gap-1">
                          <Calendar className="w-4 h-4 text-muted-foreground" />
                          <span className={`text-sm ${file.parsed.datetime ? 'text-foreground' : 'text-muted-foreground'}`}>
                            {file.parsed.datetime
                              ? new Date(file.parsed.datetime).toLocaleString()
                              : (currentService?.use_ytdlp ? 'From YouTube' : 'Unknown')}
                          </span>
                        </div>
                      ) : (
                        <input
                          type="datetime-local"
                          value={file.manual_datetime || ''}
                          onChange={(e) => updateManualDatetime(index, e.target.value)}
                          className="text-sm px-2 py-1 border border-border rounded-lg bg-background text-foreground"
                        />
                      )}
                    </td>
                    <td className="py-3 pr-4">
                      {file.parsed.valid || needsManualEntry(currentService) || currentService?.use_ytdlp ? (
                        <span className="inline-flex items-center gap-1 text-green-600 text-sm">
                          <Check className="w-4 h-4" />
                          Ready
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 text-red-600 text-sm" title={file.parsed.error || ''}>
                          <X className="w-4 h-4" />
                          Parse Error
                        </span>
                      )}
                    </td>
                    <td className="py-3">
                      <button
                        onClick={() => removeFile(index)}
                        className="p-1 text-muted-foreground hover:text-red-600 transition-colors"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Progress Modal */}
      <ThumbnailProgressModal
        isOpen={showProgress}
        title="Processing Files"
        items={progressItems}
        onClose={() => setShowProgress(false)}
      />
    </div>
  )
}
