'use client'

import { useState, useRef } from 'react'
import { Upload, X, Search, Grid, List, Image as ImageIcon, File, Download, Trash2 } from 'lucide-react'
import Image from 'next/image'

interface MediaFile {
  id: string
  name: string
  url: string
  type: string
  size: number
  uploadedAt: string
}

export default function MediaLibraryPage() {
  const [files, setFiles] = useState<MediaFile[]>([])
  const [view, setView] = useState<'grid' | 'list'>('grid')
  const [searchTerm, setSearchTerm] = useState('')
  const [uploading, setUploading] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFiles = Array.from(e.target.files || [])
    if (selectedFiles.length === 0) return

    setUploading(true)

    // In a real app, upload to server/cloud storage
    for (const file of selectedFiles) {
      const newFile: MediaFile = {
        id: Date.now().toString() + Math.random(),
        name: file.name,
        url: URL.createObjectURL(file),
        type: file.type,
        size: file.size,
        uploadedAt: new Date().toISOString(),
      }
      setFiles(prev => [newFile, ...prev])
    }

    setUploading(false)
    if (fileInputRef.current) fileInputRef.current.value = ''
  }

  const handleDelete = (id: string) => {
    if (confirm('Delete this file?')) {
      setFiles(prev => prev.filter(f => f.id !== id))
    }
  }

  const formatFileSize = (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 filteredFiles = files.filter(file =>
    file.name.toLowerCase().includes(searchTerm.toLowerCase())
  )

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-white mb-2">Media Library</h1>
          <p className="text-white/70">Manage images and files</p>
        </div>
        <button onClick={() => fileInputRef.current?.click()}
          className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all">
          <Upload className="w-5 h-5" />
          Upload Files
        </button>
        <input ref={fileInputRef} type="file" multiple accept="image/*,video/*,application/pdf"
          onChange={handleFileUpload} className="hidden" />
      </div>

      <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
        <div className="flex flex-col md:flex-row gap-4 items-center justify-between">
          <div className="relative flex-1 w-full">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-white/50" />
            <input type="text" placeholder="Search files..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary" />
          </div>
          <div className="flex gap-2">
            <button onClick={() => setView('grid')}
              className={`p-2 rounded-lg transition-all ${view === 'grid' ? 'bg-primary text-white' : 'bg-white/10 text-white/70 hover:bg-white/20'}`}>
              <Grid className="w-5 h-5" />
            </button>
            <button onClick={() => setView('list')}
              className={`p-2 rounded-lg transition-all ${view === 'list' ? 'bg-primary text-white' : 'bg-white/10 text-white/70 hover:bg-white/20'}`}>
              <List className="w-5 h-5" />
            </button>
          </div>
        </div>
      </div>

      {uploading && (
        <div className="bg-blue-500/20 border border-blue-500/50 rounded-xl p-4 text-center">
          <p className="text-blue-300">Uploading files...</p>
        </div>
      )}

      {view === 'grid' ? (
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
          {filteredFiles.map(file => (
            <div key={file.id} className="bg-white/10 backdrop-blur-xl rounded-xl border border-white/20 overflow-hidden hover:border-white/40 transition-all group">
              <div className="relative h-40 bg-white/5 flex items-center justify-center">
                {file.type.startsWith('image/') ? (
                  <Image src={file.url} alt={file.name} fill className="object-cover" />
                ) : (
                  <File className="w-16 h-16 text-white/30" />
                )}
                <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex gap-1">
                  <button onClick={() => window.open(file.url, '_blank')}
                    className="p-2 bg-blue-500 hover:bg-blue-600 rounded-lg transition-all">
                    <Download className="w-4 h-4 text-white" />
                  </button>
                  <button onClick={() => handleDelete(file.id)}
                    className="p-2 bg-red-500 hover:bg-red-600 rounded-lg transition-all">
                    <Trash2 className="w-4 h-4 text-white" />
                  </button>
                </div>
              </div>
              <div className="p-3">
                <p className="text-white text-sm truncate" title={file.name}>{file.name}</p>
                <p className="text-white/50 text-xs">{formatFileSize(file.size)}</p>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="bg-white/10 backdrop-blur-xl rounded-xl border border-white/20 overflow-hidden">
          <table className="w-full">
            <thead className="bg-white/5 border-b border-white/10">
              <tr>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Preview</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Name</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Size</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Uploaded</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-white">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/10">
              {filteredFiles.map(file => (
                <tr key={file.id} className="hover:bg-white/5 transition-colors">
                  <td className="px-6 py-4">
                    <div className="w-12 h-12 bg-white/5 rounded flex items-center justify-center">
                      {file.type.startsWith('image/') ? (
                        <Image src={file.url} alt={file.name} width={48} height={48} className="w-12 h-12 object-cover rounded" />
                      ) : (
                        <File className="w-6 h-6 text-white/30" />
                      )}
                    </div>
                  </td>
                  <td className="px-6 py-4 text-white">{file.name}</td>
                  <td className="px-6 py-4 text-white/70">{formatFileSize(file.size)}</td>
                  <td className="px-6 py-4 text-white/70">{new Date(file.uploadedAt).toLocaleDateString()}</td>
                  <td className="px-6 py-4">
                    <div className="flex gap-2">
                      <button onClick={() => window.open(file.url, '_blank')}
                        className="p-2 text-blue-400 hover:bg-blue-500/20 rounded-lg transition-all">
                        <Download className="w-4 h-4" />
                      </button>
                      <button onClick={() => handleDelete(file.id)}
                        className="p-2 text-red-400 hover:bg-red-500/20 rounded-lg transition-all">
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {filteredFiles.length === 0 && (
        <div className="bg-white/10 backdrop-blur-xl rounded-xl p-12 text-center border border-white/20">
          <ImageIcon className="w-16 h-16 text-white/30 mx-auto mb-4" />
          <p className="text-white/50">No files uploaded yet</p>
          <button onClick={() => fileInputRef.current?.click()}
            className="mt-4 px-6 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all">
            Upload Your First File
          </button>
        </div>
      )}
    </div>
  )
}
