import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useState, useRef, useCallback } from 'react'
import { useBreadcrumb } from '../../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../../config/breadcrumbConfig'
import {
  Plus,
  Link as LinkIcon,
  Upload,
  CheckCircle,
  AlertCircle,
  Loader2,
  Download,
  Calendar,
  Image,
  Video,
  File,
  X,
  Trash2,
  FolderOpen,
  Sparkles,
  ChevronRight,
  ArrowLeft,
  Layers,
} from 'lucide-react'
import { api, getErrorMessage, PaidContentCreator } from '../../lib/api'
import TagSearchSelector from '../../components/private-gallery/TagSearchSelector'
import { notificationManager } from '../../lib/notificationManager'

const SUPPORTED_HOSTS = [
  { name: 'Bunkr', domains: ['bunkr.sk', 'bunkr.si', 'bunkr.la', 'bunkrr.ru', 'bunkr.ph'] },
  { name: 'Pixeldrain', domains: ['pixeldrain.com'] },
  { name: 'Gofile', domains: ['gofile.io'] },
  { name: 'Cyberdrop', domains: ['cyberdrop.me', 'cyberdrop.to', 'cyberdrop.cc'] },
]

interface ImportResult {
  success: boolean
  message: string
  error?: string
}

interface SelectedFile {
  file: File
  preview?: string
  type: 'image' | 'video' | 'other'
  detectedDate?: string
  fanslyId?: string
  dateSource?: string
  confidence?: string
}

interface FileGroup {
  dateKey: string // YYYY-MM-DD or 'unknown'
  displayDate: string
  files: SelectedFile[]
  postDate: string
  postTime: string
  title: string
  description: string
  isAutoDetected: boolean
  selectedTags: number[] // Tag IDs
}

function getFileType(file: File): 'image' | 'video' | 'other' {
  if (file.type.startsWith('image/')) return 'image'
  if (file.type.startsWith('video/')) return 'video'
  return 'other'
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
  return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
}

function formatTimeForInput(isoString: string | null): string {
  if (!isoString) return '12:00'
  const date = new Date(isoString)
  return `${date.getUTCHours().toString().padStart(2, '0')}:${date.getUTCMinutes().toString().padStart(2, '0')}`
}

function getDateKey(isoString: string | null): string {
  if (!isoString) return 'unknown'
  return isoString.split('T')[0]
}

function formatDateKeyForDisplay(dateKey: string): string {
  if (dateKey === 'unknown') return 'Unknown Date'
  const date = new Date(dateKey + 'T12:00:00')
  return date.toLocaleDateString('en-US', {
    weekday: 'short',
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  })
}

type UploadStep = 'files' | 'details'

