import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  LayoutGrid, LayoutList, Download, Archive, Image, Film, Box, FileCode2, Layers,
  ChevronLeft, ChevronRight, Search,
} from 'lucide-react'
import { toast } from 'sonner'
import {
  getMediaAssets, zipDownloadAssets, archiveMediaAsset,
} from '../api/media'
import type { MediaAsset, MediaAssetType, MediaFilter } from '../api/media'

// ── Helpers ───────────────────────────────────────────────────────────────────

const formatBytes = (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`
}

const formatDate = (iso: string) =>
  new Date(iso).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })

const TYPE_COLORS: Record<MediaAssetType, string> = {
  thumbnail:        'bg-gray-100 text-gray-700',
  still:            'bg-blue-100 text-blue-700',
  turntable:        'bg-purple-100 text-purple-700',
  stl_low:          'bg-yellow-100 text-yellow-700',
  stl_high:         'bg-orange-100 text-orange-700',
  gltf_geometry:    'bg-green-100 text-green-700',
  gltf_production:  'bg-emerald-100 text-emerald-700',
  blend_production: 'bg-pink-100 text-pink-700',
}

const ALL_TYPES: MediaAssetType[] = [
  'thumbnail', 'still', 'turntable',
  'stl_low', 'stl_high',
  'gltf_geometry', 'gltf_production', 'blend_production',
]

const isImageAsset = (type: MediaAssetType) => type === 'thumbnail' || type === 'still'
const isVideoAsset = (type: MediaAssetType) => type === 'turntable'

// ── TypeIcon ─────────────────────────────────────────────────────────────────

function TypeIcon({ type }: { type: MediaAssetType }) {
  if (isImageAsset(type)) return <Image size={32} className="text-gray-400" />
  if (isVideoAsset(type)) return <Film size={32} className="text-gray-400" />
  if (type === 'stl_low' || type === 'stl_high') return <Box size={32} className="text-gray-400" />
  if (type === 'gltf_geometry' || type === 'gltf_production') return <FileCode2 size={32} className="text-gray-400" />
  return <Layers size={32} className="text-gray-400" />
}

// ── AssetCard (Grid) ──────────────────────────────────────────────────────────

function AssetCard({
  asset,
  selected,
  onToggle,
}: {
  asset: MediaAsset
  selected: boolean
  onToggle: () => void
}) {
  return (
    <div
      className={`relative rounded-lg border-2 overflow-hidden cursor-pointer transition-colors ${
        selected ? 'border-blue-500' : 'border-gray-200 hover:border-gray-300'
      }`}
      onClick={onToggle}
    >
      <input
        type="checkbox"
        checked={selected}
        onChange={onToggle}
        onClick={e => e.stopPropagation()}
        className="absolute top-2 left-2 z-10 w-4 h-4 cursor-pointer"
      />
      {isImageAsset(asset.asset_type) && asset.download_url ? (
        <img
          src={asset.download_url}
          alt={asset.asset_type}
          className="w-full h-40 object-cover bg-gray-50"
        />
      ) : (
        <div className="w-full h-40 flex items-center justify-center bg-gray-50">
          <TypeIcon type={asset.asset_type} />
        </div>
      )}
      <div className="p-2 space-y-1">
        <span
          className={`inline-block text-xs px-2 py-0.5 rounded-full font-medium ${TYPE_COLORS[asset.asset_type]}`}
        >
          {asset.asset_type}
        </span>
        {asset.file_size_bytes != null && (
          <p className="text-xs text-gray-500">{formatBytes(asset.file_size_bytes)}</p>
        )}
        <p className="text-xs text-gray-400">{formatDate(asset.created_at)}</p>
      </div>
    </div>
  )
}

// ── AssetRow (List) ───────────────────────────────────────────────────────────

function AssetRow({
  asset,
  selected,
  onToggle,
  onArchive,
  onDownload,
}: {
  asset: MediaAsset
  selected: boolean
  onToggle: () => void
  onArchive: () => void
  onDownload: () => void
}) {
  return (
    <tr className={`border-b border-gray-100 hover:bg-gray-50 transition-colors ${selected ? 'bg-blue-50' : ''}`}>
      <td className="px-4 py-3">
        <input type="checkbox" checked={selected} onChange={onToggle} className="w-4 h-4" />
      </td>
      <td className="px-4 py-3">
        <span className={`inline-block text-xs px-2 py-0.5 rounded-full font-medium ${TYPE_COLORS[asset.asset_type]}`}>
          {asset.asset_type}
        </span>
      </td>
      <td className="px-4 py-3 text-sm text-gray-700 font-mono truncate max-w-xs">
        {asset.storage_key}
      </td>
      <td className="px-4 py-3 text-sm text-gray-500">
        {asset.file_size_bytes != null ? formatBytes(asset.file_size_bytes) : '—'}
      </td>
      <td className="px-4 py-3 text-sm text-gray-500">
        {asset.mime_type ?? '—'}
      </td>
      <td className="px-4 py-3 text-sm text-gray-500">
        {formatDate(asset.created_at)}
      </td>
      <td className="px-4 py-3 flex items-center gap-2">
        {asset.download_url && (
          <button
            onClick={onDownload}
            className="p-1.5 rounded hover:bg-gray-200 text-gray-500 hover:text-gray-700 transition-colors"
            title="Download"
          >
            <Download size={15} />
          </button>
        )}
        <button
          onClick={onArchive}
          className="p-1.5 rounded hover:bg-red-100 text-gray-500 hover:text-red-600 transition-colors"
          title="Archive"
        >
          <Archive size={15} />
        </button>
      </td>
    </tr>
  )
}

// ── Page ──────────────────────────────────────────────────────────────────────

const PAGE_SIZE = 50

export default function MediaBrowserPage() {
  const qc = useQueryClient()

  const [view, setView] = useState<'grid' | 'list'>('grid')
  const [assetType, setAssetType] = useState<MediaAssetType | ''>('')
  const [productIdInput, setProductIdInput] = useState('')
  const [page, setPage] = useState(0)
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())

  const filter: MediaFilter = {
    asset_type: assetType || undefined,
    product_id: productIdInput.trim() || undefined,
    skip: page * PAGE_SIZE,
    limit: PAGE_SIZE,
  }

  const { data: assets = [], isLoading } = useQuery({
    queryKey: ['media', filter],
    queryFn: () => getMediaAssets(filter),
  })

  const archiveMutation = useMutation({
    mutationFn: archiveMediaAsset,
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['media'] })
      toast.success('Asset archived')
    },
    onError: () => toast.error('Failed to archive asset'),
  })

  const toggleSelect = (id: string) => {
    setSelectedIds(prev => {
      const next = new Set(prev)
      next.has(id) ? next.delete(id) : next.add(id)
      return next
    })
  }

  const toggleAll = () => {
    if (selectedIds.size === assets.length) {
      setSelectedIds(new Set())
    } else {
      setSelectedIds(new Set(assets.map(a => a.id)))
    }
  }

  const handleZipDownload = async () => {
    try {
      await zipDownloadAssets([...selectedIds])
      toast.success('ZIP download started')
    } catch {
      toast.error('ZIP download failed')
    }
  }

  const handleArchiveSelected = async () => {
    for (const id of selectedIds) {
      await archiveMutation.mutateAsync(id)
    }
    setSelectedIds(new Set())
  }

  const handleDownload = (asset: MediaAsset) => {
    if (asset.download_url) {
      window.open(asset.download_url, '_blank')
    }
  }

  return (
    <div className="p-6 space-y-5 max-w-screen-xl">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold text-content">Media Browser</h1>
          <p className="text-sm text-content-muted mt-0.5">
            Browse and manage rendered media assets
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setView('grid')}
            className={`p-2 rounded-md transition-colors ${
              view === 'grid' ? 'bg-accent-light text-accent' : 'text-content-secondary hover:bg-surface-hover'
            }`}
            title="Grid view"
          >
            <LayoutGrid size={18} />
          </button>
          <button
            onClick={() => setView('list')}
            className={`p-2 rounded-md transition-colors ${
              view === 'list' ? 'bg-accent-light text-accent' : 'text-content-secondary hover:bg-surface-hover'
            }`}
            title="List view"
          >
            <LayoutList size={18} />
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-3 items-center">
        <div className="relative">
          <Search size={15} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-400" />
          <input
            type="text"
            placeholder="Filter by product ID..."
            value={productIdInput}
            onChange={e => { setProductIdInput(e.target.value); setPage(0) }}
            className="pl-8 pr-3 py-2 text-sm border border-border-default rounded-md bg-surface focus:outline-none focus:ring-1 focus:ring-accent w-64"
          />
        </div>
        <select
          value={assetType}
          onChange={e => { setAssetType(e.target.value as MediaAssetType | ''); setPage(0) }}
          className="px-3 py-2 text-sm border border-border-default rounded-md bg-surface focus:outline-none focus:ring-1 focus:ring-accent"
        >
          <option value="">All types</option>
          {ALL_TYPES.map(t => (
            <option key={t} value={t}>{t}</option>
          ))}
        </select>
        {selectedIds.size > 0 && (
          <span className="text-sm text-content-muted">{selectedIds.size} selected</span>
        )}
      </div>

      {/* Content */}
      {isLoading ? (
        <div className="flex items-center justify-center h-48 text-content-muted text-sm">
          Loading assets…
        </div>
      ) : assets.length === 0 ? (
        <div className="flex flex-col items-center justify-center h-48 text-content-muted">
          <Image size={40} className="mb-3 opacity-30" />
          <p className="text-sm">No assets found</p>
        </div>
      ) : view === 'grid' ? (
        <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
          {assets.map(asset => (
            <AssetCard
              key={asset.id}
              asset={asset}
              selected={selectedIds.has(asset.id)}
              onToggle={() => toggleSelect(asset.id)}
            />
          ))}
        </div>
      ) : (
        <div className="bg-surface border border-border-default rounded-lg overflow-hidden">
          <table className="w-full text-left">
            <thead className="bg-surface-alt border-b border-border-default">
              <tr>
                <th className="px-4 py-3">
                  <input
                    type="checkbox"
                    checked={assets.length > 0 && selectedIds.size === assets.length}
                    onChange={toggleAll}
                    className="w-4 h-4"
                  />
                </th>
                <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">Type</th>
                <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">Storage Key</th>
                <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">Size</th>
                <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">MIME</th>
                <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">Created</th>
                <th className="px-4 py-3 text-xs font-semibold text-content-muted uppercase tracking-wide">Actions</th>
              </tr>
            </thead>
            <tbody>
              {assets.map(asset => (
                <AssetRow
                  key={asset.id}
                  asset={asset}
                  selected={selectedIds.has(asset.id)}
                  onToggle={() => toggleSelect(asset.id)}
                  onArchive={() => archiveMutation.mutate(asset.id)}
                  onDownload={() => handleDownload(asset)}
                />
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Pagination */}
      {(assets.length === PAGE_SIZE || page > 0) && (
        <div className="flex items-center gap-3 justify-center">
          <button
            disabled={page === 0}
            onClick={() => setPage(p => Math.max(0, p - 1))}
            className="p-2 rounded-md border border-border-default hover:bg-surface-hover disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
          >
            <ChevronLeft size={16} />
          </button>
          <span className="text-sm text-content-muted">Page {page + 1}</span>
          <button
            disabled={assets.length < PAGE_SIZE}
            onClick={() => setPage(p => p + 1)}
            className="p-2 rounded-md border border-border-default hover:bg-surface-hover disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
          >
            <ChevronRight size={16} />
          </button>
        </div>
      )}

      {/* Floating Action Bar */}
      {selectedIds.size > 0 && (
        <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 bg-gray-900 text-white rounded-xl shadow-2xl px-6 py-3 flex items-center gap-4">
          <span className="text-sm font-medium">{selectedIds.size} selected</span>
          <button
            onClick={handleZipDownload}
            className="flex items-center gap-2 text-sm bg-blue-600 hover:bg-blue-700 px-4 py-2 rounded-lg transition-colors"
          >
            <Download size={16} />
            ZIP download
          </button>
          <button
            onClick={handleArchiveSelected}
            className="flex items-center gap-2 text-sm bg-red-600 hover:bg-red-700 px-4 py-2 rounded-lg transition-colors"
          >
            <Archive size={16} />
            Archive
          </button>
          <button
            onClick={() => setSelectedIds(new Set())}
            className="text-gray-400 hover:text-white transition-colors text-lg leading-none"
            title="Clear selection"
          >
            ×
          </button>
        </div>
      )}
    </div>
  )
}
