No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

388 líneas
21 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 handleSaveCard = async () => {
  42. if (!isEditing) return;
  43. const generateSafeId = () => 'card-' + Date.now().toString(36) + Math.random().toString(36).substring(2);
  44. const newCard = { ...isEditing, id: isEditing.id || generateSafeId() } as Card;
  45. await fetch('/api/cards', {
  46. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newCard)
  47. });
  48. setCards(prev => {
  49. const exists = prev.find(c => c.id === newCard.id);
  50. return exists ? prev.map(c => c.id === newCard.id ? newCard : c) : [...prev, newCard];
  51. });
  52. setIsEditing(null);
  53. };
  54. const handleDeleteCard = (id: string) => {
  55. // Replace window.confirm with our custom dialog
  56. setConfirmDialog({
  57. message: 'Are you sure you want to delete this card? This action cannot be undone.',
  58. onConfirm: async () => {
  59. await fetch(`/api/cards?id=${id}`, { method: 'DELETE' });
  60. setCards(prev => prev.filter(c => c.id !== id));
  61. setConfirmDialog(null);
  62. showToast('Card successfully deleted.');
  63. }
  64. });
  65. };
  66. const moveCard = async (index: number, direction: 'up' | 'down') => {
  67. const newCards = [...cards];
  68. if (direction === 'up' && index > 0) {
  69. [newCards[index - 1], newCards[index]] = [newCards[index], newCards[index - 1]];
  70. } else if (direction === 'down' && index < newCards.length - 1) {
  71. [newCards[index + 1], newCards[index]] = [newCards[index], newCards[index + 1]];
  72. } else {
  73. return; // Do nothing if trying to move out of bounds
  74. }
  75. // Recalculate displayOrder for the whole array
  76. const updatedCards = newCards.map((c, i) => ({ ...c, displayOrder: i }));
  77. // Optimistically update the UI
  78. setCards(updatedCards);
  79. // Persist the new order to the backend
  80. await fetch('/api/cards', {
  81. method: 'PUT',
  82. headers: { 'Content-Type': 'application/json' },
  83. body: JSON.stringify(updatedCards)
  84. });
  85. };
  86. const handleSavePortal = async () => {
  87. setSavingPortal(true);
  88. await fetch('/api/portals', {
  89. method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(portal)
  90. });
  91. setSavingPortal(false);
  92. showToast('Portal settings saved successfully!'); // Replaced window.alert
  93. };
  94. // Shared Input Classes for high contrast
  95. 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";
  96. return (
  97. <div className="min-h-screen bg-gray-50 font-sans pb-12">
  98. {/* Top Header */}
  99. <div className="bg-blue-900 text-white shadow-md py-6 px-4">
  100. <div className="max-w-5xl mx-auto flex justify-between items-center">
  101. <div>
  102. <h1 className="text-2xl font-bold">Captive Portal CMS</h1>
  103. <p className="text-sm text-blue-200">Local Administration</p>
  104. </div>
  105. <a href="/" target="_blank" className="bg-blue-800 hover:bg-blue-700 text-white px-4 py-2 rounded text-sm transition-colors">
  106. View Live Portal ↗
  107. </a>
  108. </div>
  109. </div>
  110. <div className="max-w-5xl mx-auto mt-8 px-4">
  111. {/* Tab Navigation */}
  112. <div className="flex space-x-2 mb-6">
  113. <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'}`}>
  114. Manage Cards
  115. </button>
  116. <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'}`}>
  117. Portal Settings
  118. </button>
  119. </div>
  120. <div className="bg-white rounded-b-xl rounded-tr-xl shadow-sm border border-gray-200 overflow-hidden min-h-[500px]">
  121. {/* TAB: CARDS */}
  122. {activeTab === 'cards' && (
  123. <div className="p-6 md:p-8">
  124. <div className="flex justify-between items-center mb-8 border-b pb-4">
  125. <h2 className="text-xl font-bold text-gray-800">Card Grid</h2>
  126. <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">
  127. + Add New Card
  128. </button>
  129. </div>
  130. <div className="space-y-3 mb-8">
  131. {cards.length === 0 && <p className="text-gray-500 italic text-center py-8">No cards available. Create one to get started.</p>}
  132. {cards.map((card, idx) => (
  133. // CHANGED: flex-col on mobile, flex-row on sm+, added gap-4 for mobile spacing
  134. <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">
  135. <div className="flex items-center gap-4">
  136. {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>}
  137. <div>
  138. <span className="font-semibold text-gray-800 block">{card.title}</span>
  139. <span className="text-xs text-gray-500 uppercase tracking-wider">{card.cardType}</span>
  140. </div>
  141. </div>
  142. {/* CHANGED: flex-wrap to ensure buttons don't overflow on small screens, w-full on mobile */}
  143. <div className="flex flex-wrap items-center gap-2 w-full sm:w-auto justify-end">
  144. <button onClick={() => moveCard(idx, 'up')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Up">↑</button>
  145. <button onClick={() => moveCard(idx, 'down')} className="p-2 text-gray-500 hover:text-gray-800 hover:bg-gray-200 rounded" title="Move Down">↓</button>
  146. <div className="w-px h-6 bg-gray-300 mx-1 hidden sm:block"></div>
  147. <button onClick={() => setIsEditing(card)} className="px-4 py-2 text-blue-600 hover:bg-blue-50 rounded font-medium">Edit</button>
  148. <button onClick={() => handleDeleteCard(card.id)} className="px-4 py-2 text-red-600 hover:bg-red-50 rounded font-medium">Delete</button>
  149. </div>
  150. </div>
  151. ))}
  152. </div>
  153. </div>
  154. )}
  155. {/* TAB: SETTINGS */}
  156. {activeTab === 'settings' && (
  157. <div className="p-6 md:p-8">
  158. <h2 className="text-xl font-bold text-gray-800 mb-8 border-b pb-4">Global Portal Settings</h2>
  159. <div className="grid grid-cols-1 md:grid-cols-2 gap-10">
  160. <div className="space-y-6">
  161. <div>
  162. <label className="block text-sm font-semibold text-gray-700 mb-1">Portal Title</label>
  163. <input type="text" value={portal.title || ''} onChange={e => setPortal({...portal, title: e.target.value})} className={inputClasses} />
  164. </div>
  165. <div>
  166. <label className="block text-sm font-semibold text-gray-700 mb-1">Welcome Text</label>
  167. <textarea value={portal.welcomeText || ''} onChange={e => setPortal({...portal, welcomeText: e.target.value})} className={`${inputClasses} h-32 resize-none`} />
  168. </div>
  169. <div className="flex gap-8">
  170. <div>
  171. <label className="block text-sm font-semibold text-gray-700 mb-1">Theme Color</label>
  172. <div className="flex items-center gap-4">
  173. <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" />
  174. <span className="text-gray-900 font-mono font-medium">{portal.themeColor || '#1e3a8a'}</span>
  175. </div>
  176. </div>
  177. {/* NEW: Max Columns Setting updated for 3 */}
  178. <div className="flex-1">
  179. <label className="block text-sm font-semibold text-gray-700 mb-1">Grid Max Columns: {portal.maxGridColumns || 5}</label>
  180. <input
  181. type="range"
  182. min="3"
  183. max="8"
  184. value={portal.maxGridColumns || 5}
  185. onChange={e => setPortal({...portal, maxGridColumns: parseInt(e.target.value)})}
  186. className="w-full mt-3 accent-blue-600"
  187. />
  188. <div className="flex justify-between text-xs text-gray-400 mt-1">
  189. <span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span>
  190. </div>
  191. </div>
  192. </div>
  193. </div>
  194. <div className="space-y-6">
  195. {/* Logo Upload with Remove Button */}
  196. <div>
  197. <label className="block text-sm font-semibold text-gray-700 mb-1">Logo Image</label>
  198. <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" />
  199. {uploading['logoUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  200. {portal.logoUrl && (
  201. <div className="mt-2 bg-gray-100 p-4 rounded inline-block relative border">
  202. <img src={portal.logoUrl} className="h-16 object-contain" alt="Logo Preview" />
  203. <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>
  204. </div>
  205. )}
  206. </div>
  207. {/* Hero Upload with Remove Button */}
  208. <div>
  209. <label className="block text-sm font-semibold text-gray-700 mb-1">Hero Background Image</label>
  210. <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" />
  211. {uploading['heroImageUrl'] && <span className="text-xs text-blue-500">Uploading...</span>}
  212. {portal.heroImageUrl && (
  213. <div className="mt-2 relative rounded shadow border inline-block w-full">
  214. <img src={portal.heroImageUrl} className="h-32 w-full object-cover rounded" alt="Hero Preview" />
  215. <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>
  216. </div>
  217. )}
  218. </div>
  219. <div className="bg-gray-50 p-4 rounded-lg border border-gray-200">
  220. <label className="flex items-center gap-3 cursor-pointer">
  221. <input type="checkbox" checked={!!portal.fadeHeroImage} onChange={e => setPortal({...portal, fadeHeroImage: e.target.checked})} className="w-5 h-5 text-blue-600 rounded" />
  222. <div>
  223. <span className="block text-sm font-semibold text-gray-900">Fade Image into Background Color</span>
  224. <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>
  225. </div>
  226. </label>
  227. </div>
  228. </div>
  229. </div>
  230. <div className="mt-10 pt-6 border-t border-gray-200 flex justify-end">
  231. <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">
  232. {savingPortal ? 'Saving...' : 'Save Portal Settings'}
  233. </button>
  234. </div>
  235. </div>
  236. )}
  237. </div>
  238. </div>
  239. {/* MODAL FOR EDITING/CREATING CARDS */}
  240. {isEditing && (
  241. <div
  242. className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4 transition-opacity"
  243. onClick={() => setIsEditing(null)} // Click outside to close
  244. >
  245. <div
  246. 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"
  247. onClick={(e) => e.stopPropagation()} // Prevent inside clicks from closing
  248. >
  249. <button
  250. onClick={() => setIsEditing(null)}
  251. 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"
  252. >
  253. </button>
  254. <h3 className="text-2xl font-bold mb-6 text-gray-900 border-b pb-4">
  255. {isEditing.id ? 'Edit Card' : 'Create New Card'}
  256. </h3>
  257. <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
  258. <div className="space-y-5">
  259. <div>
  260. <label className="block text-sm font-semibold text-gray-800 mb-1">Title</label>
  261. <input type="text" value={isEditing.title || ''} onChange={e => setIsEditing({...isEditing, title: e.target.value})} className={inputClasses} placeholder="e.g., Local History" />
  262. </div>
  263. <div>
  264. <label className="block text-sm font-semibold text-gray-800 mb-1">Card Type</label>
  265. <select value={isEditing.cardType || 'INFO_PAGE'} onChange={e => setIsEditing({...isEditing, cardType: e.target.value as any})} className={inputClasses}>
  266. <option value="INFO_PAGE">Info Page</option>
  267. <option value="IMAGE_GALLERY">Image Gallery</option>
  268. <option value="EXTERNAL_LINK">External Link</option>
  269. </select>
  270. </div>
  271. <div>
  272. <label className="block text-sm font-semibold text-gray-800 mb-1">Short Description</label>
  273. <textarea value={isEditing.shortDescription || ''} onChange={e => setIsEditing({...isEditing, shortDescription: e.target.value})} className={`${inputClasses} h-24 resize-none`} placeholder="Brief summary..." />
  274. </div>
  275. </div>
  276. <div className="space-y-5">
  277. <div>
  278. <label className="block text-sm font-semibold text-gray-800 mb-1">Cover Image</label>
  279. <div className="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center hover:bg-gray-50 transition-colors">
  280. <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" />
  281. {uploading['imageUrl'] && <p className="mt-2 text-sm text-blue-600 font-medium">Uploading image...</p>}
  282. </div>
  283. {isEditing.imageUrl && (
  284. <div className="mt-4 relative rounded-lg overflow-hidden border border-gray-200 group">
  285. <img src={isEditing.imageUrl} className="w-full h-40 object-cover" alt="Preview" />
  286. <button
  287. onClick={() => setIsEditing({...isEditing, imageUrl: ''})}
  288. 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"
  289. title="Remove Image"
  290. >
  291. </button>
  292. </div>
  293. )}
  294. </div>
  295. </div>
  296. </div>
  297. <div className="flex gap-3 pt-8 mt-6 border-t border-gray-200 justify-end">
  298. <button onClick={() => setIsEditing(null)} className="px-5 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors">
  299. Cancel
  300. </button>
  301. <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">
  302. Save Card
  303. </button>
  304. </div>
  305. </div>
  306. </div>
  307. )}
  308. {/* CUSTOM CONFIRM DIALOG */}
  309. {confirmDialog && (
  310. <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">
  311. <div className="bg-white rounded-xl shadow-2xl p-6 max-w-sm w-full animate-in zoom-in-95">
  312. <h3 className="text-xl font-bold text-gray-900 mb-2">Confirm Action</h3>
  313. <p className="text-gray-600 mb-6 leading-relaxed">{confirmDialog.message}</p>
  314. <div className="flex justify-end gap-3">
  315. <button
  316. onClick={() => setConfirmDialog(null)}
  317. className="px-4 py-2.5 text-gray-700 hover:bg-gray-100 rounded-lg font-medium transition-colors"
  318. >
  319. Cancel
  320. </button>
  321. <button
  322. onClick={confirmDialog.onConfirm}
  323. className="px-6 py-2.5 bg-red-600 text-white rounded-lg hover:bg-red-700 font-medium transition-colors shadow-sm"
  324. >
  325. Delete
  326. </button>
  327. </div>
  328. </div>
  329. </div>
  330. )}
  331. {/* CUSTOM TOAST NOTIFICATION */}
  332. {toast && (
  333. <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">
  334. <div className="w-6 h-6 bg-green-500 rounded-full flex items-center justify-center text-gray-900 font-bold text-sm">
  335. </div>
  336. <span className="font-medium">{toast}</span>
  337. </div>
  338. )}
  339. </div>
  340. );
  341. }