export default function PaidContentAddContent() {
  useBreadcrumb(breadcrumbConfig['/paid-content/add'])
  const queryClient = useQueryClient()
  const fileInputRef = useRef<HTMLInputElement>(null)

  const [activeTab, setActiveTab] = useState<'url' | 'upload'>('upload')
  const [uploadStep, setUploadStep] = useState<UploadStep>('files')

  // URL Import state
  const [url, setUrl] = useState('')
  const [selectedCreator, setSelectedCreator] = useState<number | ''>('')
  const [importResults, setImportResults] = useState<ImportResult[]>([])

  // Manual Upload state
  const [uploadCreator, setUploadCreator] = useState<number | ''>('')
  const [selectedFiles, setSelectedFiles] = useState<SelectedFile[]>([])
  const [fileGroups, setFileGroups] = useState<FileGroup[]>([])
  const [isDragging, setIsDragging] = useState(false)
  const [isParsing, setIsParsing] = useState(false)
  const [isUploading, setIsUploading] = useState(false)
  const [uploadProgress, setUploadProgress] = useState<{ current: number; total: number } | null>(null)

  const { data: creatorsResponse } = useQuery({
    queryKey: ['paid-content-creators-list'],
    queryFn: () => api.paidContent.getCreators(),
  })
  const creators: PaidContentCreator[] | undefined = creatorsResponse
    ? (Array.isArray(creatorsResponse)
        ? creatorsResponse
        : (creatorsResponse as unknown as { creators?: PaidContentCreator[] })?.creators)
    : undefined

  // Fetch available tags
  const { data: tags = [] } = useQuery({
    queryKey: ['paid-content-tags'],
    queryFn: () => api.paidContent.getTags(),
  })

  // URL Import mutation
  const importMutation = useMutation({
    mutationFn: ({ url, creatorId }: { url: string; creatorId?: number }) =>
      api.paidContent.importUrl(url, creatorId),
    onSuccess: () => {
      setImportResults((prev) => [
        { success: true, message: `Successfully queued content for import` },
        ...prev,
      ])
      notificationManager.success('Import Started', 'Content import has been queued')
      setUrl('')
    },
    onError: (error: unknown) => {
      const message = getErrorMessage(error)
      setImportResults((prev) => [
        { success: false, message: 'Import failed', error: message },
        ...prev,
      ])
      notificationManager.error('Import Failed', message)
    },
  })

  const resetUploadForm = () => {
    selectedFiles.forEach((f) => {
      if (f.preview) URL.revokeObjectURL(f.preview)
    })
    setSelectedFiles([])
    setFileGroups([])
    setUploadStep('files')
    setIsUploading(false)
    setUploadProgress(null)
  }

  const handleImport = (e: React.FormEvent) => {
    e.preventDefault()
    if (!url.trim()) return
    importMutation.mutate({
      url: url.trim(),
      creatorId: selectedCreator ? Number(selectedCreator) : undefined,
    })
  }

  const detectHost = (inputUrl: string): string | null => {
    try {
      const urlObj = new URL(inputUrl)
      const domain = urlObj.hostname.toLowerCase().replace('www.', '')
      for (const host of SUPPORTED_HOSTS) {
        if (host.domains.includes(domain)) return host.name
      }
    } catch {
      return null
    }
    return null
  }

  const detectedHost = url ? detectHost(url) : null

  // Group files by detected date
  const groupFilesByDate = useCallback((files: SelectedFile[]): FileGroup[] => {
    const groups: Map<string, SelectedFile[]> = new Map()

    files.forEach((file) => {
      const dateKey = getDateKey(file.detectedDate || null)
      const existing = groups.get(dateKey) || []
      groups.set(dateKey, [...existing, file])
    })

    // Convert to array and sort by date (unknown last)
    const groupArray: FileGroup[] = []
    const sortedKeys = Array.from(groups.keys()).sort((a, b) => {
      if (a === 'unknown') return 1
      if (b === 'unknown') return -1
      return a.localeCompare(b)
    })

    sortedKeys.forEach((dateKey) => {
      const files = groups.get(dateKey)!
      const firstFileWithDate = files.find((f) => f.detectedDate)
      const isAutoDetected = dateKey !== 'unknown'

      groupArray.push({
        dateKey,
        displayDate: formatDateKeyForDisplay(dateKey),
        files,
        postDate: isAutoDetected ? dateKey : new Date().toISOString().split('T')[0],
        postTime: firstFileWithDate ? formatTimeForInput(firstFileWithDate.detectedDate || null) : '12:00',
        title: '',
        description: '',
        isAutoDetected,
        selectedTags: [],
      })
    })

    return groupArray
  }, [])

  // Parse filenames when files are added
  const parseFilenames = useCallback(
    async (files: SelectedFile[]) => {
      if (files.length === 0) {
        setFileGroups([])
        return
      }

      setIsParsing(true)
      try {
        const filenames = files.map((f) => f.file.name)
        const result = await api.paidContent.parseFilenames(filenames)

        // Update files with parsed info
        const updatedFiles = files.map((f, idx) => {
          const parsed = result.files[idx]
          return {
            ...f,
            detectedDate: parsed?.detected_date || undefined,
            fanslyId: parsed?.fansly_id || undefined,
            dateSource: parsed?.date_source || undefined,
            confidence: parsed?.confidence || undefined,
          }
        })
        setSelectedFiles(updatedFiles)

        // Group files by detected date
        const groups = groupFilesByDate(updatedFiles)
        setFileGroups(groups)
      } catch (error) {
        console.error('Failed to parse filenames:', error)
        // Still group files even if parsing fails
        const groups = groupFilesByDate(files)
        setFileGroups(groups)
      } finally {
        setIsParsing(false)
      }
    },
    [groupFilesByDate]
  )

  // File handling
  const processFiles = useCallback(
    (files: FileList | File[]) => {
      const fileArray = Array.from(files)
      const newFiles: SelectedFile[] = fileArray.map((file) => {
        const type = getFileType(file)
        let preview: string | undefined
        if (type === 'image') {
          preview = URL.createObjectURL(file)
        }
        return { file, preview, type }
      })

      const allFiles = [...selectedFiles, ...newFiles]
      setSelectedFiles(allFiles)
      parseFilenames(allFiles)
    },
    [selectedFiles, parseFilenames]
  )

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      processFiles(e.target.files)
    }
    e.target.value = ''
  }

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(true)
  }

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      processFiles(e.dataTransfer.files)
    }
  }

  const removeFile = (index: number) => {
    setSelectedFiles((prev) => {
      const newFiles = [...prev]
      if (newFiles[index].preview) {
        URL.revokeObjectURL(newFiles[index].preview!)
      }
      newFiles.splice(index, 1)
      parseFilenames(newFiles)
      return newFiles
    })
  }

  const clearAllFiles = () => {
    selectedFiles.forEach((f) => {
      if (f.preview) URL.revokeObjectURL(f.preview)
    })
    setSelectedFiles([])
    setFileGroups([])
  }

  const updateGroupField = (groupIndex: number, field: keyof FileGroup, value: string) => {
    setFileGroups((prev) => {
      const updated = [...prev]
      updated[groupIndex] = {
        ...updated[groupIndex],
        [field]: value,
        // Clear auto-detected flag if user changes date
        ...(field === 'postDate' || field === 'postTime' ? { isAutoDetected: false } : {}),
      }
      return updated
    })
  }



  const handleUpload = async (e: React.FormEvent) => {
    e.preventDefault()
    if (fileGroups.length === 0) {
      notificationManager.error('No Files', 'Please select at least one file to upload')
      return
    }
    if (!uploadCreator) {
      notificationManager.error('No Creator', 'Please select a creator to associate with this content')
      return
    }

    setIsUploading(true)
    setUploadProgress({ current: 0, total: fileGroups.length })

    let successCount = 0
    let failCount = 0

    for (let i = 0; i < fileGroups.length; i++) {
      const group = fileGroups[i]
      setUploadProgress({ current: i + 1, total: fileGroups.length })

      try {
        const formData = new FormData()
        formData.append('creator_id', uploadCreator.toString())
        formData.append('title', group.title.trim())
        formData.append('description', group.description.trim())
        formData.append('post_date', group.postDate)
        formData.append('tags', group.selectedTags.join(','))

        group.files.forEach((sf) => {
          formData.append('files', sf.file)
        })

        await api.paidContent.uploadContent(formData)

        successCount++
      } catch (error) {
        console.error(`Failed to upload group ${i + 1}:`, error)
        failCount++
      }
    }

    setIsUploading(false)
    setUploadProgress(null)

    if (successCount > 0) {
      notificationManager.success(
        'Upload Complete',
        `Successfully created ${successCount} post${successCount > 1 ? 's' : ''}${failCount > 0 ? ` (${failCount} failed)` : ''}`
      )
      resetUploadForm()
      queryClient.invalidateQueries({ queryKey: ['paid-content-feed'] })
      queryClient.invalidateQueries({ queryKey: ['paid-content-posts'] })
    } else {
      notificationManager.error('Upload Failed', 'All uploads failed. Please try again.')
    }
  }

  const goToDetails = () => {
    if (selectedFiles.length === 0) {
      notificationManager.error('No Files', 'Please select at least one file first')
      return
    }
    setUploadStep('details')
  }

  const goBackToFiles = () => {
    setUploadStep('files')
  }

  const totalSize = selectedFiles.reduce((acc, sf) => acc + sf.file.size, 0)
  const imageCount = selectedFiles.filter((sf) => sf.type === 'image').length
  const videoCount = selectedFiles.filter((sf) => sf.type === 'video').length
  const otherCount = selectedFiles.filter((sf) => sf.type === 'other').length
  const filesWithDates = selectedFiles.filter((sf) => sf.detectedDate).length
  const groupCount = fileGroups.length

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
          <Plus className="w-8 h-8 text-violet-500" />
          Add Content
        </h1>
        <p className="text-slate-600 dark:text-slate-400 mt-1">
          Import from URLs or upload files manually
        </p>
      </div>

      {/* Tabs */}
      <div className="bg-card rounded-xl border border-border overflow-hidden">
        <div className="border-b border-border">
          <div className="flex">
            <button
              onClick={() => setActiveTab('upload')}
              className={`flex-1 py-3 px-4 text-sm font-medium transition-colors ${
                activeTab === 'upload'
                  ? 'text-primary border-b-2 border-primary bg-primary/5'
                  : 'text-muted-foreground hover:text-foreground'
              }`}
            >
              <Upload className="w-4 h-4 inline mr-2" />
              Manual Upload
            </button>
            <button
              onClick={() => setActiveTab('url')}
              className={`flex-1 py-3 px-4 text-sm font-medium transition-colors ${
                activeTab === 'url'
                  ? 'text-primary border-b-2 border-primary bg-primary/5'
                  : 'text-muted-foreground hover:text-foreground'
              }`}
            >
              <LinkIcon className="w-4 h-4 inline mr-2" />
              Import from URL
            </button>
          </div>
        </div>

        <div className="p-6">
          {activeTab === 'url' && (
            <div className="space-y-6">
              <form onSubmit={handleImport} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">URL</label>
                  <div className="relative">
                    <input
                      type="url"
                      value={url}
                      onChange={(e) => setUrl(e.target.value)}
                      placeholder="https://bunkr.sk/a/albumid or https://pixeldrain.com/l/listid"
                      className="input w-full pr-24"
                      required
                    />
                    {detectedHost && (
                      <span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs font-medium text-emerald-600 dark:text-emerald-400 bg-emerald-100 dark:bg-emerald-900/30 px-2 py-1 rounded">
                        {detectedHost}
                      </span>
                    )}
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-foreground mb-1">
                    Associate with Creator (Optional)
                  </label>
                  <select
                    value={selectedCreator}
                    onChange={(e) => setSelectedCreator(e.target.value ? Number(e.target.value) : '')}
                    className="input w-full"
                  >
                    <option value="">No creator selected</option>
                    {creators?.map((creator) => (
                      <option key={creator.id} value={creator.id}>
                        {creator.username} ({creator.platform})
                      </option>
                    ))}
                  </select>
                </div>

                <button
                  type="submit"
                  disabled={importMutation.isPending || !url.trim()}
                  className="btn btn-primary w-full"
                >
                  {importMutation.isPending ? (
                    <>
                      <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                      Importing...
                    </>
                  ) : (
                    <>
                      <Download className="w-4 h-4 mr-2" />
                      Import Content
                    </>
                  )}
                </button>
              </form>

              {/* Supported Hosts */}
              <div className="bg-secondary/50 rounded-lg p-4">
                <h3 className="text-sm font-medium text-foreground mb-3">Supported File Hosts</h3>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                  {SUPPORTED_HOSTS.map((host) => (
                    <div
                      key={host.name}
                      className="flex items-center space-x-2 text-sm text-muted-foreground"
                    >
                      <CheckCircle className="w-4 h-4 text-emerald-500" />
                      <span>{host.name}</span>
                    </div>
                  ))}
                </div>
              </div>

              {/* Import Results */}
              {importResults.length > 0 && (
                <div className="space-y-3">
                  <h3 className="text-sm font-medium text-foreground">Recent Imports</h3>
                  <div className="space-y-2">
                    {importResults.slice(0, 5).map((result, index) => (
                      <div
                        key={index}
                        className={`flex items-start space-x-3 p-3 rounded-lg ${
                          result.success
                            ? 'bg-emerald-100 dark:bg-emerald-900/20'
                            : 'bg-red-100 dark:bg-red-900/20'
                        }`}
                      >
                        {result.success ? (
                          <CheckCircle className="w-5 h-5 text-emerald-600 dark:text-emerald-400 flex-shrink-0" />
                        ) : (
                          <AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0" />
                        )}
                        <div className="flex-1 min-w-0">
                          <p
                            className={`text-sm font-medium ${
                              result.success
                                ? 'text-emerald-700 dark:text-emerald-300'
                                : 'text-red-700 dark:text-red-300'
                            }`}
                          >
                            {result.message}
                          </p>
                          {result.error && (
                            <p className="text-xs text-red-600 dark:text-red-400">{result.error}</p>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {activeTab === 'upload' && (
            <div className="space-y-6">
              {/* Step Indicator */}
              <div className="flex items-center justify-center gap-4 mb-6">
                <div
                  className={`flex items-center gap-2 px-4 py-2 rounded-full transition-colors ${
                    uploadStep === 'files'
                      ? 'bg-primary text-primary-foreground'
                      : 'bg-secondary text-muted-foreground'
                  }`}
                >
                  <span className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center text-sm font-medium">
                    1
                  </span>
                  <span className="text-sm font-medium">Select Files</span>
                </div>
                <ChevronRight className="w-5 h-5 text-muted-foreground" />
                <div
                  className={`flex items-center gap-2 px-4 py-2 rounded-full transition-colors ${
                    uploadStep === 'details'
                      ? 'bg-primary text-primary-foreground'
                      : 'bg-secondary text-muted-foreground'
                  }`}
                >
                  <span className="w-6 h-6 rounded-full bg-white/20 flex items-center justify-center text-sm font-medium">
                    2
                  </span>
                  <span className="text-sm font-medium">Add Details</span>
                </div>
              </div>

              {uploadStep === 'files' && (
                <div className="space-y-6">
                  {/* File Upload Zone */}
                  <div
                    onDragOver={handleDragOver}
                    onDragLeave={handleDragLeave}
                    onDrop={handleDrop}
                    onClick={() => fileInputRef.current?.click()}
                    className={`border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition-all ${
                      isDragging
                        ? 'border-primary bg-primary/10'
                        : 'border-border hover:border-primary/50 hover:bg-secondary/50'
                    }`}
                  >
                    <input
                      ref={fileInputRef}
                      type="file"
                      multiple
                      accept="image/*,video/*"
                      onChange={handleFileSelect}
                      className="hidden"
                    />
                    <FolderOpen
                      className={`w-12 h-12 mx-auto mb-3 ${isDragging ? 'text-primary' : 'text-muted-foreground'}`}
                    />
                    <p className="text-sm font-medium text-foreground">
                      {isDragging ? 'Drop files here...' : 'Drag & drop files here'}
                    </p>
                    <p className="text-xs text-muted-foreground mt-1">or click to browse</p>
                    <p className="text-xs text-muted-foreground mt-3">
                      Supports images and videos • Auto-groups by detected date
                    </p>
                  </div>

                  {/* Parsing indicator */}
                  {isParsing && (
                    <div className="flex items-center justify-center gap-2 text-muted-foreground">
                      <Loader2 className="w-4 h-4 animate-spin" />
                      <span className="text-sm">Analyzing filenames...</span>
                    </div>
                  )}

                  {/* Selected Files */}
                  {selectedFiles.length > 0 && (
                    <div className="space-y-4">
                      <div className="flex items-center justify-between">
                        <h3 className="text-sm font-medium text-foreground">
                          Selected Files ({selectedFiles.length})
                        </h3>
                        <button
                          type="button"
                          onClick={clearAllFiles}
                          className="text-xs text-red-600 hover:text-red-700 flex items-center gap-1"
                        >
                          <Trash2 className="w-3 h-3" />
                          Clear All
                        </button>
                      </div>

                      {/* File Stats */}
                      <div className="flex flex-wrap gap-3 text-xs">
                        {imageCount > 0 && (
                          <span className="flex items-center gap-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 px-2 py-1 rounded">
                            <Image className="w-3 h-3" />
                            {imageCount} images
                          </span>
                        )}
                        {videoCount > 0 && (
                          <span className="flex items-center gap-1 bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 px-2 py-1 rounded">
                            <Video className="w-3 h-3" />
                            {videoCount} videos
                          </span>
                        )}
                        {otherCount > 0 && (
                          <span className="flex items-center gap-1 bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 px-2 py-1 rounded">
                            <File className="w-3 h-3" />
                            {otherCount} other
                          </span>
                        )}
                        <span className="text-muted-foreground">Total: {formatFileSize(totalSize)}</span>
                        {filesWithDates > 0 && (
                          <span className="flex items-center gap-1 bg-emerald-100 dark:bg-emerald-900/30 text-emerald-700 dark:text-emerald-300 px-2 py-1 rounded">
                            <Sparkles className="w-3 h-3" />
                            {filesWithDates} with dates
                          </span>
                        )}
                        {groupCount > 1 && (
                          <span className="flex items-center gap-1 bg-violet-100 dark:bg-violet-900/30 text-violet-700 dark:text-violet-300 px-2 py-1 rounded">
                            <Layers className="w-3 h-3" />
                            {groupCount} groups
                          </span>
                        )}
                      </div>

                      {/* Group Preview */}
                      {groupCount > 1 && (
                        <div className="bg-violet-50 dark:bg-violet-900/20 rounded-lg p-3">
                          <div className="flex items-center gap-2 mb-2">
                            <Layers className="w-4 h-4 text-violet-600 dark:text-violet-400" />
                            <span className="text-sm font-medium text-violet-700 dark:text-violet-300">
                              Files will be grouped into {groupCount} posts by date
                            </span>
                          </div>
                          <div className="flex flex-wrap gap-2">
                            {fileGroups.map((group, idx) => (
                              <span
                                key={idx}
                                className="text-xs bg-violet-200 dark:bg-violet-800 text-violet-800 dark:text-violet-200 px-2 py-1 rounded"
                              >
                                {group.displayDate} ({group.files.length} files)
                              </span>
                            ))}
                          </div>
                        </div>
                      )}

                      {/* File Grid */}
                      <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3 max-h-80 overflow-y-auto p-1">
                        {selectedFiles.map((sf, index) => (
                          <div
                            key={index}
                            className="relative group aspect-square bg-secondary rounded-lg overflow-hidden"
                          >
                            {sf.type === 'image' && sf.preview ? (
                              <img src={sf.preview} alt={sf.file.name} className="w-full h-full object-cover" />
                            ) : sf.type === 'video' ? (
                              <div className="w-full h-full flex flex-col items-center justify-center bg-purple-100 dark:bg-purple-900/30">
                                <Video className="w-8 h-8 text-purple-600 dark:text-purple-400" />
                                <span className="text-[10px] text-purple-600 dark:text-purple-400 mt-1 px-1 text-center truncate w-full">
                                  {sf.file.name}
                                </span>
                              </div>
                            ) : (
                              <div className="w-full h-full flex flex-col items-center justify-center bg-gray-100 dark:bg-gray-800">
                                <File className="w-8 h-8 text-gray-600 dark:text-gray-400" />
                                <span className="text-[10px] text-gray-600 dark:text-gray-400 mt-1 px-1 text-center truncate w-full">
                                  {sf.file.name}
                                </span>
                              </div>
                            )}

                            {/* Date indicator */}
                            {sf.detectedDate && (
                              <div className="absolute top-1 left-1 p-1 bg-emerald-500 rounded-full">
                                <Calendar className="w-2.5 h-2.5 text-white" />
                              </div>
                            )}

                            {/* Remove button */}
                            <button
                              type="button"
                              onClick={() => removeFile(index)}
                              className="absolute top-1 right-1 p-1 bg-red-500 text-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                            >
                              <X className="w-3 h-3" />
                            </button>

                            {/* File size */}
                            <div className="absolute bottom-0 left-0 right-0 bg-black/60 text-white text-[10px] px-1 py-0.5 text-center">
                              {formatFileSize(sf.file.size)}
                            </div>
                          </div>
                        ))}
                      </div>

                      {/* Continue Button */}
                      <button
                        type="button"
                        onClick={goToDetails}
                        className="btn btn-primary w-full"
                        disabled={selectedFiles.length === 0}
                      >
                        Continue to Details
                        <ChevronRight className="w-4 h-4 ml-2" />
                      </button>
                    </div>
                  )}
                </div>
              )}

              {uploadStep === 'details' && (
                <form onSubmit={handleUpload} className="space-y-6">
                  {/* Back button */}
                  <button
                    type="button"
                    onClick={goBackToFiles}
                    className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
                    disabled={isUploading}
                  >
                    <ArrowLeft className="w-4 h-4" />
                    Back to file selection
                  </button>

                  {/* Creator Selection (applies to all groups) */}
                  <div className="bg-secondary/50 rounded-lg p-4">
                    <label className="block text-sm font-medium text-foreground mb-2">
                      Creator <span className="text-red-500">*</span>
                      <span className="text-xs text-muted-foreground ml-2">(applies to all posts)</span>
                    </label>
                    <select
                      value={uploadCreator}
                      onChange={(e) => setUploadCreator(e.target.value ? Number(e.target.value) : '')}
                      className="input w-full"
                      required
                      disabled={isUploading}
                    >
                      <option value="">Select a creator...</option>
                      {creators?.map((creator) => (
                        <option key={creator.id} value={creator.id}>
                          {creator.username} ({creator.platform})
                        </option>
                      ))}
                    </select>
                  </div>

                  {/* File Groups */}
                  <div className="space-y-4">
                    <h3 className="text-sm font-medium text-foreground flex items-center gap-2">
                      <Layers className="w-4 h-4" />
                      {fileGroups.length === 1 ? '1 Post' : `${fileGroups.length} Posts`} to Create
                    </h3>

                    {fileGroups.map((group, groupIndex) => {
                      const groupImageCount = group.files.filter((f) => f.type === 'image').length
                      const groupVideoCount = group.files.filter((f) => f.type === 'video').length

                      return (
                        <div
                          key={groupIndex}
                          className="border border-border rounded-xl overflow-hidden"
                        >
                          {/* Group Header */}
                          <div className="bg-secondary/50 px-4 py-3 flex items-center justify-between">
                            <div className="flex items-center gap-3">
                              <div className="flex items-center gap-2">
                                {group.isAutoDetected ? (
                                  <Sparkles className="w-4 h-4 text-emerald-500" />
                                ) : (
                                  <Calendar className="w-4 h-4 text-muted-foreground" />
                                )}
                                <span className="font-medium text-foreground">{group.displayDate}</span>
                              </div>
                              <span className="text-xs text-muted-foreground">
                                {group.files.length} {group.files.length === 1 ? 'file' : 'files'}
                              </span>
                            </div>
                            <div className="flex gap-2">
                              {groupImageCount > 0 && (
                                <span className="text-xs bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 px-2 py-0.5 rounded">
                                  {groupImageCount} img
                                </span>
                              )}
                              {groupVideoCount > 0 && (
                                <span className="text-xs bg-purple-100 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 px-2 py-0.5 rounded">
                                  {groupVideoCount} vid
                                </span>
                              )}
                            </div>
                          </div>

                          {/* Group Content */}
                          <div className="p-4 space-y-4">
                            {/* File thumbnails */}
                            <div className="flex gap-2 overflow-x-auto pb-2">
                              {group.files.slice(0, 8).map((sf, fileIndex) => (
                                <div
                                  key={fileIndex}
                                  className="flex-shrink-0 w-12 h-12 bg-secondary rounded overflow-hidden"
                                >
                                  {sf.type === 'image' && sf.preview ? (
                                    <img src={sf.preview} alt="" className="w-full h-full object-cover" />
                                  ) : sf.type === 'video' ? (
                                    <div className="w-full h-full flex items-center justify-center bg-purple-100 dark:bg-purple-900/30">
                                      <Video className="w-5 h-5 text-purple-600 dark:text-purple-400" />
                                    </div>
                                  ) : (
                                    <div className="w-full h-full flex items-center justify-center bg-gray-100 dark:bg-gray-800">
                                      <File className="w-5 h-5 text-gray-600 dark:text-gray-400" />
                                    </div>
                                  )}
                                </div>
                              ))}
                              {group.files.length > 8 && (
                                <div className="flex-shrink-0 w-12 h-12 bg-secondary rounded flex items-center justify-center">
                                  <span className="text-xs text-muted-foreground">+{group.files.length - 8}</span>
                                </div>
                              )}
                            </div>

                            {/* Date and Time */}
                            <div className="grid grid-cols-2 gap-3">
                              <div>
                                <label className="block text-xs text-muted-foreground mb-1">Date</label>
                                <input
                                  type="date"
                                  value={group.postDate}
                                  onChange={(e) => updateGroupField(groupIndex, 'postDate', e.target.value)}
                                  className="input w-full text-sm"
                                  disabled={isUploading}
                                />
                              </div>
                              <div>
                                <label className="block text-xs text-muted-foreground mb-1">Time</label>
                                <input
                                  type="time"
                                  value={group.postTime}
                                  onChange={(e) => updateGroupField(groupIndex, 'postTime', e.target.value)}
                                  className="input w-full text-sm"
                                  disabled={isUploading}
                                />
                              </div>
                            </div>

                            {/* Title */}
                            <div>
                              <label className="block text-xs text-muted-foreground mb-1">
                                Title (optional)
                              </label>
                              <input
                                type="text"
                                value={group.title}
                                onChange={(e) => updateGroupField(groupIndex, 'title', e.target.value)}
                                placeholder={`Auto: ${new Date(group.postDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })} — ${groupImageCount > 0 ? `${groupImageCount} ${groupImageCount === 1 ? 'image' : 'images'}` : ''}${groupImageCount > 0 && groupVideoCount > 0 ? ', ' : ''}${groupVideoCount > 0 ? `${groupVideoCount} ${groupVideoCount === 1 ? 'video' : 'videos'}` : ''}`}
                                className="input w-full text-sm"
                                disabled={isUploading}
                              />
                            </div>

                            {/* Description */}
                            <div>
                              <label className="block text-xs text-muted-foreground mb-1">
                                Description (optional)
                              </label>
                              <textarea
                                value={group.description}
                                onChange={(e) => updateGroupField(groupIndex, 'description', e.target.value)}
                                placeholder="Add notes..."
                                rows={2}
                                className="input w-full text-sm resize-none"
                                disabled={isUploading}
                              />
                            </div>

                            {/* Tags */}
                            {tags.length > 0 && (
                              <TagSearchSelector
                                tags={tags}
                                selectedTagIds={group.selectedTags || []}
                                onChange={(ids) => {
                                  setFileGroups((prev) => {
                                    const updated = [...prev]
                                    updated[groupIndex] = { ...updated[groupIndex], selectedTags: ids }
                                    return updated
                                  })
                                }}
                                label="Tags"
                                compact
                              />
                            )}
                          </div>
                        </div>
                      )
                    })}
                  </div>

                  {/* Upload Progress */}
                  {uploadProgress && (
                    <div className="bg-primary/10 rounded-lg p-4">
                      <div className="flex items-center gap-3">
                        <Loader2 className="w-5 h-5 animate-spin text-primary" />
                        <span className="text-sm font-medium text-foreground">
                          Uploading post {uploadProgress.current} of {uploadProgress.total}...
                        </span>
                      </div>
                      <div className="mt-2 h-2 bg-secondary rounded-full overflow-hidden">
                        <div
                          className="h-full bg-primary transition-all duration-300"
                          style={{ width: `${(uploadProgress.current / uploadProgress.total) * 100}%` }}
                        />
                      </div>
                    </div>
                  )}

                  {/* Submit Button */}
                  <button
                    type="submit"
                    disabled={isUploading || fileGroups.length === 0 || !uploadCreator}
                    className="btn btn-primary w-full"
                  >
                    {isUploading ? (
                      <>
                        <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                        Uploading...
                      </>
                    ) : (
                      <>
                        <Upload className="w-4 h-4 mr-2" />
                        Upload {fileGroups.length} {fileGroups.length === 1 ? 'Post' : 'Posts'} ({selectedFiles.length} files)
                      </>
                    )}
                  </button>
                </form>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Help Section */}
      <div className="bg-card rounded-xl border border-border p-6">
        <h3 className="text-lg font-semibold text-foreground mb-4">How It Works</h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="flex space-x-3">
            <div className="flex-shrink-0 w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center">
              <span className="text-sm font-bold text-primary">1</span>
            </div>
            <div>
              <h4 className="font-medium text-foreground">Drop Files</h4>
              <p className="text-sm text-muted-foreground mt-1">
                Drag & drop files. They&apos;re automatically grouped by detected date.
              </p>
            </div>
          </div>
          <div className="flex space-x-3">
            <div className="flex-shrink-0 w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center">
              <span className="text-sm font-bold text-primary">2</span>
            </div>
            <div>
              <h4 className="font-medium text-foreground">Review Groups</h4>
              <p className="text-sm text-muted-foreground mt-1">
                Each date group becomes a separate post. Adjust dates and add details.
              </p>
            </div>
          </div>
          <div className="flex space-x-3">
            <div className="flex-shrink-0 w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center">
              <span className="text-sm font-bold text-primary">3</span>
            </div>
            <div>
              <h4 className="font-medium text-foreground">Upload</h4>
              <p className="text-sm text-muted-foreground mt-1">
                All posts are created and added to the creator&apos;s feed.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
