You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

455 lines
24 KiB

  1. 'use client';
  2. import { useState, useEffect } from 'react';
  3. import { Card, Portal } from '@/types';
  4. export default function AdminDashboard() {
  5. const [activeTab, setActiveTab] = useState<'cards' | 'settings'>('cards');
  6. // Card State
  7. const [cards, setCards] = useState<Card[]>([]);
  8. const [isEditing, setIsEditing] = useState<Partial<Card> | null>(null);
  9. // Portal State
  10. const [portal, setPortal] = useState<Partial<Portal>>({});
  11. const [savingPortal, setSavingPortal] = useState(false);
  12. const [uploading, setUploading] = useState<{ [key: string]: boolean }>({});
  13. // NEW UI STATES: Toast and Confirm Dialog
  14. const [toast, setToast] = useState<string | null>(null);
  15. const [confirmDialog, setConfirmDialog] = useState<{ message: string, onConfirm: () => void } | null>(null);
  16. // Helper to show auto-dismissing toast
  17. const showToast = (message: string) => {
  18. setToast(message);
  19. setTimeout(() => setToast(null), 3000);
  20. };
  21. useEffect(() => {
  22. fetch('/api/cards').then(res => res.json()).then(setCards);
  23. fetch('/api/portals').then(res => res.json()).then(data => data && setPortal(data));
  24. }, []);
  25. const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>, field: string, isPortal = false) => {
  26. if (!e.target.files?.[0]) return;
  27. setUploading(prev => ({ ...prev, [field]: true }));
  28. const formData = new FormData();
  29. formData.append('file', e.target.files[0]);
  30. const res = await fetch('/api/upload', { method: 'POST', body: formData });
  31. const data = await res.json();
  32. if (data.url) {
  33. if (isPortal) {
  34. setPortal(prev => ({ ...prev, [field]: data.url }));
  35. } else {
  36. setIsEditing(prev => ({ ...prev, [field]: data.url }));
  37. }
  38. }
  39. setUploading(prev => ({ ...prev, [field]: false }));
  40. };
  41. const handleUploadExtraImage = async (e: React.ChangeEvent<HTMLInputElement>) => {
  42. const files = e.target.files;
  43. if (!files || files.length === 0) return;
  44. setUploading(prev => ({ ...prev, extraImages: true }));
  45. const uploaded: string[] = [];
  46. for (const file of Array.from(files)) {
  47. const formData = new FormData();
  48. formData.append('file', file);
  49. const res = await fetch('/api/upload', { method: 'POST', body: formData });
  50. const data = await res.json();
  51. if (data.url) uploaded.push(data.url);
  52. }
  53. setIsEditing(prev => ({
  54. ...prev,
  55. extraImages: [...(prev?.extraImages || []), ...uploaded],
  56. }));
  57. setUploading(prev => ({ ...prev, extraImages: false }));
  58. // Reset input so the same file can be re-selected if needed
  59. e.target.value = '';
  60. };
  61. const removeExtraImage = (index: number) => {
  62. setIsEditing(prev => ({
  63. ...prev,
  64. extraImages: (prev?.extraImages || []).filter((_, i) => i !== index),
  65. }));
  66. };
  67. const handleSaveCard = async () => {
  68. if (!isEditing) return;
  69. const generateSafeId = () => 'card-' + Date.now().toString(36) + Math.random().toString(36).substring(2);
  70. const newCard = { ...isEditing, id: isEditing.id || generateSafeId() } as Card;
  71. await fetch('/api/cards', {
  72. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newCard)
  73. });
  74. setCards(prev => {
  75. const exists = prev.find(c => c.id === newCard.id);
  76. return exists ? prev.map(c => c.id === newCard.id ? newCard : c) : [...prev, newCard];
  77. });
  78. setIsEditing(null);
  79. };
  80. const handleDeleteCard = (id: string) => {
  81. // Replace window.confirm with our custom dialog
  82. setConfirmDialog({
  83. message: 'Are you sure you want to delete this card? This action cannot be undone.',
  84. onConfirm: async () => {
  85. await fetch(`/api/cards?id=${id}`, { method: 'DELETE' });
  86. setCards(prev => prev.filter(c => c.id !== id));
  87. setConfirmDialog(null);
  88. showToast('Card successfully deleted.');
  89. }
  90. });
  91. };
  92. const moveCard = async (index: number, direction: 'up' | 'down') => {
  93. const newCards = [...cards];
  94. if (direction === 'up' && index > 0) {
  95. [newCards[index - 1], newCards[index]] = [newCards[index], newCards[index - 1]];
  96. } else if (direction === 'down' && index < newCards.length - 1) {
  97. [newCards[index + 1], newCards[index]] = [newCards[index], newCards[index + 1]];
  98. } else {
  99. return; // Do nothing if trying to move out of bounds
  100. }
  101. // Recalculate displayOrder for the whole array
  102. const updatedCards = newCards.map((c, i) => ({ ...c, displayOrder: i }));
  103. // Optimistically update the UI
  104. setCards(updatedCards);
  105. // Persist the new order to the backend
  106. await fetch('/api/cards', {
  107. method: 'PUT',
  108. headers: { 'Content-Type': 'application/json' },
  109. body: JSON.stringify(updatedCards)
  110. });
  111. };
  112. const handleSavePortal = async () => {
  113. setSavingPortal(true);
  114. await fetch('/api/portals', {
  115. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(portal)
  116. });
  117. setSavingPortal(false);
  118. showToast('Portal settings saved successfully!'); // Replaced window.alert
  119. };
  120. // Shared Input Classes for high contrast
  121. const inputClasses = "w-full border border-gray-300 p-2.5 rounded-lg outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900 placeholder-gray-400";
  122. return (
  123. <div className="min-h-screen bg-gray-50 font-sans pb-12">
  124. {/* Top Header */}
  125. <div className="bg-blue-900 text-white shadow-md py-6 px-4">
  126. <div className="max-w-5xl mx-auto flex justify-between items-center">
  127. <div>
  128. <h1 className="text-2xl font-bold">Captive Portal CMS</h1>
  129. <p className="text-sm text-blue-200">Local Administration</p>
  130. </div>
  131. <a href="/" target="_blank" className="bg-blue-800 hover:bg-blue-700 text-white px-4 py-2 rounded text-sm transition-colors">
  132. View Live Portal ↗
  133. </a>
  134. </div>
  135. </div>
  136. <div className="max-w-5xl mx-auto mt-8 px-4">
  137. {/* Tab Navigation */}
  138. <div className="flex space-x-2 mb-6">
  139. <button onClick={() => setActiveTab('cards')} className={`px-6 py-3 rounded-t-lg font-bold transition-colors ${activeTab === 'cards' ? 'bg-white text-blue-700 border-t-4 border-blue-600 shadow-sm' : 'bg-gray-200 text-gray-600 hover:bg-gray-300'}`}>
  140. Manage Cards
  141. </button>
  142. <button onClick={() => setActiveTab('settings')} className={`px-6 py-3 rounded-t-lg font-bold transition-colors ${activeTab === 'settings' ? 'bg-white text-blue-700 border-t-4 border-blue-600 shadow-sm' : 'bg-gray-200 text-gray-600 hover:bg-gray-300'}`}>
  143. Portal Settings
  144. </button>
  145. </div>
  146. <div className="bg-white rounded-b-xl rounded-tr-xl shadow-sm border border-gray-200 overflow-hidden min-h-[500px]">
  147. {/* TAB: CARDS */}
  148. {activeTab === 'cards' && (
  149. <div className="p-6 md:p-8">
  150. <div className="flex justify-between items-center mb-8 border-b pb-4">
  151. <h2 className="text-xl font-bold text-gray-800">Card Grid</h2>
  152. <button onClick={() => setIsEditing({ title: '', cardType: 'INFO_PAGE', displayOrder: cards.length })} className="bg-blue-600 text-white px-5 py-2.5 rounded-lg shadow-sm hover:bg-blue-700 font-medium">
  153. + Add New Card
  154. </button>
  155. </div>
  156. <div className="space-y-3 mb-8">
  157. {cards.length === 0 && <p className="text-gray-500 italic text-center py-8">No cards available. Create one to get started.</p>}
  158. {cards.map((card, idx) => (
  159. // CHANGED: flex-col on mobile, flex-row on sm+, added gap-4 for mobile spacing
  160. <div key={card.id} className="flex flex-col sm:flex-row sm:items-center justify-between p-4 border rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors gap-4">
  161. <div className="flex items-center gap-4">
  162. {card.imageUrl ? <img src={card.imageUrl} className="w-16 h-16 object-cover rounded-md shadow-sm shrink-0" alt="" /> : <div className="w-16 h-16 bg-gray-200 rounded-md shadow-sm flex items-center justify-center text-gray-400 text-xs shrink-0">No Image</div>}
  163. <div>
  164. <span className="font-semibold text-gray-800 block">{card.title}</span>
  165. <span className="text-xs text-gray-500 uppercase tracking-wider">{card.cardType}</span>
  166. </div>
  167. </div>
  168. {/* CHANGED: flex-wrap to ensure buttons don't overflow on small screens, w-full on mobile */}
  169. <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto justify-end">
  170. <button onClick={() => moveCard(idx, 'up')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Up">↑</button>
  171. <button onClick={() => moveCard(idx, 'down')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Down">↓</button>
  172. <div className="w-px h-6 bg-gray-300 mx-1 hidden sm:block"></div>
  173. <button onClick={() => setIsEditing(card)} className="px-4 py-2 text-blue-600 hover:bg-blue-50 rounded font-medium">Edit</button>
  174. <button onClick={() => handleDeleteCard(card.id)} className="px-4 py-2 text-red-600 hover:bg-red-50 rounded font-medium">Delete</button>
  175. </div>
  176. </div>
  177. ))}
  178. </div>
  179. </div>
  180. )}
  181. {/* TAB: SETTINGS */}
  182. {activeTab === 'settings' && (
  183. <div className="p-6 md:p-8">
  184. <h2 className="text-xl font-bold text-gray-800 mb-8 border-b pb-4">Global Portal Settings</h2>
  185. <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
  186. <div className="space-y-6">
  187. <div>
  188. <label className="block text-sm font-semibold text-gray-700 mb-1">Portal Title</label>
  189. <input type="text" value={portal.title || ''} onChange={e => setPortal({...portal, title: e.target.value})} className={inputClasses} />
  190. </div>
  191. <div>
  192. <label className="block text-sm font-semibold text-gray-700 mb-1">Welcome Text</label>
  193. <textarea value={portal.welcomeText || ''} onChange={e => setPortal({...portal, welcomeText: e.target.value})} className={`${inputClasses} h-32 resize-none`} />
  194. </div>
  195. <div className="flex gap-8">
  196. <div>
  197. <label className="block text-sm font-semibold text-gray-700 mb-1">Theme Color</label>
  198. <div className="flex items-center gap-4">
  199. <input type="color" value={portal.themeColor || '#1e3a8a'} onChange={e => setPortal({...portal, themeColor: e.target.value})} className="h-12 w-12 rounded cursor-pointer border-0 p-0" />
  200. <span className="text-gray-900 font-mono font-medium">{portal.themeColor || '#1e3a8a'}</span>
  201. </div>
  202. </div>
  203. {/* NEW: Max Columns Setting updated for 3 */}
  204. <div className="flex-1">
  205. <label className="block text-sm font-semibold text-gray-700 mb-1">Grid Max Columns: {portal.maxGridColumns || 5}</label>
  206. <input
  207. type="range"
  208. min="3"
  209. max="8"
  210. value={portal.maxGridColumns || 5}
  211. onChange={e => setPortal({...portal, maxGridColumns: parseInt(e.target.value)})}
  212. className="w-full mt-3 accent-blue-600"
  213. />
  214. <div className="flex justify-between text-xs text-gray-400 mt-1">
  215. <span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span>
  216. </div>
  217. </div>
  218. </div>
  219. </div>
  220. <div className="space-y-6">
  221. {/* Logo Upload with Remove Button */}
  222. <div>
  223. <label className="block text-sm font-semibold text-gray-700 mb-1">Logo Image</label>
  224. <input type="file" accept="image/*" onChange={e => handleUpload(e, 'logoUrl', true)} className="block w-full text-sm text-gray-900 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:bg-gray-100 cursor-pointer" />
  225. {uploading['logoUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  226. {portal.logoUrl && (
  227. <div className="mt-2 bg-gray-100 p-4 rounded inline-block relative border">
  228. <img src={portal.logoUrl} className="h-16 object-contain" alt="Logo Preview" />
  229. <button onClick={() => setPortal({...portal, logoUrl: ''})} className="absolute -top-2 -right-2 bg-red-500 text-white w-6 h-6 rounded-full text-xs font-bold hover:bg-red-600 shadow">✕</button>
  230. </div>
  231. )}
  232. </div>
  233. {/* Hero Upload with Remove Button */}
  234. <div>
  235. <label className="block text-sm font-semibold text-gray-700 mb-1">Hero Background Image</label>
  236. <input type="file" accept="image/*" onChange={e => handleUpload(e, 'heroImageUrl', true)} className="block w-full text-sm text-gray-900 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:bg-gray-100 cursor-pointer" />
  237. {uploading['heroImageUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  238. {portal.heroImageUrl && (
  239. <div className="mt-2 relative rounded shadow border inline-block w-full">
  240. <img src={portal.heroImageUrl} className="h-32 w-full object-cover rounded" alt="Hero Preview" />
  241. <button onClick={() => setPortal({...portal, heroImageUrl: ''})} className="absolute top-2 right-2 bg-red-500 text-white w-8 h-8 flex items-center justify-center rounded-full text-sm font-bold hover:bg-red-600 shadow-lg">✕</button>
  242. </div>
  243. )}
  244. </div>
  245. <div className="bg-gray-50 p-4 rounded-lg border border-gray-200">
  246. <label className="flex items-center gap-3 cursor-pointer">
  247. <input type="checkbox" checked={!!portal.fadeHeroImage} onChange={e => setPortal({...portal, fadeHeroImage: e.target.checked})} className="w-5 h-5 text-blue-600 rounded" />
  248. <div>
  249. <span className="block text-sm font-semibold text-gray-900">Fade Image into Background Color</span>
  250. <span className="block text-xs text-gray-600">Creates a smooth gradient from the top of the image into the solid theme color at the bottom.</span>
  251. </div>
  252. </label>
  253. </div>
  254. </div>
  255. </div>
  256. <div className="mt-10 pt-6 border-t border-gray-200 flex justify-end">
  257. <button onClick={handleSavePortal} disabled={savingPortal} className="bg-blue-600 text-white px-10 py-3 rounded-lg hover:bg-blue-700 font-bold shadow disabled:opacity-50 transition-colors">
  258. {savingPortal ? 'Saving...' : 'Save Portal Settings'}
  259. </button>
  260. </div>
  261. </div>
  262. )}
  263. </div>
  264. </div>
  265. {/* MODAL FOR EDITING/CREATING CARDS */}
  266. {isEditing && (
  267. <div
  268. className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4 transition-opacity"
  269. onClick={() => setIsEditing(null)} // Click outside to close
  270. >
  271. <div
  272. className="bg-white rounded-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto shadow-2xl p-6 md:p-8 relative animate-in fade-in zoom-in-95 duration-200"
  273. onClick={(e) => e.stopPropagation()} // Prevent inside clicks from closing
  274. >
  275. <button
  276. onClick={() => setIsEditing(null)}
  277. className="absolute top-6 right-6 text-gray-400 hover:text-gray-900 bg-gray-100 hover:bg-gray-200 rounded-full w-8 h-8 flex items-center justify-center transition-colors"
  278. >
  279. </button>
  280. <h3 className="text-2xl font-bold mb-6 text-gray-900 border-b pb-4">
  281. {isEditing.id ? 'Edit Card' : 'Create New Card'}
  282. </h3>
  283. <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
  284. <div className="space-y-5">
  285. <div>
  286. <label className="block text-sm font-semibold text-gray-800 mb-1">Title</label>
  287. <input type="text" value={isEditing.title || ''} onChange={e => setIsEditing({...isEditing, title: e.target.value})} className={inputClasses} placeholder="e.g., Local History" />
  288. </div>
  289. <div>
  290. <label className="block text-sm font-semibold text-gray-800 mb-1">Card Type</label>
  291. <select value={isEditing.cardType || 'INFO_PAGE'} onChange={e => setIsEditing({...isEditing, cardType: e.target.value as any})} className={inputClasses}>
  292. <option value="INFO_PAGE">Info Page</option>
  293. <option value="IMAGE_GALLERY">Image Gallery</option>
  294. <option value="EXTERNAL_LINK">External Link</option>
  295. </select>
  296. </div>
  297. <div>
  298. <label className="block text-sm font-semibold text-gray-800 mb-1">Short Description</label>
  299. <textarea value={isEditing.shortDescription || ''} onChange={e => setIsEditing({...isEditing, shortDescription: e.target.value})} className={`${inputClasses} h-24 resize-none`} placeholder="Brief summary..." />
  300. </div>
  301. </div>
  302. <div className="space-y-5">
  303. {/* Cover Image */}
  304. <div>
  305. <label className="block text-sm font-semibold text-gray-800 mb-1">
  306. Cover Image <span className="text-gray-400 font-normal text-xs">(shown in grid)</span>
  307. </label>
  308. <div className="border-2 border-dashed border-gray-300 rounded-lg p-3 hover:bg-gray-50 transition-colors">
  309. <input type="file" accept="image/*" onChange={e => handleUpload(e, 'imageUrl')} className="block w-full text-sm text-gray-700 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 cursor-pointer" />
  310. {uploading['imageUrl'] && <p className="mt-2 text-sm text-blue-600 font-medium">Uploading...</p>}
  311. </div>
  312. {isEditing.imageUrl && (
  313. <div className="mt-3 relative rounded-lg overflow-hidden border border-gray-200 group">
  314. <img src={isEditing.imageUrl} className="w-full h-32 object-cover" alt="Cover preview" />
  315. <button
  316. onClick={() => setIsEditing({...isEditing, imageUrl: ''})}
  317. className="absolute top-2 right-2 bg-red-500 text-white w-8 h-8 rounded-full text-sm font-bold shadow opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-600"
  318. title="Remove cover image"
  319. >✕</button>
  320. </div>
  321. )}
  322. </div>
  323. {/* Gallery Images */}
  324. <div>
  325. <label className="block text-sm font-semibold text-gray-800 mb-1">
  326. Gallery Images <span className="text-gray-400 font-normal text-xs">(optional, shown in detail modal)</span>
  327. </label>
  328. <div className="border-2 border-dashed border-gray-300 rounded-lg p-3 hover:bg-gray-50 transition-colors">
  329. <input
  330. type="file"
  331. accept="image/*"
  332. multiple
  333. onChange={handleUploadExtraImage}
  334. className="block w-full text-sm text-gray-700 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-purple-50 file:text-purple-700 hover:file:bg-purple-100 cursor-pointer"
  335. />
  336. {uploading['extraImages'] && <p className="mt-2 text-sm text-purple-600 font-medium">Uploading...</p>}
  337. </div>
  338. {/* Thumbnails strip */}
  339. {(isEditing.extraImages || []).length > 0 && (
  340. <div className="mt-3 flex flex-wrap gap-2">
  341. {(isEditing.extraImages || []).map((url, i) => (
  342. <div key={url + i} className="relative group w-20 h-20 rounded-lg overflow-hidden border border-gray-200 shrink-0">
  343. <img src={url} className="w-full h-full object-cover" alt={`Gallery ${i + 1}`} />
  344. <div className="absolute inset-0 bg-black/30 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
  345. <button
  346. onClick={() => removeExtraImage(i)}
  347. className="bg-red-500 text-white w-7 h-7 rounded-full text-xs font-bold hover:bg-red-600"
  348. title="Remove"
  349. >✕</button>
  350. </div>
  351. <span className="absolute bottom-0 left-0 right-0 text-center text-white text-[10px] bg-black/50 pb-0.5">{i + 1}</span>
  352. </div>
  353. ))}
  354. </div>
  355. )}
  356. </div>
  357. </div>
  358. </div>
  359. <div className="flex gap-3 pt-8 mt-6 border-t border-gray-200 justify-end">
  360. <button onClick={() => setIsEditing(null)} className="px-5 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors">
  361. Cancel
  362. </button>
  363. <button onClick={handleSaveCard} className="bg-green-600 text-white px-8 py-2.5 rounded-lg hover:bg-green-700 font-medium shadow-sm transition-colors">
  364. Save Card
  365. </button>
  366. </div>
  367. </div>
  368. </div>
  369. )}
  370. {/* CUSTOM CONFIRM DIALOG */}
  371. {confirmDialog && (
  372. <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in duration-200">
  373. <div className="bg-white rounded-xl shadow-2xl p-6 max-w-sm w-full animate-in zoom-in-95">
  374. <h3 className="text-xl font-bold text-gray-900 mb-2">Confirm Action</h3>
  375. <p className="text-gray-600 mb-6 leading-relaxed">{confirmDialog.message}</p>
  376. <div className="flex justify-end gap-3">
  377. <button
  378. onClick={() => setConfirmDialog(null)}
  379. className="px-4 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors"
  380. >
  381. Cancel
  382. </button>
  383. <button
  384. onClick={confirmDialog.onConfirm}
  385. className="px-6 py-2.5 bg-red-600 text-white rounded-lg hover:bg-red-700 font-medium transition-colors shadow-sm"
  386. >
  387. Delete
  388. </button>
  389. </div>
  390. </div>
  391. </div>
  392. )}
  393. {/* CUSTOM TOAST NOTIFICATION */}
  394. {toast && (
  395. <div className="fixed bottom-6 right-6 z-[70] bg-gray-900 text-white px-6 py-4 rounded-lg shadow-2xl flex items-center gap-3 animate-in slide-in-from-bottom-5 fade-in duration-300">
  396. <div className="w-6 h-6 bg-green-500 rounded-full flex items-center justify-center text-gray-900 font-bold text-sm">
  397. </div>
  398. <span className="font-medium">{toast}</span>
  399. </div>
  400. )}
  401. </div>
  402. );
  403. }