File size: 21,586 Bytes
3c8d218
 
 
 
 
 
 
ef865f2
3c8d218
481e01c
ef865f2
3c8d218
 
 
 
 
 
 
 
 
 
 
481e01c
 
3c8d218
 
 
 
 
 
 
 
 
 
481e01c
3c8d218
 
 
 
 
481e01c
 
3c8d218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
481e01c
 
 
 
 
 
 
3c8d218
 
481e01c
3c8d218
 
 
ef865f2
3c8d218
 
 
 
 
 
 
 
481e01c
3c8d218
 
 
 
 
 
 
 
481e01c
 
 
 
 
 
 
 
 
 
 
 
3c8d218
 
 
 
 
 
 
 
 
 
 
 
481e01c
3c8d218
 
 
481e01c
3c8d218
 
 
 
7457a6f
 
 
 
3c8d218
 
 
 
7457a6f
3c8d218
7457a6f
3c8d218
481e01c
 
 
 
 
 
 
 
7457a6f
3c8d218
 
 
 
 
7457a6f
3c8d218
 
 
 
 
 
 
 
7457a6f
3c8d218
 
 
7457a6f
3c8d218
 
 
 
 
481e01c
 
 
 
7457a6f
3c8d218
 
 
 
 
 
 
 
 
7457a6f
3c8d218
7457a6f
 
3c8d218
 
 
 
7457a6f
3c8d218
 
 
 
 
 
 
 
481e01c
3c8d218
 
 
 
 
481e01c
 
 
 
 
 
3c8d218
 
 
 
 
 
 
 
 
7457a6f
3c8d218
 
 
7457a6f
 
3c8d218
 
 
 
7457a6f
 
3c8d218
 
 
7457a6f
3c8d218
 
 
 
 
 
 
 
7457a6f
 
3c8d218
7457a6f
3c8d218
 
 
 
7457a6f
3c8d218
 
 
 
7457a6f
3c8d218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7457a6f
 
 
 
3c8d218
 
7457a6f
3c8d218
 
 
 
7457a6f
3c8d218
 
 
 
 
 
 
 
 
 
 
7457a6f
3c8d218
 
 
7457a6f
 
 
3c8d218
 
 
 
 
481e01c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c8d218
 
 
 
 
7457a6f
3c8d218
 
 
 
 
 
 
 
 
 
 
 
7457a6f
 
 
 
3c8d218
 
7457a6f
3c8d218
 
 
 
7457a6f
3c8d218
 
7457a6f
3c8d218
 
 
 
 
7457a6f
3c8d218
7457a6f
3c8d218
 
 
 
 
 
 
7457a6f
3c8d218
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import React, { useState, useEffect } from 'react';
import { 
  File, Image as ImageIcon, Music, Video, Folder, 
  Plus, Trash2, Search, Filter, Upload, Tags, 
  ChevronRight, MoreVertical, X, Check, Info 
} from 'lucide-react';
import { AssetService } from '../services/api';
import { useAppContext } from './AppContext';

