import { useState, useEffect, useRef } from 'react'
import { Plus, Upload, Search, FolderOpen, ChevronRight, Grid3X3, X } from 'lucide-react'
import { api } from '../utils/api'
import AssetCard from '../components/AssetCard'
import Modal from '../components/Modal'
import BulkSelectBar from '../components/BulkSelectBar'
import CommentsSection from '../components/CommentsSection'
import { SkeletonAssetGrid } from '../components/SkeletonLoader'
import { useLanguage } from '../i18n/LanguageContext'
import { useToast } from '../components/ToastContainer'

export default function Assets() {
  const { t } = useLanguage()
  const toast = useToast()
  const [assets, setAssets] = useState([])
  const [loading, setLoading] = useState(true)
  const [filters, setFilters] = useState({ brand: '', tag: '', folder: '', search: '' })
  const [showUpload, setShowUpload] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [uploadProgress, setUploadProgress] = useState(0)
  const [dragOver, setDragOver] = useState(false)
  const [selectedAsset, setSelectedAsset] = useState(null)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [assetToDelete, setAssetToDelete] = useState(null)
  const fileRef = useRef(null)
  const [selectedIds, setSelectedIds] = useState(new Set())
  const [showBulkDeleteConfirm, setShowBulkDeleteConfirm] = useState(false)

  useEffect(() => { loadAssets() }, [])

  const loadAssets = async () => {
    try {
      const res = await api.get('/assets')
      const assetsData = Array.isArray(res) ? res : []
      // Map assets to include URL for thumbnails
      const assetsWithUrls = assetsData.map(asset => ({
        ...asset,
        _id: asset.id,
        name: asset.original_name || asset.filename,
        type: asset.mime_type?.startsWith('image') ? 'image' :
              asset.mime_type?.startsWith('video') ? 'video' :
              asset.mime_type?.startsWith('audio') ? 'audio' : 'document',
        url: `/api/uploads/${asset.filename}`,
        createdAt: asset.created_at,
        fileType: asset.mime_type?.split('/')[1]?.toUpperCase() || 'FILE',
      }))
      setAssets(assetsWithUrls)
    } catch (err) {
      console.error('Failed to load assets:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleUpload = async (files) => {
    if (!files || files.length === 0) return
    setUploading(true)
    setUploadProgress(0)
    
    try {
      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        const formData = new FormData()
        formData.append('file', file)
        formData.append('folder', 'general')
        formData.append('brand_id', '')
        formData.append('uploaded_by', '')
        
        // Use XMLHttpRequest to track upload progress
        await new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest()
          
          xhr.upload.addEventListener('progress', (e) => {
            if (e.lengthComputable) {
              const fileProgress = (e.loaded / e.total) * 100
              const totalProgress = ((i + fileProgress / 100) / files.length) * 100
              setUploadProgress(Math.round(totalProgress))
            }
          })
          
          xhr.addEventListener('load', () => {
            if (xhr.status >= 200 && xhr.status < 300) {
              resolve(JSON.parse(xhr.responseText))
            } else {
              reject(new Error(`Upload failed with status ${xhr.status}`))
            }
          })
          
          xhr.addEventListener('error', () => reject(new Error('Network error')))
          
          xhr.open('POST', '/api/assets/upload')
          xhr.send(formData)
        })
      }
      
      loadAssets()
      setShowUpload(false)
      setUploadProgress(0)
    } catch (err) {
      console.error('Upload failed:', err)
      toast.error(t('assets.uploadFailed') + ': ' + err.message)
    } finally {
      setUploading(false)
    }
  }

  const handleDeleteAsset = async (asset) => {
    setAssetToDelete(asset)
    setShowDeleteConfirm(true)
  }

  const confirmDeleteAsset = async () => {
    if (!assetToDelete) return
    try {
      await api.delete(`/assets/${assetToDelete.id || assetToDelete._id}`)
      setSelectedAsset(null)
      setAssetToDelete(null)
      loadAssets()
    } catch (err) {
      console.error('Delete failed:', err)
      toast.error(t('assets.failedToDelete'))
    }
  }

  const handleBulkDelete = async () => {
    try {
      await api.post('/assets/bulk-delete', { ids: [...selectedIds] })
      setSelectedIds(new Set())
      setShowBulkDeleteConfirm(false)
      loadAssets()
    } catch (err) {
      console.error('Bulk delete failed:', err)
      toast.error(t('common.deleteFailed'))
    }
  }

  const toggleSelect = (id) => {
    setSelectedIds(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const toggleSelectAll = () => {
    if (selectedIds.size === filteredAssets.length) setSelectedIds(new Set())
    else setSelectedIds(new Set(filteredAssets.map(a => a._id || a.id)))
  }

  const handleDrop = (e) => {
    e.preventDefault()
    setDragOver(false)
    handleUpload(e.dataTransfer.files)
  }

  // Get unique values for filters
  const brands = [...new Set(assets.map(a => a.brand).filter(Boolean))]
  const allTags = [...new Set(assets.flatMap(a => a.tags || []))]
  const folders = [...new Set(assets.map(a => a.folder).filter(Boolean))]

  const filteredAssets = assets.filter(a => {
    if (filters.brand && a.brand !== filters.brand) return false
    if (filters.tag && !(a.tags || []).includes(filters.tag)) return false
    if (filters.folder && a.folder !== filters.folder) return false
    if (filters.search && !a.name?.toLowerCase().includes(filters.search.toLowerCase())) return false
    return true
  })

  if (loading) {
    return (
      <div className="space-y-4">
        <div className="h-12 bg-surface-tertiary rounded-xl animate-pulse"></div>
        <SkeletonAssetGrid count={10} />
      </div>
    )
  }

  return (
    <div className="space-y-4 animate-fade-in">
      {/* Toolbar */}
      <div className="flex flex-wrap items-center gap-3">
        <div className="relative flex-1 min-w-[200px] max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-tertiary" />
          <input
            type="text"
            placeholder="Search assets..."
            value={filters.search}
            onChange={e => setFilters(f => ({ ...f, search: e.target.value }))}
            className="w-full pl-10 pr-4 py-2 text-sm border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-brand-primary/20 focus:border-brand-primary bg-white"
          />
        </div>

        <select
          value={filters.brand}
          onChange={e => setFilters(f => ({ ...f, brand: e.target.value }))}
          className="text-sm border border-border rounded-lg px-3 py-2 bg-white text-text-secondary focus:outline-none"
        >
          <option value="">All Brands</option>
          {brands.map(b => <option key={b} value={b}>{b}</option>)}
        </select>

        <select
          value={filters.tag}
          onChange={e => setFilters(f => ({ ...f, tag: e.target.value }))}
          className="text-sm border border-border rounded-lg px-3 py-2 bg-white text-text-secondary focus:outline-none"
        >
          <option value="">All Tags</option>
          {allTags.map(t => <option key={t} value={t}>{t}</option>)}
        </select>

        <button
          onClick={() => setShowUpload(true)}
          className="flex items-center gap-2 px-4 py-2 bg-brand-primary text-white rounded-lg text-sm font-medium hover:bg-brand-primary-light shadow-sm ml-auto"
        >
          <Upload className="w-4 h-4" />
          Upload
        </button>
      </div>

      {/* Folder breadcrumbs */}
      {folders.length > 0 && (
        <div className="flex items-center gap-2 flex-wrap">
          <button
            onClick={() => setFilters(f => ({ ...f, folder: '' }))}
            className={`flex items-center gap-1.5 text-sm px-3 py-1.5 rounded-lg transition-colors ${
              !filters.folder ? 'bg-brand-primary/10 text-brand-primary font-medium' : 'text-text-secondary hover:bg-surface-tertiary'
            }`}
          >
            <FolderOpen className="w-4 h-4" />
            All
          </button>
          {folders.map(folder => (
            <button
              key={folder}
              onClick={() => setFilters(f => ({ ...f, folder }))}
              className={`flex items-center gap-1.5 text-sm px-3 py-1.5 rounded-lg transition-colors ${
                filters.folder === folder ? 'bg-brand-primary/10 text-brand-primary font-medium' : 'text-text-secondary hover:bg-surface-tertiary'
              }`}
            >
              <FolderOpen className="w-4 h-4" />
              {folder}
            </button>
          ))}
        </div>
      )}

      {selectedIds.size > 0 && (
        <BulkSelectBar selectedCount={selectedIds.size} onDelete={() => setShowBulkDeleteConfirm(true)} onClear={() => setSelectedIds(new Set())} />
      )}

      {/* Asset grid */}
      {filteredAssets.length === 0 ? (
        <div className="py-20 text-center">
          <Grid3X3 className="w-12 h-12 text-text-tertiary mx-auto mb-3" />
          <p className="text-text-secondary font-medium">No assets found</p>
          <p className="text-sm text-text-tertiary mt-1">Upload your first asset to get started</p>
        </div>
      ) : (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 stagger-children">
          {filteredAssets.map(asset => (
            <div key={asset._id || asset.id} className="relative">
              <div className="absolute top-2 left-2 z-10" onClick={e => e.stopPropagation()}>
                <input type="checkbox" checked={selectedIds.has(asset._id || asset.id)} onChange={() => toggleSelect(asset._id || asset.id)} className="rounded border-border" />
              </div>
              <AssetCard asset={asset} onClick={setSelectedAsset} />
            </div>
          ))}
        </div>
      )}

      {/* Upload Modal */}
      <Modal isOpen={showUpload} onClose={() => !uploading && setShowUpload(false)} title="Upload Assets" size="md">
        <div
          onDragOver={(e) => { e.preventDefault(); setDragOver(true) }}
          onDragLeave={() => setDragOver(false)}
          onDrop={handleDrop}
          onClick={() => !uploading && fileRef.current?.click()}
          className={`border-2 border-dashed rounded-xl p-12 text-center transition-colors ${
            uploading ? 'cursor-not-allowed opacity-60' : 'cursor-pointer'
          } ${
            dragOver ? 'border-brand-primary bg-brand-primary/5' : 'border-border hover:border-brand-primary/50'
          }`}
        >
          <Upload className={`w-10 h-10 mx-auto mb-3 ${uploading ? 'animate-pulse' : ''} ${dragOver ? 'text-brand-primary' : 'text-text-tertiary'}`} />
          <p className="text-sm font-medium text-text-primary">
            {uploading ? `Uploading... ${uploadProgress}%` : 'Drop files here or click to browse'}
          </p>
          <p className="text-xs text-text-tertiary mt-1">
            Images, videos, documents up to 50MB
          </p>
          {uploading && (
            <div className="mt-4 w-full bg-surface-tertiary rounded-full h-2 overflow-hidden">
              <div 
                className="h-full bg-brand-primary transition-all duration-300"
                style={{ width: `${uploadProgress}%` }}
              />
            </div>
          )}
          <input
            ref={fileRef}
            type="file"
            multiple
            disabled={uploading}
            className="hidden"
            onChange={e => handleUpload(e.target.files)}
          />
        </div>
      </Modal>

      {/* Asset detail modal */}
      <Modal
        isOpen={!!selectedAsset}
        onClose={() => setSelectedAsset(null)}
        title={selectedAsset?.name || 'Asset Details'}
        size="lg"
      >
        {selectedAsset && (
          <div className="space-y-4">
            {selectedAsset.type === 'image' && selectedAsset.url && (
              <div className="rounded-lg overflow-hidden bg-surface-tertiary">
                <img src={selectedAsset.url} alt={selectedAsset.name} className="w-full max-h-[400px] object-contain" />
              </div>
            )}
            {selectedAsset.type === 'video' && selectedAsset.url && (
              <div className="rounded-lg overflow-hidden bg-surface-tertiary">
                <video src={selectedAsset.url} controls preload="metadata" className="w-full max-h-[400px]" />
              </div>
            )}
            <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                <p className="text-text-tertiary">Type</p>
                <p className="font-medium text-text-primary capitalize">{selectedAsset.type}</p>
              </div>
              <div>
                <p className="text-text-tertiary">Size</p>
                <p className="font-medium text-text-primary">{selectedAsset.size ? `${(selectedAsset.size / 1024 / 1024).toFixed(2)} MB` : '—'}</p>
              </div>
              {selectedAsset.brand_name && (
                <div>
                  <p className="text-text-tertiary">Brand</p>
                  <p className="font-medium text-text-primary">{selectedAsset.brand_name}</p>
                </div>
              )}
              {selectedAsset.folder && (
                <div>
                  <p className="text-text-tertiary">Folder</p>
                  <p className="font-medium text-text-primary">{selectedAsset.folder}</p>
                </div>
              )}
            </div>
            {selectedAsset.tags && selectedAsset.tags.length > 0 && (
              <div>
                <p className="text-sm text-text-tertiary mb-2">Tags</p>
                <div className="flex flex-wrap gap-2">
                  {selectedAsset.tags.map(tag => (
                    <span key={tag} className="text-xs px-2 py-1 rounded-full bg-surface-tertiary text-text-secondary">
                      {tag}
                    </span>
                  ))}
                </div>
              </div>
            )}
            <CommentsSection entityType="asset" entityId={selectedAsset.id || selectedAsset._id} />
            <div className="flex items-center gap-3 pt-4 border-t border-border">
              <button
                onClick={() => handleDeleteAsset(selectedAsset)}
                className="px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50 rounded-lg"
              >
                Delete Asset
              </button>
              <a
                href={selectedAsset.url}
                download={selectedAsset.name}
                target="_blank"
                rel="noopener noreferrer"
                className="ml-auto px-4 py-2 text-sm font-medium bg-brand-primary text-white rounded-lg hover:bg-brand-primary-light"
              >
                Download
              </a>
            </div>
          </div>
        )}
      </Modal>

      <Modal
        isOpen={showBulkDeleteConfirm}
        onClose={() => setShowBulkDeleteConfirm(false)}
        title={t('common.bulkDeleteConfirm').replace('{count}', selectedIds.size)}
        isConfirm
        danger
        confirmText={t('common.deleteSelected')}
        onConfirm={handleBulkDelete}
      >
        {t('common.bulkDeleteDesc')}
      </Modal>

      {/* Delete Asset Confirmation */}
      <Modal
        isOpen={showDeleteConfirm}
        onClose={() => { setShowDeleteConfirm(false); setAssetToDelete(null) }}
        title="Delete Asset?"
        isConfirm
        danger
        confirmText="Delete Asset"
        onConfirm={confirmDeleteAsset}
      >
        Are you sure you want to delete this asset? This file will be permanently removed from the server. This action cannot be undone.
      </Modal>
    </div>
  )
}
