Files
ims/components/admin/site-zone-manager.tsx
T

264 lines
12 KiB
TypeScript

'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Modal } from '@/components/ui/modal'
export type SiteWithZones = {
id: string
name: string
address: string | null
active: boolean
zones: Array<{ id: string; name: string; qr_code_token: string; active: boolean }>
}
interface Props {
sites: SiteWithZones[]
}
const inp = 'w-full border border-gray-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-500'
const lbl = 'block text-xs font-medium text-gray-600 mb-1'
type DeleteTarget = { kind: 'site'; id: string; name: string } | { kind: 'zone'; id: string; name: string }
export function SiteZoneManager({ sites }: Props) {
const router = useRouter()
const [siteName, setSiteName] = useState('')
const [zoneName, setZoneName] = useState('')
const [zoneSiteId, setZoneSiteId] = useState('')
const [busy, setBusy] = useState(false)
const [busyId, setBusyId] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const [showAddSite, setShowAddSite] = useState(false)
const [showAddZone, setShowAddZone] = useState(false)
const [confirmDelete, setConfirmDelete] = useState<DeleteTarget | null>(null)
const post = async (payload: Record<string, unknown>) => {
setBusy(true)
setError(null)
const res = await fetch('/api/admin/sites', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
setBusy(false)
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(data.error ?? 'Save failed')
return false
}
router.refresh()
return true
}
const send = async (method: 'PATCH' | 'DELETE', payload: Record<string, unknown>) => {
const id = payload.id as string
setBusyId(id)
setError(null)
const res = await fetch('/api/admin/sites', {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
setBusyId(null)
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(data.error ?? 'Action failed')
return false
}
router.refresh()
return true
}
const handleDelete = async (target: DeleteTarget) => {
await send('DELETE', target.kind === 'site'
? { kind: 'site', id: target.id }
: { kind: 'zone', id: target.id }
)
setConfirmDelete(null)
}
const totalZones = sites.reduce((n, s) => n + s.zones.length, 0)
return (
<div className="bg-surface border border-divider shadow-sm overflow-hidden">
<div className="flex items-center justify-between px-5 py-4 border-b border-divider">
<div>
<h2 className="text-sm font-semibold text-gray-900">Sites & Zones</h2>
<p className="text-xs text-gray-400 mt-0.5">{sites.length} site{sites.length !== 1 ? 's' : ''} · {totalZones} zone{totalZones !== 1 ? 's' : ''}</p>
</div>
<div className="flex gap-2">
<button onClick={() => { setShowAddZone(true); setError(null) }}
className="flex items-center gap-1.5 px-3 py-1.5 bg-gray-100 text-gray-700 text-xs font-semibold hover:bg-gray-200 transition-colors cursor-pointer">
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
</svg>
Add Zone
</button>
<button onClick={() => { setShowAddSite(true); setError(null) }}
className="flex items-center gap-1.5 px-3 py-1.5 bg-green-600 text-white text-xs font-semibold hover:bg-green-700 transition-colors cursor-pointer">
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
</svg>
Add Site
</button>
</div>
</div>
{error && <div className="px-5 py-2 bg-red-50 border-b border-red-100 text-xs text-red-600">{error}</div>}
<div className="divide-y divide-gray-50">
{sites.map(site => (
<div key={site.id} className={`px-5 py-4 ${!site.active ? 'opacity-50' : ''}`}>
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-semibold text-gray-900">{site.name}</p>
{site.address && <p className="text-xs text-gray-400 mt-0.5">{site.address}</p>}
</div>
<div className="flex items-center gap-2">
<button disabled={busyId === site.id}
onClick={() => send('PATCH', { kind: 'site', id: site.id, active: !site.active })}
className={`text-xs font-medium px-2.5 py-1 rounded-full border transition-colors cursor-pointer disabled:opacity-50 ${
site.active
? 'bg-green-50 text-green-700 border-green-200 hover:bg-green-100'
: 'bg-gray-50 text-gray-500 border-divider hover:bg-gray-100'
}`}>
{site.active ? 'Active' : 'Inactive'}
</button>
<button disabled={busyId === site.id}
onClick={() => setConfirmDelete({ kind: 'site', id: site.id, name: site.name })}
className="text-xs text-red-500 hover:text-red-700 hover:underline cursor-pointer transition-colors disabled:opacity-50">
Delete
</button>
</div>
</div>
{site.zones.length > 0 && (
<ul className="mt-3 space-y-1.5 pl-3 border-l-2 border-divider">
{site.zones.map(z => (
<li key={z.id} className={`flex items-center justify-between ${!z.active ? 'opacity-50' : ''}`}>
<span className="text-xs text-gray-700 font-medium">{z.name}</span>
<div className="flex items-center gap-3">
<a href={`/report?zone=${z.qr_code_token}`} target="_blank"
className="text-xs text-blue-600 hover:underline cursor-pointer">
Report link
</a>
<button disabled={busyId === z.id}
onClick={() => send('PATCH', { kind: 'zone', id: z.id, active: !z.active })}
className={`text-xs font-medium px-2 py-0.5 rounded-full border transition-colors cursor-pointer disabled:opacity-50 ${
z.active
? 'bg-green-50 text-green-700 border-green-200 hover:bg-green-100'
: 'bg-gray-50 text-gray-500 border-divider hover:bg-gray-100'
}`}>
{z.active ? 'Active' : 'Inactive'}
</button>
<button disabled={busyId === z.id}
onClick={() => setConfirmDelete({ kind: 'zone', id: z.id, name: z.name })}
className="text-xs text-red-500 hover:text-red-700 hover:underline cursor-pointer transition-colors disabled:opacity-50">
Delete
</button>
</div>
</li>
))}
</ul>
)}
{site.zones.length === 0 && (
<p className="text-xs text-gray-400 mt-2 pl-3">No zones</p>
)}
</div>
))}
{sites.length === 0 && (
<div className="px-5 py-10 text-center text-sm text-gray-400">No sites yet</div>
)}
</div>
{/* Add Site Modal */}
<Modal open={showAddSite} onClose={() => { setShowAddSite(false); setSiteName(''); setError(null) }}
title="Add Site" width="sm"
footer={
<>
<button onClick={() => { setShowAddSite(false); setSiteName(''); setError(null) }}
className="px-4 py-2 text-sm font-medium border border-divider text-gray-700 hover:bg-gray-50 cursor-pointer transition-colors">
Cancel
</button>
<button disabled={busy || !siteName.trim()}
onClick={async () => { if (await post({ kind: 'site', name: siteName })) { setSiteName(''); setShowAddSite(false) } }}
className="px-4 py-2 bg-green-600 text-white text-sm font-semibold hover:bg-green-700 disabled:opacity-50 cursor-pointer transition-colors">
{busy ? 'Adding…' : 'Add Site'}
</button>
</>
}
>
{error && <p className="text-xs text-red-600 bg-red-50 px-3 py-2 mb-3">{error}</p>}
<div>
<label className={lbl} htmlFor="add-site-name">Site Name *</label>
<input id="add-site-name" type="text" placeholder="e.g. Setia Warehouse KL"
value={siteName} onChange={e => setSiteName(e.target.value)}
onKeyDown={e => e.key === 'Enter' && !busy && siteName.trim() && post({ kind: 'site', name: siteName }).then(ok => ok && (setSiteName(''), setShowAddSite(false)))}
className={inp} autoFocus />
</div>
</Modal>
{/* Add Zone Modal */}
<Modal open={showAddZone} onClose={() => { setShowAddZone(false); setZoneName(''); setZoneSiteId(''); setError(null) }}
title="Add Zone" width="sm"
footer={
<>
<button onClick={() => { setShowAddZone(false); setZoneName(''); setZoneSiteId(''); setError(null) }}
className="px-4 py-2 text-sm font-medium border border-divider text-gray-700 hover:bg-gray-50 cursor-pointer transition-colors">
Cancel
</button>
<button disabled={busy || !zoneName.trim() || !zoneSiteId}
onClick={async () => {
if (await post({ kind: 'zone', name: zoneName, site_id: zoneSiteId })) {
setZoneName(''); setZoneSiteId(''); setShowAddZone(false)
}
}}
className="px-4 py-2 bg-green-600 text-white text-sm font-semibold hover:bg-green-700 disabled:opacity-50 cursor-pointer transition-colors">
{busy ? 'Adding…' : 'Add Zone'}
</button>
</>
}
>
{error && <p className="text-xs text-red-600 bg-red-50 px-3 py-2 mb-3">{error}</p>}
<div className="space-y-4">
<div>
<label className={lbl} htmlFor="add-zone-site">Site *</label>
<select id="add-zone-site" value={zoneSiteId} onChange={e => setZoneSiteId(e.target.value)} className={inp}>
<option value="">Select site…</option>
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
</div>
<div>
<label className={lbl} htmlFor="add-zone-name">Zone Name *</label>
<input id="add-zone-name" type="text" placeholder="e.g. Loading Bay A"
value={zoneName} onChange={e => setZoneName(e.target.value)}
className={inp} />
</div>
</div>
</Modal>
{/* Delete Confirm Modal */}
<Modal open={!!confirmDelete} onClose={() => setConfirmDelete(null)} title={`Delete ${confirmDelete?.kind === 'site' ? 'Site' : 'Zone'}`} width="sm"
footer={
<>
<button onClick={() => setConfirmDelete(null)}
className="px-4 py-2 text-sm font-medium border border-divider text-gray-700 hover:bg-gray-50 cursor-pointer transition-colors">
Cancel
</button>
<button disabled={!!(confirmDelete && busyId === confirmDelete.id)}
onClick={() => confirmDelete && handleDelete(confirmDelete)}
className="px-4 py-2 bg-red-600 text-white text-sm font-semibold hover:bg-red-700 disabled:opacity-50 cursor-pointer transition-colors">
Delete
</button>
</>
}
>
<p className="text-sm text-gray-700">
Delete <span className="font-semibold">{confirmDelete?.name}</span>? This cannot be undone.
</p>
</Modal>
</div>
)
}