const MediaHubPage = ({ activeSpecId, activeSpecName }) => {
  const { addToast } = useAppContext();
  const [assets, setAssets] = useState([]);
  const [collections, setCollections] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [activeCategory, setActiveCategory] = useState('all');
  const [activeCollectionId, setActiveCollectionId] = useState(null);
  const [searchQuery, setSearchQuery] = useState('');
  
  // Upload State
  const [isUploading, setIsUploading] = useState(false);
  const [uploadForm, setUploadForm] = useState({
    description: '',
    tags: '',
    collectionId: ''
  });
  const [selectedFile, setSelectedFile] = useState(null);
  const [showUploadModal, setShowUploadModal] = useState(false);

  // New Collection State
  const [showNewCollectionModal, setShowNewCollectionModal] = useState(false);
  const [newColForm, setNewColForm] = useState({ name: '', description: '' });

  useEffect(() => {
    fetchData();
  }, [activeSpecId]); // Re-fetch when spec changes

  const fetchData = async () => {
    setIsLoading(true);
    try {
      const [assetsData, colsData] = await Promise.all([
        AssetService.getAllAssets(activeSpecId),
        AssetService.getCollections(activeSpecId)
      ]);
      setAssets(assetsData);
      setCollections(colsData);
    } catch (e) {
      console.error("Failed to fetch media data", e);
    } finally {
      setIsLoading(false);
    }
  };

  const handleFileUpload = async () => {
    if (!selectedFile) return;
    setIsUploading(true);
    try {
      const tags = uploadForm.tags.split(',').map(t => t.trim()).filter(t => t);
      await AssetService.uploadAsset(
        activeSpecId, 
        uploadForm.collectionId || null, 
        selectedFile, 
        uploadForm.description, 
        tags
      );
      setShowUploadModal(false);
      setSelectedFile(null);
      setUploadForm({ description: '', tags: '', collectionId: '' });
      fetchData();
    } catch (e) {
      console.error("Upload failed", e);
      addToast('error', e.message || "Failed to upload asset.");
    } finally {
      setIsUploading(false);
    }
  };

  const handleCreateCollection = async () => {
    if (!newColForm.name.trim()) return;
    try {
      await AssetService.createCollection(newColForm.name, activeSpecId, newColForm.description);
      setShowNewCollectionModal(false);
      setNewColForm({ name: '', description: '' });
      fetchData();
    } catch (e) {
      console.error("Collection creation failed", e);
    }
  };

  const handleDeleteCollection = async (e, id) => {
    e.stopPropagation();
    if (!confirm('Are you sure you want to delete this collection? Assets will NOT be deleted.')) return;
    try {
      await AssetService.deleteCollection(id);
      if (activeCollectionId === id) setActiveCollectionId(null);
      fetchData();
    } catch (e) {
      console.error("Delete collection failed", e);
    }
  };

  const handleDeleteAsset = async (id) => {
    if (!confirm('Permanent delete this asset?')) return;
    try {
      await AssetService.deleteAsset(id);
      fetchData();
    } catch (e) {
       console.error("Delete failed", e);
    }
  };

  const filteredAssets = assets.filter(a => {
    const matchesCategory = activeCategory === 'all' || a.category === activeCategory;
    const matchesCollection = !activeCollectionId || (a.collection_ids && a.collection_ids.includes(activeCollectionId));
    const matchesSearch = a.name.toLowerCase().includes(searchQuery.toLowerCase()) || 
                         (a.description && a.description.toLowerCase().includes(searchQuery.toLowerCase())) ||
                         (a.tags && a.tags.some(t => t.toLowerCase().includes(searchQuery.toLowerCase())));
    return matchesCategory && matchesCollection && matchesSearch;
  });

  const getIcon = (category) => {
    switch(category) {
      case 'images': return <ImageIcon size={20} className="text-[var(--accent-secondary)]" />;
      case 'audio': return <Music size={20} className="text-[var(--accent-secondary)]" />;
      case 'video': return <Video size={20} className="text-[var(--accent-secondary)]" />;
      default: return <File size={20} className="text-[var(--accent-primary)]" />;
    }
  };

  return (
    <div className="flex-1 flex flex-col bg-[var(--bg-primary)] overflow-hidden">
      {/* Header */}
      <div className="h-14 border-b border-[var(--border-subtle)] flex items-center justify-between px-6 bg-[var(--bg-secondary)]">
        <div className="flex items-center space-x-4">
          <div className="flex flex-col">
            <h1 className="text-lg font-medium text-[var(--text-primary)] leading-none">Media Hub</h1>
            {activeSpecName && (
              <span className="text-[10px] text-[var(--accent-primary)] font-mono mt-1 opacity-80 uppercase tracking-widest">
                {activeSpecName}
              </span>
            )}
          </div>
          <div className="h-6 w-px bg-[var(--border-subtle)]" />
          <div className="flex space-x-2">
            {['all', 'documents', 'images', 'audio', 'video'].map(cat => (
              <button
                key={cat}
                onClick={() => setActiveCategory(cat)}
                className={`px-3 py-1 text-xs capitalize rounded-full transition ${activeCategory === cat ? 'bg-[var(--accent-primary)] text-white shadow-sm' : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)] bg-[var(--bg-tertiary)] hover:bg-[var(--bg-secondary)]'}`}
              >
                {cat}
              </button>
            ))}
          </div>
        </div>
        <div className="flex items-center space-x-3">
          <div className="relative">
            <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-secondary)]" />
            <input 
              type="text"
              placeholder="Search assets, tags, descriptions..."
              className="bg-[var(--bg-primary)] border border-[var(--border-subtle)] text-[var(--text-primary)] text-xs pl-9 pr-3 py-1.5 rounded-md w-64 outline-none focus:border-[var(--accent-primary)]"
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
            />
          </div>
          <button 
            onClick={() => {
              setUploadForm(prev => ({ ...prev, collectionId: activeCollectionId || '' }));
              setShowUploadModal(true);
            }}
            className="bg-[var(--accent-gradient)] hover:opacity-90 text-white px-4 py-1.5 text-xs rounded flex items-center space-x-2 transition shadow-lg"
          >
            <Upload size={14} />
            <span>Upload Asset</span>
          </button>
        </div>
      </div>

      <div className="flex-1 flex overflow-hidden">
        {/* Sidebar: Collections */}
        <div className="w-64 border-r border-[var(--border-subtle)] bg-[var(--bg-secondary)] flex flex-col p-4">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-[10px] uppercase font-bold text-[var(--text-secondary)] tracking-wider">Collections</h3>
            <button onClick={() => setShowNewCollectionModal(true)} className="text-[var(--text-secondary)] hover:text-[var(--text-primary)]"><Plus size={16}/></button>
          </div>
          <div className="flex-1 overflow-y-auto space-y-1">
            <button 
              onClick={() => setActiveCollectionId(null)}
              className={`w-full flex items-center space-x-2 px-3 py-2 rounded text-xs transition ${!activeCollectionId ? 'bg-[var(--bg-tertiary)] text-[var(--text-primary)] border border-[var(--border-subtle)]' : 'text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-primary)]'}`}
            >
              <Folder size={14} />
              <span>All Assets</span>
            </button>
            {collections.map(col => (
              <button 
                key={col.id}
                onClick={() => setActiveCollectionId(col.id)}
                className={`group w-full flex items-center justify-between px-3 py-2 rounded text-xs transition ${activeCollectionId === col.id ? 'bg-[var(--bg-tertiary)] text-[var(--text-primary)] border border-[var(--border-subtle)]' : 'text-[var(--text-secondary)] hover:bg-[var(--bg-tertiary)] hover:text-[var(--text-primary)]'}`}
              >
                <div className="flex items-center space-x-2">
                  <Folder size={14} />
                  <span>{col.name}</span>
                </div>
                <button 
                  onClick={(e) => handleDeleteCollection(e, col.id)}
                  className="p-1 opacity-0 group-hover:opacity-100 hover:text-red-400 transition"
                >
                  <Trash2 size={12} />
                </button>
              </button>
            ))}
          </div>
        </div>

        {/* Main Grid */}
        <div className="flex-1 overflow-y-auto p-6">
          {isLoading ? (
            <div className="flex items-center justify-center h-64">
              <Upload size={48} className="text-[var(--bg-tertiary)] animate-pulse" />
            </div>
          ) : filteredAssets.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-64 opacity-50">
              <ImageIcon size={64} className="mb-4 text-[var(--bg-tertiary)]" />
              <p className="text-[var(--text-secondary)]">No assets found in this category.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
              {filteredAssets.map(asset => (
                <div key={asset.id} className="bg-[var(--bg-secondary)] border border-[var(--border-subtle)] rounded-lg group hover:border-[var(--text-secondary)]/30 transition shadow-sm overflow-hidden">
                  <div className="h-32 bg-[var(--bg-primary)] flex items-center justify-center relative overflow-hidden">
                    {asset.category === 'images' ? (
                       <div className="w-full h-full bg-cover bg-center opacity-40 group-hover:opacity-60 transition" style={{ backgroundImage: `url(${import.meta.env.VITE_BACKEND_URL}/uploads/${asset.path})` }} />
                    ) : (
                       <div className="text-[var(--text-secondary)] opacity-20 uppercase font-black text-4xl select-none">{asset.type.split('/')[1]}</div>
                    )}
                    <div className="absolute inset-0 flex items-center justify-center">
                      {getIcon(asset.category)}
                    </div>
                  </div>
                  <div className="p-3 space-y-2">
                    <div className="flex items-start justify-between">
                      <div className="truncate pr-4">
                        <div className="text-xs font-medium text-[var(--text-primary)] truncate" title={asset.name}>{asset.name}</div>
                        <div className="text-[10px] text-[var(--text-secondary)] mt-0.5 opacity-60">{(asset.size / 1024).toFixed(1)} KB • {asset.type.split('/')[1]}</div>
                      </div>
                      <button onClick={() => handleDeleteAsset(asset.id)} className="text-[var(--text-secondary)] hover:text-red-400 transition opacity-0 group-hover:opacity-100">
                        <Trash2 size={14} />
                      </button>
                    </div>
                    {asset.description && (
                      <p className="text-[10px] text-[var(--text-secondary)] line-clamp-2 italic leading-relaxed">"{asset.description}"</p>
                    )}
                    {asset.tags && asset.tags.length > 0 && (
                      <div className="flex flex-wrap gap-1 pt-1">
                        {asset.tags.map(tag => (
                          <span key={tag} className="bg-[var(--bg-primary)] border border-[var(--border-subtle)] text-[var(--accent-primary)] text-[9px] px-1.5 py-0.5 rounded flex items-center space-x-1 font-mono">
                            <Tags size={8} />
                            <span>{tag}</span>
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Upload Modal */}
      {showUploadModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
           <div className="bg-[var(--bg-secondary)] border border-[var(--border-subtle)] rounded-lg shadow-2xl w-full max-w-lg overflow-hidden animate-in fade-in zoom-in duration-200">
              <div className="p-4 border-b border-[var(--border-subtle)] bg-[var(--bg-tertiary)] flex items-center justify-between">
                 <h3 className="text-sm font-semibold text-[var(--text-primary)] flex items-center space-x-2">
                    <Upload size={16} className="text-[var(--accent-primary)]" />
                    <span>Upload New Asset</span>
                 </h3>
                 <button onClick={() => setShowUploadModal(false)} className="text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition"><X size={18} /></button>
              </div>
              <div className="p-6 space-y-4">
                 <div 
                   onClick={() => document.getElementById('asset-file-input').click()}
                   className="border-2 border-dashed border-[var(--border-subtle)] rounded-lg p-8 flex flex-col items-center justify-center cursor-pointer hover:border-[var(--accent-primary)] hover:bg-[var(--accent-primary)]/5 transition"
                 >
                    <input 
                      id="asset-file-input" 
                      type="file" 
                      className="hidden" 
                      onChange={(e) => setSelectedFile(e.target.files[0])} 
                    />
                    {selectedFile ? (
                      <div className="text-center">
                        <Check size={32} className="text-green-500 mb-2 mx-auto" />
                        <div className="text-xs text-white font-medium">{selectedFile.name}</div>
                        <div className="text-[10px] text-[var(--text-secondary)] mt-1">{(selectedFile.size / 1024).toFixed(1)} KB</div>
                      </div>
                    ) : (
                      <div className="text-center">
                        <Upload size={32} className="text-[var(--text-secondary)] opacity-30 mb-2 mx-auto" />
                        <div className="text-xs text-[var(--text-secondary)]">Drag and drop or click to browse</div>
                        <div className="text-[10px] text-[var(--text-secondary)] opacity-40 mt-1 italic">Format reasoning: Images, Audio, Video, Docs</div>
                      </div>
                    )}
                 </div>

                 <div className="space-y-3">
                     <div className="space-y-1">
                        <label className="text-[10px] uppercase font-bold text-[var(--text-secondary)] tracking-wider">Add to Collection</label>
                        <select 
                          className="w-full bg-[var(--bg-primary)] border border-[var(--border-subtle)] text-[var(--text-primary)] px-3 py-2 text-xs rounded outline-none focus:border-[var(--accent-primary)] appearance-none cursor-pointer"
                          value={uploadForm.collectionId}
                          onChange={e => setUploadForm({...uploadForm, collectionId: e.target.value})}
                        >
                          <option value="">No Collection (Individual Asset)</option>
                          {collections.map(col => (
                            <option key={col.id} value={col.id}>{col.name}</option>
                          ))}
                        </select>
                     </div>
                     <div className="space-y-1">
                        <label className="text-[10px] uppercase font-bold text-[var(--text-secondary)] tracking-wider">Semantic Description (AI Hint)</label>
                        <textarea 
                          placeholder="Explain what this file is for (e.g. 'This is the Aadhar card used for user identity verification')"
                          className="w-full bg-[var(--bg-primary)] border border-[var(--border-subtle)] text-[var(--text-primary)] p-2.5 text-xs rounded outline-none focus:border-[var(--accent-primary)] resize-none h-20"
                          value={uploadForm.description}
                          onChange={e => setUploadForm({...uploadForm, description: e.target.value})}
                        />
                     </div>
                     <div className="space-y-1">
                        <label className="text-[10px] uppercase font-bold text-[var(--text-secondary)] tracking-wider">Tags (comma separated)</label>
                        <div className="relative">
                          <Tags size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-secondary)]" />
                          <input 
                            type="text"
                            placeholder="aadhar, identity, personal, legal"
                            className="w-full bg-[var(--bg-primary)] border border-[var(--border-subtle)] text-[var(--text-primary)] pl-10 pr-3 py-2 text-xs rounded outline-none focus:border-[var(--accent-primary)] font-mono"
                            value={uploadForm.tags}
                            onChange={e => setUploadForm({...uploadForm, tags: e.target.value})}
                          />
                        </div>
                     </div>
                 </div>

                 <button 
                   onClick={handleFileUpload}
                   disabled={!selectedFile || isUploading}
                   className="w-full bg-[var(--accent-gradient)] hover:opacity-90 disabled:opacity-50 text-white py-2.5 text-sm font-semibold rounded transition flex items-center justify-center space-x-2"
                 >
                    {isUploading ? <Upload className="animate-spin" size={16} /> : <Check size={16} />}
                    <span>{isUploading ? 'Uploading...' : 'Finalize Upload'}</span>
                 </button>
              </div>
           </div>
        </div>
      )}

      {/* New Collection Modal */}
      {showNewCollectionModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
           <div className="bg-[var(--bg-secondary)] border border-[var(--border-subtle)] rounded-lg shadow-2xl w-full max-w-sm overflow-hidden animate-in fade-in zoom-in duration-200">
              <div className="p-4 border-b border-[var(--border-subtle)] bg-[var(--bg-tertiary)] flex items-center justify-between">
                 <h3 className="text-sm font-semibold text-[var(--text-primary)] flex items-center space-x-2">
                    <Plus size={16} className="text-emerald-500" />
                    <span>New Collection</span>
                 </h3>
                 <button onClick={() => setShowNewCollectionModal(false)} className="text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition"><X size={18} /></button>
              </div>
              <div className="p-6 space-y-4">
                 <div className="space-y-3">
                    <div className="space-y-1">
                       <label className="text-[10px] uppercase font-bold text-[var(--text-secondary)] tracking-wider">Collection Name</label>
                       <input 
                         type="text"
                         className="w-full bg-[var(--bg-primary)] border border-[var(--border-subtle)] text-[var(--text-primary)] px-3 py-2 text-xs rounded outline-none focus:border-[var(--accent-primary)]"
                         value={newColForm.name}
                         onChange={e => setNewColForm({...newColForm, name: e.target.value})}
                       />
                    </div>
                    <div className="space-y-1">
                       <label className="text-[10px] uppercase font-bold text-[var(--text-secondary)] tracking-wider">Description</label>
                       <textarea 
                         className="w-full bg-[var(--bg-primary)] border border-[var(--border-subtle)] text-[var(--text-primary)] p-2.5 text-xs rounded outline-none focus:border-[var(--accent-primary)] resize-none h-20"
                         value={newColForm.description}
                         onChange={e => setNewColForm({...newColForm, description: e.target.value})}
                       />
                    </div>
                 </div>
                 <button 
                   onClick={handleCreateCollection}
                   className="w-full bg-[var(--accent-gradient)] hover:opacity-90 text-white py-2.5 text-sm font-semibold rounded transition shadow-lg"
                 >
                    Create Collection
                 </button>
              </div>
           </div>
        </div>
      )}
    </div>
  );
};

export default MediaHubPage;