"use client"; /* eslint-disable react-hooks/set-state-in-effect */ import React, { useState, useTransition, useEffect, useMemo } from "react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { publishStop, deleteStop } from "@/actions/stops"; import { AdminSearchInput, AdminFilterTabs, AdminButton, AdminIconButton, useToast, Skeleton, } from "@/components/admin/design-system"; import ScheduleImportModal from "@/components/admin/ScheduleImportModal"; import AddStopModal from "@/components/admin/AddStopModal"; import StopDetailModal from "@/components/admin/StopDetailModal"; type Stop = { id: string; city: string; state: string; date: string; time: string; location: string; active: boolean; deleted_at?: string | null; brand_id: string; status?: string; address?: string | null; brands: { name: string } | { name: string }[] | null; }; type Props = { stops: Stop[]; /** * Hide the internal search/filter bar at the top of the table. Use when * the parent component already renders shared filters (e.g. StopsViewClient). */ hideInternalFilterBar?: boolean; }; const TAB_NUMERIC: Record<"all" | "active" | "inactive" | "draft", "all" | "active" | "inactive" | "draft"> = { all: "all", active: "active", inactive: "inactive", draft: "draft", }; export default function StopTableClient({ stops, hideInternalFilterBar = false }: Props) { const router = useRouter(); const { success: showSuccess, error: showError } = useToast(); const [, startTransition] = useTransition(); const [search, setSearch] = useState(""); const [statusFilter, setStatusFilter] = useState<"all" | "active" | "inactive" | "draft">("all"); const [deleteError, setDeleteError] = useState(null); const [page, setPage] = useState(0); const [isLoading, setIsLoading] = useState(false); const [selectedStops, setSelectedStops] = useState>(new Set()); const [bulkPublishing, setBulkPublishing] = useState(false); const [showImport, setShowImport] = useState(false); const [showAdd, setShowAdd] = useState(false); const [openStopId, setOpenStopId] = useState(null); const PAGE_SIZE = 50; useEffect(() => { setIsLoading(true); const timer = setTimeout(() => setIsLoading(false), 220); return () => clearTimeout(timer); }, [page, statusFilter, search]); const filtered = useMemo(() => { const q = search.trim().toLowerCase(); return stops.filter((s) => { const matchesSearch = !q || s.city.toLowerCase().includes(q) || s.location.toLowerCase().includes(q); const matchesStatus = statusFilter === "all" || (statusFilter === "active" && s.active && s.status !== "draft") || (statusFilter === "inactive" && !s.active && s.status !== "draft") || (statusFilter === "draft" && s.status === "draft"); return matchesSearch && matchesStatus; }); }, [stops, search, statusFilter]); const statusCounts = useMemo( () => ({ all: stops.length, active: stops.filter((s) => s.active && s.status !== "draft").length, inactive: stops.filter((s) => !s.active && s.status !== "draft").length, draft: stops.filter((s) => s.status === "draft").length, }), [stops] ); const tabs = useMemo( () => [ { value: "all", label: "All", count: statusCounts.all }, { value: "active", label: "Active", count: statusCounts.active }, { value: "inactive", label: "Inactive", count: statusCounts.inactive }, { value: "draft", label: "Draft", count: statusCounts.draft }, ], [statusCounts] ); const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE)); const paginatedStops = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE); const toggleSelectAll = () => { if (selectedStops.size === paginatedStops.length) { setSelectedStops(new Set()); } else { setSelectedStops(new Set(paginatedStops.map((s) => s.id))); } }; const toggleStopSelection = (stopId: string) => { setSelectedStops((prev) => { const next = new Set(prev); if (next.has(stopId)) { next.delete(stopId); } else { next.add(stopId); } return next; }); }; async function handleBulkPublish() { if (selectedStops.size === 0) return; setBulkPublishing(true); let successCount = 0; let failCount = 0; for (const stopId of selectedStops) { const stop = stops.find((s) => s.id === stopId); if (stop && stop.status === "draft") { const result = await publishStop(stopId, stop.brand_id); if (result.success) { successCount++; } else { failCount++; } } } setBulkPublishing(false); setSelectedStops(new Set()); if (failCount === 0) { showSuccess(`${successCount} stop${successCount !== 1 ? "s" : ""} published`); } else { showError("Some stops failed", `${successCount} succeeded, ${failCount} failed`); } startTransition(() => router.refresh()); } function handleDeleted() { setDeleteError(null); startTransition(() => router.refresh()); } function refresh() { startTransition(() => router.refresh()); } return ( <> {/* Filter bar */} {!hideInternalFilterBar && (
{ setSearch(e.target.value); setPage(0); }} onClear={() => { setSearch(""); setPage(0); }} showClear className="flex-1 min-w-[180px] max-w-[280px]" /> { setStatusFilter(TAB_NUMERIC[value as keyof typeof TAB_NUMERIC] ?? "all"); setPage(0); }} tabs={tabs} size="sm" showCounts /> {filtered.length} stop{filtered.length !== 1 ? "s" : ""} {totalPages > 1 && (
setPage((p) => Math.max(0, p - 1))} disabled={page === 0 || isLoading} className="!rounded-lg border border-[var(--admin-border)]" > {page + 1}/{totalPages} setPage((p) => Math.min(totalPages - 1, p + 1))} disabled={page >= totalPages - 1 || isLoading} className="!rounded-lg border border-[var(--admin-border)]" >
)} setShowImport(true)} icon={ } > Upload Schedule setShowAdd(true)} icon={ } > Add Stop
)} {/* Bulk actions bar */} {selectedStops.size > 0 && (
{selectedStops.size} stop{selectedStops.size !== 1 ? "s" : ""} selected
Publish Selected
)} {/* Delete error */} {deleteError && (
{deleteError}{" "}
)} {/* Table */} {isLoading ? ( Array.from({ length: 8 }).map((_, i) => ( )) ) : filtered.length === 0 ? ( ) : ( paginatedStops.map((stop) => ( { e.stopPropagation(); toggleStopSelection(stop.id); }} onOpen={() => setOpenStopId(stop.id)} /> )) )}
0} onChange={toggleSelectAll} className="h-4 w-4 rounded border-stone-300 text-emerald-600 focus:ring-emerald-500 cursor-pointer" aria-label="Select all" /> When Where Venue Status

{search || statusFilter !== "all" ? "No stops match your filters" : "No stops yet"}

{search || statusFilter !== "all" ? "Try a different search or clear the filters above." : "Use the buttons above to upload a schedule or add your first stop."}

{showImport && ( setShowImport(false)} onComplete={refresh} /> )} setShowAdd(false)} brandId={stops[0]?.brand_id ?? ""} onSuccess={refresh} /> {openStopId && ( setOpenStopId(null)} /> )} ); } function formatDate(iso: string): { date: string; weekday: string } { // Stop date is stored as YYYY-MM-DD; parse without TZ shift const [y, m, d] = iso.split("-").map((s) => parseInt(s, 10)); if (!y || !m || !d) return { date: iso, weekday: "" }; const dt = new Date(y, m - 1, d); const weekday = dt.toLocaleDateString("en-US", { weekday: "short" }); const month = dt.toLocaleDateString("en-US", { month: "short" }); return { date: `${month} ${d}`, weekday }; } function formatTime(t: string): string { // Stored as HH:MM (24h). Display as 10:00 AM. if (!t) return ""; const [hStr, mStr] = t.split(":"); const h = parseInt(hStr, 10); if (Number.isNaN(h)) return t; const period = h >= 12 ? "PM" : "AM"; const hh = h === 0 ? 12 : h > 12 ? h - 12 : h; return `${hh}:${mStr} ${period}`; } function StopRowBase({ stop, onDeleted, onDeleteError, isSelected, onToggleSelect, onOpen, }: { stop: Stop; onDeleted: () => void; onDeleteError: (msg: string) => void; isSelected: boolean; onToggleSelect: (e: React.MouseEvent) => void; onOpen: () => void; }) { const { success: showSuccess, error: showError } = useToast(); const [openMenu, setOpenMenu] = useState(null); const [deletingId, setDeletingId] = useState(null); const [confirmDelete, setConfirmDelete] = useState(null); const [publishingId, setPublishingId] = useState(null); const { date, weekday } = formatDate(stop.date); const time = formatTime(stop.time); async function handlePublish() { setPublishingId(stop.id); const result = await publishStop(stop.id, stop.brand_id); setPublishingId(null); if (result.success) { showSuccess("Stop published", "The stop is now visible on the storefront"); onDeleted(); } else { showError("Failed to publish", result.error ?? "Please try again"); } } async function handleDelete() { setDeletingId(stop.id); const result = await deleteStop(stop.id, stop.brand_id); setDeletingId(null); setConfirmDelete(null); setOpenMenu(null); if (result.success) { showSuccess("Stop deleted", "The stop has been removed"); onDeleted(); } else { onDeleteError(result.error ?? "Delete failed"); } } return ( e.stopPropagation()}> {}} onClick={onToggleSelect} className="h-4 w-4 rounded border-stone-300 text-emerald-600 focus:ring-emerald-500 cursor-pointer" aria-label={`Select stop in ${stop.city}`} />
{date} {weekday} {time && `· ${time}`}
{stop.city} {stop.state}
{stop.location} {stop.address && ( {stop.address} )}
{stop.status === "draft" ? "Draft" : stop.active ? "Active" : "Inactive"} e.stopPropagation()}>
{ e.preventDefault(); e.stopPropagation(); setOpenMenu(openMenu === stop.id ? null : stop.id); }} className="opacity-60 group-hover:opacity-100" > {openMenu === stop.id && ( <>
{ e.stopPropagation(); setOpenMenu(null); setConfirmDelete(null); }} />
{stop.status === "draft" && ( )} e.stopPropagation()} className="flex items-center px-4 py-2.5 text-sm text-[var(--admin-text-secondary)] hover:bg-[var(--admin-bg-subtle)] transition-colors" > Duplicate
)} {confirmDelete === stop.id && ( <>
{ e.stopPropagation(); setConfirmDelete(null); setOpenMenu(null); }} />

Delete "{stop.city}, {stop.state}"?

This will remove the stop. If it has active orders, you must resolve those first.

{ e.stopPropagation(); setConfirmDelete(null); setOpenMenu(null); }} > Cancel { e.stopPropagation(); handleDelete(); }} disabled={deletingId === stop.id} isLoading={deletingId === stop.id} > {deletingId === stop.id ? "Deleting…" : "Delete"}
)}
); } const StopRow = React.memo(StopRowBase);