1410 lines
58 KiB
TypeScript
1410 lines
58 KiB
TypeScript
'use client';
|
|
|
|
import { useState, useEffect, useMemo, useRef, type ReactNode } from 'react';
|
|
import {
|
|
Tag,
|
|
Plus,
|
|
Search,
|
|
RefreshCw,
|
|
ChevronDown,
|
|
ChevronRight,
|
|
Trash2,
|
|
Filter,
|
|
X,
|
|
Box,
|
|
FileSpreadsheet,
|
|
FileText,
|
|
Columns3,
|
|
GripVertical,
|
|
ArrowUpDown,
|
|
Calendar,
|
|
AlertTriangle,
|
|
} from 'lucide-react';
|
|
import { toast } from 'sonner';
|
|
import { format, subDays } from 'date-fns';
|
|
import { AnimatePresence, motion } from '@/lib/motion';
|
|
import { catalogService, BrandResponse } from '@/services/api/catalogService';
|
|
import { getMediaUrl } from '@/services/api/config';
|
|
|
|
import ImageUpload from '@/components/ui/ImageUpload';
|
|
import { SlideOver } from '@/components/ui/SlideOver';
|
|
import { RowActionsMenu } from '@/components/ui/RowActionsMenu';
|
|
import { ViewModeToggle } from '@/components/ui/ViewModeToggle';
|
|
import { TablePagination, useClientPagination } from '@/components/ui/TablePagination';
|
|
|
|
const DEVICE_TYPES = ['laptop', 'tablet', 'mobile'] as const;
|
|
type DeviceType = (typeof DEVICE_TYPES)[number];
|
|
type StatusFilter = 'active' | 'inactive';
|
|
type SortField = 'name' | 'slug' | 'status';
|
|
type SortDir = 'asc' | 'desc';
|
|
type SortConfig = { field: SortField; dir: SortDir };
|
|
type FilterSection = 'name' | 'deviceTypes' | 'status';
|
|
|
|
type BrandFilters = {
|
|
brandIds: string[];
|
|
deviceTypes: DeviceType[];
|
|
statuses: StatusFilter[];
|
|
};
|
|
|
|
const EMPTY_FILTERS: BrandFilters = {
|
|
brandIds: [],
|
|
deviceTypes: [],
|
|
statuses: [],
|
|
};
|
|
|
|
const FILTER_PAGE_SIZE = 5;
|
|
|
|
const EMPTY_COLUMNS = {
|
|
brandName: true,
|
|
slug: true,
|
|
deviceTypes: true,
|
|
status: true,
|
|
actions: true,
|
|
};
|
|
|
|
const COLUMN_OPTIONS = [
|
|
{ key: 'brandName' as const, label: 'Brand Name', locked: true },
|
|
{ key: 'slug' as const, label: 'Slug / Path', locked: false },
|
|
{ key: 'deviceTypes' as const, label: 'Device Types', locked: false },
|
|
{ key: 'status' as const, label: 'Status', locked: false },
|
|
{ key: 'actions' as const, label: 'Actions', locked: false },
|
|
];
|
|
|
|
const SORT_OPTIONS: { field: SortField; dir: SortDir; label: string }[] = [
|
|
{ field: 'name', dir: 'asc', label: 'Name A-Z' },
|
|
{ field: 'name', dir: 'desc', label: 'Name Z-A' },
|
|
{ field: 'slug', dir: 'asc', label: 'Slug A-Z' },
|
|
{ field: 'slug', dir: 'desc', label: 'Slug Z-A' },
|
|
{ field: 'status', dir: 'asc', label: 'Status Active first' },
|
|
{ field: 'status', dir: 'desc', label: 'Status Inactive first' },
|
|
];
|
|
|
|
const DEFAULT_SORT: SortConfig = { field: 'name', dir: 'asc' };
|
|
const DEFAULT_DATE_FROM = format(subDays(new Date(), 30), 'yyyy-MM-dd');
|
|
const DEFAULT_DATE_TO = format(new Date(), 'yyyy-MM-dd');
|
|
|
|
function normalizeId(value: unknown): string {
|
|
if (value == null) return '';
|
|
return String(value).trim();
|
|
}
|
|
|
|
function coerceFlag(value: unknown): boolean {
|
|
if (typeof value === 'boolean') return value;
|
|
if (typeof value === 'number') return value !== 0;
|
|
if (value == null) return false;
|
|
const normalized = String(value).trim().toLowerCase();
|
|
if (['true', '1', 'yes', 'enabled', 'active'].includes(normalized)) return true;
|
|
if (['false', '0', 'no', 'disabled', 'inactive', '', 'null', 'undefined'].includes(normalized)) return false;
|
|
return false;
|
|
}
|
|
|
|
function dayStartMs(isoDate: string): number {
|
|
const [year, month, day] = isoDate.split('-').map(Number);
|
|
if (!year || !month || !day) return NaN;
|
|
return new Date(year, month - 1, day, 0, 0, 0, 0).getTime();
|
|
}
|
|
|
|
function dayEndMs(isoDate: string): number {
|
|
const [year, month, day] = isoDate.split('-').map(Number);
|
|
if (!year || !month || !day) return NaN;
|
|
return new Date(year, month - 1, day, 23, 59, 59, 999).getTime();
|
|
}
|
|
|
|
function formatDeviceTypes(types?: string[]): string {
|
|
if (!types || types.length === 0) return '—';
|
|
return types.map((t) => t.charAt(0).toUpperCase() + t.slice(1)).join(', ');
|
|
}
|
|
|
|
export default function BrandsPage() {
|
|
const [brands, setBrands] = useState<BrandResponse[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [searchQuery, setSearchQuery] = useState('');
|
|
const [viewMode, setViewMode] = useState<'table' | 'grid'>('table');
|
|
const [openActionId, setOpenActionId] = useState<string | null>(null);
|
|
const [showFilterPanel, setShowFilterPanel] = useState(false);
|
|
const [showExportMenu, setShowExportMenu] = useState(false);
|
|
const [showColumnsPanel, setShowColumnsPanel] = useState(false);
|
|
const [showSortPanel, setShowSortPanel] = useState(false);
|
|
const [showDatePanel, setShowDatePanel] = useState(false);
|
|
const [draftFilters, setDraftFilters] = useState<BrandFilters>(EMPTY_FILTERS);
|
|
const [activeFilters, setActiveFilters] = useState<BrandFilters>(EMPTY_FILTERS);
|
|
const [expandedFilterSections, setExpandedFilterSections] = useState<Record<FilterSection, boolean>>({
|
|
name: false,
|
|
deviceTypes: true,
|
|
status: false,
|
|
});
|
|
const [filterSectionSearch, setFilterSectionSearch] = useState({ name: '' });
|
|
const [filterVisibleCounts, setFilterVisibleCounts] = useState({ name: FILTER_PAGE_SIZE });
|
|
const [visibleColumns, setVisibleColumns] = useState(EMPTY_COLUMNS);
|
|
const [sortConfig, setSortConfig] = useState<SortConfig>(DEFAULT_SORT);
|
|
const [dateFrom, setDateFrom] = useState(DEFAULT_DATE_FROM);
|
|
const [dateTo, setDateTo] = useState(DEFAULT_DATE_TO);
|
|
const [draftDateFrom, setDraftDateFrom] = useState(DEFAULT_DATE_FROM);
|
|
const [draftDateTo, setDraftDateTo] = useState(DEFAULT_DATE_TO);
|
|
const [dateFilterEnabled, setDateFilterEnabled] = useState(false);
|
|
const filterRef = useRef<HTMLDivElement>(null);
|
|
const exportRef = useRef<HTMLDivElement>(null);
|
|
const columnsRef = useRef<HTMLDivElement>(null);
|
|
const sortRef = useRef<HTMLDivElement>(null);
|
|
const dateRef = useRef<HTMLDivElement>(null);
|
|
|
|
const [showBrandModal, setShowBrandModal] = useState(false);
|
|
const [editingBrand, setEditingBrand] = useState<BrandResponse | null>(null);
|
|
const [brandName, setBrandName] = useState('');
|
|
const [brandLogo, setBrandLogo] = useState('');
|
|
const [selectedDeviceTypes, setSelectedDeviceTypes] = useState<string[]>([]);
|
|
const [hasMultipleDevices, setHasMultipleDevices] = useState(false);
|
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
|
const [deleteTarget, setDeleteTarget] = useState<{ id: string; name: string } | null>(null);
|
|
const [isDeleting, setIsDeleting] = useState(false);
|
|
|
|
const fetchData = async () => {
|
|
setLoading(true);
|
|
try {
|
|
const fetchedBrands = await catalogService.getBrands();
|
|
setBrands(fetchedBrands);
|
|
} catch (err: any) {
|
|
toast.error(err?.message || 'Failed to load brand data');
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
fetchData();
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!showFilterPanel) return;
|
|
const onPointerDown = (event: MouseEvent) => {
|
|
if (!filterRef.current?.contains(event.target as Node)) setShowFilterPanel(false);
|
|
};
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') setShowFilterPanel(false);
|
|
};
|
|
document.addEventListener('mousedown', onPointerDown);
|
|
document.addEventListener('keydown', onKeyDown);
|
|
return () => {
|
|
document.removeEventListener('mousedown', onPointerDown);
|
|
document.removeEventListener('keydown', onKeyDown);
|
|
};
|
|
}, [showFilterPanel]);
|
|
|
|
useEffect(() => {
|
|
if (!showExportMenu) return;
|
|
const onPointerDown = (event: MouseEvent) => {
|
|
if (!exportRef.current?.contains(event.target as Node)) setShowExportMenu(false);
|
|
};
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') setShowExportMenu(false);
|
|
};
|
|
document.addEventListener('mousedown', onPointerDown);
|
|
document.addEventListener('keydown', onKeyDown);
|
|
return () => {
|
|
document.removeEventListener('mousedown', onPointerDown);
|
|
document.removeEventListener('keydown', onKeyDown);
|
|
};
|
|
}, [showExportMenu]);
|
|
|
|
useEffect(() => {
|
|
if (!showColumnsPanel) return;
|
|
const onPointerDown = (event: MouseEvent) => {
|
|
if (!columnsRef.current?.contains(event.target as Node)) setShowColumnsPanel(false);
|
|
};
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') setShowColumnsPanel(false);
|
|
};
|
|
document.addEventListener('mousedown', onPointerDown);
|
|
document.addEventListener('keydown', onKeyDown);
|
|
return () => {
|
|
document.removeEventListener('mousedown', onPointerDown);
|
|
document.removeEventListener('keydown', onKeyDown);
|
|
};
|
|
}, [showColumnsPanel]);
|
|
|
|
useEffect(() => {
|
|
if (!showSortPanel) return;
|
|
const onPointerDown = (event: MouseEvent) => {
|
|
if (!sortRef.current?.contains(event.target as Node)) setShowSortPanel(false);
|
|
};
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') setShowSortPanel(false);
|
|
};
|
|
document.addEventListener('mousedown', onPointerDown);
|
|
document.addEventListener('keydown', onKeyDown);
|
|
return () => {
|
|
document.removeEventListener('mousedown', onPointerDown);
|
|
document.removeEventListener('keydown', onKeyDown);
|
|
};
|
|
}, [showSortPanel]);
|
|
|
|
useEffect(() => {
|
|
if (!showDatePanel) return;
|
|
const onPointerDown = (event: MouseEvent) => {
|
|
if (!dateRef.current?.contains(event.target as Node)) setShowDatePanel(false);
|
|
};
|
|
const onKeyDown = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') setShowDatePanel(false);
|
|
};
|
|
document.addEventListener('mousedown', onPointerDown);
|
|
document.addEventListener('keydown', onKeyDown);
|
|
return () => {
|
|
document.removeEventListener('mousedown', onPointerDown);
|
|
document.removeEventListener('keydown', onKeyDown);
|
|
};
|
|
}, [showDatePanel]);
|
|
|
|
const closeOverlays = () => {
|
|
setShowFilterPanel(false);
|
|
setShowColumnsPanel(false);
|
|
setShowSortPanel(false);
|
|
setShowDatePanel(false);
|
|
};
|
|
|
|
const handleViewModeChange = (mode: 'table' | 'grid') => {
|
|
setViewMode(mode);
|
|
setOpenActionId(null);
|
|
closeOverlays();
|
|
};
|
|
|
|
const handleOpenCreate = () => {
|
|
setEditingBrand(null);
|
|
setBrandName('');
|
|
setBrandLogo('');
|
|
setSelectedDeviceTypes([]);
|
|
setHasMultipleDevices(false);
|
|
setShowBrandModal(true);
|
|
};
|
|
|
|
const handleOpenEdit = (brand: BrandResponse) => {
|
|
setEditingBrand(brand);
|
|
setBrandName(brand.name);
|
|
setBrandLogo(brand.logo_url || '');
|
|
setSelectedDeviceTypes(brand.device_types || []);
|
|
setHasMultipleDevices((brand.device_types || []).length > 0);
|
|
setShowBrandModal(true);
|
|
};
|
|
|
|
const closeBrandDrawer = () => {
|
|
if (isSubmitting) return;
|
|
setShowBrandModal(false);
|
|
};
|
|
|
|
const handleSubmitBrand = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
if (!brandName.trim()) {
|
|
toast.error('Brand name is required');
|
|
return;
|
|
}
|
|
setIsSubmitting(true);
|
|
try {
|
|
const payloadDeviceTypes = hasMultipleDevices ? selectedDeviceTypes : [];
|
|
if (editingBrand) {
|
|
const updated = await catalogService.updateBrand(editingBrand.brand_id, {
|
|
name: brandName.trim(),
|
|
logo_url: brandLogo ? brandLogo.trim() : '',
|
|
device_types: payloadDeviceTypes,
|
|
});
|
|
setBrands(brands.map((b) => (b.brand_id === updated.brand_id ? updated : b)));
|
|
toast.success(`Brand "${updated.name}" updated successfully`);
|
|
} else {
|
|
const created = await catalogService.createBrand({
|
|
name: brandName.trim(),
|
|
logo_url: brandLogo ? brandLogo.trim() : '',
|
|
device_types: payloadDeviceTypes,
|
|
});
|
|
setBrands([...brands, created]);
|
|
toast.success(`Brand "${created.name}" created successfully`);
|
|
}
|
|
setBrandName('');
|
|
setBrandLogo('');
|
|
setSelectedDeviceTypes([]);
|
|
setHasMultipleDevices(false);
|
|
setEditingBrand(null);
|
|
setShowBrandModal(false);
|
|
} catch (err: any) {
|
|
toast.error(err?.message || `Failed to ${editingBrand ? 'update' : 'create'} brand`);
|
|
} finally {
|
|
setIsSubmitting(false);
|
|
}
|
|
};
|
|
|
|
const openDeleteModal = (id: string, name: string) => {
|
|
setOpenActionId(null);
|
|
setDeleteTarget({ id, name });
|
|
};
|
|
|
|
const closeDeleteModal = () => {
|
|
if (isDeleting) return;
|
|
setDeleteTarget(null);
|
|
};
|
|
|
|
const handleConfirmDelete = async () => {
|
|
if (!deleteTarget) return;
|
|
const { id, name } = deleteTarget;
|
|
setIsDeleting(true);
|
|
try {
|
|
setBrands((prev) => prev.filter((b) => b.brand_id !== id));
|
|
await catalogService.deleteBrand(id);
|
|
toast.success(`Brand "${name}" deleted successfully`);
|
|
setDeleteTarget(null);
|
|
fetchData();
|
|
} catch (err: any) {
|
|
toast.error(err?.message || 'Failed to delete brand');
|
|
fetchData();
|
|
} finally {
|
|
setIsDeleting(false);
|
|
}
|
|
};
|
|
|
|
const filteredBrands = useMemo(() => {
|
|
const q = searchQuery.trim().toLowerCase();
|
|
const fromTs = dateFilterEnabled && dateFrom ? dayStartMs(dateFrom) : null;
|
|
const toTs = dateFilterEnabled && dateTo ? dayEndMs(dateTo) : null;
|
|
|
|
const result = brands.filter((b) => {
|
|
const searchMatch =
|
|
!q ||
|
|
(b.name || '').toLowerCase().includes(q) ||
|
|
(b.slug || '').toLowerCase().includes(q);
|
|
|
|
const isActive = coerceFlag(b.is_active);
|
|
const statusMatch =
|
|
activeFilters.statuses.length === 0 ||
|
|
(activeFilters.statuses.includes('active') && isActive) ||
|
|
(activeFilters.statuses.includes('inactive') && !isActive);
|
|
|
|
const brandMatch =
|
|
activeFilters.brandIds.length === 0 ||
|
|
activeFilters.brandIds.includes(normalizeId(b.brand_id));
|
|
|
|
const brandDeviceTypes = b.device_types || [];
|
|
const deviceMatch =
|
|
activeFilters.deviceTypes.length === 0 ||
|
|
activeFilters.deviceTypes.some((dt) => brandDeviceTypes.includes(dt));
|
|
|
|
let dateMatch = true;
|
|
if (fromTs != null && toTs != null && !Number.isNaN(fromTs) && !Number.isNaN(toTs)) {
|
|
const createdTs = new Date(b.created_at).getTime();
|
|
if (!Number.isNaN(createdTs)) {
|
|
dateMatch = createdTs >= fromTs && createdTs <= toTs;
|
|
}
|
|
}
|
|
|
|
return searchMatch && brandMatch && statusMatch && deviceMatch && dateMatch;
|
|
});
|
|
|
|
const dir = sortConfig.dir === 'asc' ? 1 : -1;
|
|
return [...result].sort((a, b) => {
|
|
if (sortConfig.field === 'status') {
|
|
return (Number(coerceFlag(a.is_active)) - Number(coerceFlag(b.is_active))) * dir;
|
|
}
|
|
const left = sortConfig.field === 'name' ? a.name || '' : a.slug || '';
|
|
const right = sortConfig.field === 'name' ? b.name || '' : b.slug || '';
|
|
return left.localeCompare(right, undefined, { sensitivity: 'base' }) * dir;
|
|
});
|
|
}, [brands, searchQuery, activeFilters, dateFrom, dateTo, dateFilterEnabled, sortConfig]);
|
|
|
|
const pager = useClientPagination(filteredBrands);
|
|
|
|
const filtersActive =
|
|
activeFilters.brandIds.length > 0 ||
|
|
activeFilters.deviceTypes.length > 0 ||
|
|
activeFilters.statuses.length > 0;
|
|
|
|
const sortedBrandFilterOptions = useMemo(
|
|
() => [...brands].sort((a, b) => a.name.localeCompare(b.name)),
|
|
[brands]
|
|
);
|
|
|
|
const toggleFilterSection = (section: FilterSection) => {
|
|
setExpandedFilterSections((prev) => ({ ...prev, [section]: !prev[section] }));
|
|
};
|
|
|
|
const toggleDraftListValue = <T extends string>(
|
|
key: keyof Pick<BrandFilters, 'brandIds' | 'deviceTypes' | 'statuses'>,
|
|
value: T
|
|
) => {
|
|
setDraftFilters((prev) => {
|
|
const current = prev[key] as T[];
|
|
return {
|
|
...prev,
|
|
[key]: current.includes(value) ? current.filter((item) => item !== value) : [...current, value],
|
|
};
|
|
});
|
|
};
|
|
|
|
const openFilterPanel = () => {
|
|
setDraftFilters(activeFilters);
|
|
setFilterSectionSearch({ name: '' });
|
|
setFilterVisibleCounts({ name: FILTER_PAGE_SIZE });
|
|
setShowColumnsPanel(false);
|
|
setShowSortPanel(false);
|
|
setShowDatePanel(false);
|
|
setShowFilterPanel(true);
|
|
};
|
|
|
|
const visibleColumnCount = Object.values(visibleColumns).filter(Boolean).length;
|
|
|
|
const toggleColumn = (key: keyof typeof EMPTY_COLUMNS) => {
|
|
if (key === 'brandName') return;
|
|
setVisibleColumns((prev) => ({ ...prev, [key]: !prev[key] }));
|
|
};
|
|
|
|
const handleExportExcel = () => {
|
|
if (filteredBrands.length === 0) {
|
|
toast.warning('No brands to export');
|
|
return;
|
|
}
|
|
const headers = ['S.No', 'Brand Name', 'Slug / Path', 'Device Types', 'Status'];
|
|
const rows = filteredBrands.map((b, i) => [
|
|
i + 1,
|
|
b.name,
|
|
b.slug || '',
|
|
formatDeviceTypes(b.device_types),
|
|
coerceFlag(b.is_active) ? 'Active' : 'Inactive',
|
|
]);
|
|
const csvContent = [headers.join(','), ...rows.map((row) => row.map((val) => `"${String(val).replace(/"/g, '""')}"`).join(','))].join('\n');
|
|
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
|
|
const url = URL.createObjectURL(blob);
|
|
const link = document.createElement('a');
|
|
link.href = url;
|
|
link.download = `ifixkart_brands_${format(new Date(), 'yyyyMMdd')}.csv`;
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
document.body.removeChild(link);
|
|
URL.revokeObjectURL(url);
|
|
setShowExportMenu(false);
|
|
toast.success(`Downloaded ${filteredBrands.length} ${filteredBrands.length === 1 ? 'brand' : 'brands'} as CSV`);
|
|
};
|
|
|
|
const handleExportPDF = () => {
|
|
if (filteredBrands.length === 0) {
|
|
toast.warning('No brands to export');
|
|
return;
|
|
}
|
|
const printWindow = window.open('', '_blank');
|
|
if (!printWindow) {
|
|
toast.error('Allow pop-ups to open the brands print preview');
|
|
return;
|
|
}
|
|
const html = `
|
|
<html>
|
|
<head>
|
|
<title>iFixKart Brands PDF Export</title>
|
|
<style>
|
|
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; padding: 20px; color: #1e293b; }
|
|
h2 { color: #0f172a; border-bottom: 2px solid #e2e8f0; padding-bottom: 10px; }
|
|
table { width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 11px; }
|
|
th { background-color: #0f172a; color: white; padding: 10px; text-align: left; }
|
|
td { padding: 10px; border-bottom: 1px solid #e2e8f0; }
|
|
tr:nth-child(even) { background-color: #f8fafc; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<h2>iFixKart Brands (${filteredBrands.length} Records)</h2>
|
|
<p>Exported on: ${format(new Date(), 'yyyy-MM-dd HH:mm:ss')}</p>
|
|
<table>
|
|
<thead>
|
|
<tr>
|
|
<th>S.No</th>
|
|
<th>Brand Name</th>
|
|
<th>Slug / Path</th>
|
|
<th>Device Types</th>
|
|
<th>Status</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
${filteredBrands.map((b, i) => `
|
|
<tr>
|
|
<td>${i + 1}</td>
|
|
<td>${b.name}</td>
|
|
<td>${b.slug || ''}</td>
|
|
<td>${formatDeviceTypes(b.device_types)}</td>
|
|
<td>${coerceFlag(b.is_active) ? 'Active' : 'Inactive'}</td>
|
|
</tr>
|
|
`).join('')}
|
|
</tbody>
|
|
</table>
|
|
<script>window.onload = function() { window.print(); }</script>
|
|
</body>
|
|
</html>
|
|
`;
|
|
printWindow.document.write(html);
|
|
printWindow.document.close();
|
|
setShowExportMenu(false);
|
|
toast.success(`Print preview opened for ${filteredBrands.length} ${filteredBrands.length === 1 ? 'brand' : 'brands'}`);
|
|
};
|
|
|
|
const dateRangeLabel = `${format(new Date(dayStartMs(dateFrom || DEFAULT_DATE_FROM)), 'd MMM yy')} - ${format(new Date(dayStartMs(dateTo || DEFAULT_DATE_TO)), 'd MMM yy')}`;
|
|
|
|
const dataCardShell = 'crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] overflow-hidden min-w-0';
|
|
|
|
const renderSortLabel = (label: string, field?: SortField, showIcon = true) => {
|
|
const active = field != null && sortConfig.field === field;
|
|
return (
|
|
<span className="inline-flex items-center gap-1.5">
|
|
{label}
|
|
{showIcon && (
|
|
<ArrowUpDown className={`w-3.5 h-3.5 shrink-0 ${active ? 'text-gray-700' : 'text-gray-400'}`} />
|
|
)}
|
|
</span>
|
|
);
|
|
};
|
|
|
|
const renderStatusBadge = (active: boolean) => (
|
|
<span
|
|
className={`inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold ${
|
|
active ? 'bg-success text-white' : 'bg-destructive text-white'
|
|
}`}
|
|
>
|
|
{active ? 'Active' : 'Inactive'}
|
|
</span>
|
|
);
|
|
|
|
const renderDeviceTypeBadges = (types?: string[]) => {
|
|
if (!types || types.length === 0) {
|
|
return <span className="text-[13px] text-muted-foreground">—</span>;
|
|
}
|
|
return (
|
|
<div className="flex flex-wrap gap-1.5">
|
|
{types.map((dt) => (
|
|
<span
|
|
key={dt}
|
|
className="inline-flex items-center px-2 py-0.5 crm-radius-badge text-[11px] font-semibold bg-muted text-muted-foreground capitalize"
|
|
>
|
|
{dt}
|
|
</span>
|
|
))}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const renderBrandAvatar = (brand: BrandResponse, size: 'sm' | 'md' = 'md') => {
|
|
const dim = size === 'sm' ? 'w-9 h-9' : 'w-10 h-10';
|
|
return (
|
|
<div className={`${dim} crm-radius-icon bg-primary/10 text-primary flex items-center justify-center shrink-0 overflow-hidden`}>
|
|
{brand.logo_url ? (
|
|
<img src={getMediaUrl(brand.logo_url)} alt={brand.name} className="w-full h-full object-contain p-1" />
|
|
) : (
|
|
<Tag className="w-4 h-4" />
|
|
)}
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const searchField = (
|
|
<div className="relative flex-1 min-w-[180px] max-w-[480px]">
|
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none" />
|
|
<input
|
|
type="text"
|
|
placeholder="Search"
|
|
value={searchQuery}
|
|
onChange={(e) => setSearchQuery(e.target.value)}
|
|
className="w-full h-9 pl-9 pr-3 crm-radius-control border border-border bg-card text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary transition-colors"
|
|
/>
|
|
</div>
|
|
);
|
|
|
|
const addBrandButton = (
|
|
<button
|
|
type="button"
|
|
onClick={handleOpenCreate}
|
|
className="inline-flex items-center gap-2 h-9 px-4 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer shrink-0"
|
|
>
|
|
<span className="w-[18px] h-[18px] rounded-full bg-white text-primary flex items-center justify-center">
|
|
<Plus className="w-3 h-3" strokeWidth={3} />
|
|
</span>
|
|
Add Brand
|
|
</button>
|
|
);
|
|
|
|
const viewToggle = <ViewModeToggle value={viewMode} onChange={handleViewModeChange} />;
|
|
|
|
const renderFilterControl = (align: 'left' | 'right') => {
|
|
const nameQuery = filterSectionSearch.name.trim().toLowerCase();
|
|
const filteredNameOptions = sortedBrandFilterOptions.filter((brand) =>
|
|
!nameQuery || brand.name.toLowerCase().includes(nameQuery) || (brand.slug || '').toLowerCase().includes(nameQuery)
|
|
);
|
|
const visibleNameOptions = filteredNameOptions.slice(0, filterVisibleCounts.name);
|
|
|
|
const renderSectionSearch = (value: string, onChange: (next: string) => void) => (
|
|
<div className="relative">
|
|
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none" />
|
|
<input
|
|
type="text"
|
|
placeholder="Search"
|
|
value={value}
|
|
onChange={(e) => {
|
|
onChange(e.target.value);
|
|
setFilterVisibleCounts({ name: FILTER_PAGE_SIZE });
|
|
}}
|
|
className="w-full h-8 pl-8 pr-3 crm-radius-control border border-border bg-card text-[12px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary"
|
|
/>
|
|
</div>
|
|
);
|
|
|
|
const renderCheckboxOption = (checked: boolean, onToggle: () => void, label: string, icon?: ReactNode) => (
|
|
<label className="flex items-center gap-2.5 py-1.5 cursor-pointer">
|
|
<input
|
|
type="checkbox"
|
|
checked={checked}
|
|
onChange={onToggle}
|
|
className="w-3.5 h-3.5 rounded-[3px] border-border text-primary focus:ring-primary cursor-pointer"
|
|
/>
|
|
{icon}
|
|
<span className="text-[13px] text-muted-foreground">{label}</span>
|
|
</label>
|
|
);
|
|
|
|
return (
|
|
<div className="relative shrink-0" ref={filterRef}>
|
|
<button
|
|
type="button"
|
|
onClick={() => (showFilterPanel ? setShowFilterPanel(false) : openFilterPanel())}
|
|
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control text-[13px] font-medium cursor-pointer transition-colors ${
|
|
showFilterPanel || filtersActive
|
|
? 'bg-primary text-white'
|
|
: 'border border-border bg-card text-foreground hover:bg-muted'
|
|
}`}
|
|
>
|
|
<Filter className="w-3.5 h-3.5" />
|
|
Filter
|
|
{filtersActive && !showFilterPanel && <span className="w-1.5 h-1.5 rounded-full bg-white" />}
|
|
<ChevronDown
|
|
className={`w-3.5 h-3.5 transition-transform ${showFilterPanel ? 'rotate-180' : ''} ${
|
|
showFilterPanel || filtersActive ? 'text-white/80' : 'text-muted-foreground'
|
|
}`}
|
|
/>
|
|
</button>
|
|
<AnimatePresence>
|
|
{showFilterPanel && (
|
|
<motion.div
|
|
initial={{ opacity: 0, y: -6 }}
|
|
animate={{ opacity: 1, y: 0 }}
|
|
exit={{ opacity: 0, y: -6 }}
|
|
transition={{ duration: 0.16, ease: 'easeOut' }}
|
|
className={`absolute ${align === 'right' ? 'right-0' : 'left-0'} top-full mt-1.5 z-50 w-[320px] max-w-[calc(100vw-2rem)] crm-radius-card border border-border bg-card shadow-lg overflow-hidden`}
|
|
>
|
|
<div className="flex items-center justify-between px-4 py-3 border-b border-border">
|
|
<span className="inline-flex items-center gap-2 text-[14px] font-semibold text-foreground">
|
|
<Filter className="w-4 h-4" />
|
|
Filter
|
|
</span>
|
|
<button
|
|
type="button"
|
|
aria-label="Close filters"
|
|
onClick={() => setShowFilterPanel(false)}
|
|
className="w-7 h-7 rounded-full bg-primary/10 text-primary hover:bg-primary hover:text-white cursor-pointer transition-colors flex items-center justify-center"
|
|
>
|
|
<X className="w-3.5 h-3.5" />
|
|
</button>
|
|
</div>
|
|
|
|
<div className="max-h-[420px] overflow-y-auto">
|
|
<div className="border-b border-border">
|
|
<button
|
|
type="button"
|
|
onClick={() => toggleFilterSection('name')}
|
|
className="w-full flex items-center gap-2 px-4 py-3 text-[13px] font-semibold text-foreground hover:bg-muted/20 cursor-pointer"
|
|
>
|
|
<ChevronRight className={`w-3.5 h-3.5 transition-transform ${expandedFilterSections.name ? 'rotate-90' : ''}`} />
|
|
Brand Name
|
|
</button>
|
|
{expandedFilterSections.name && (
|
|
<div className="px-4 pb-4">
|
|
<div className="crm-radius-control border border-border bg-muted/20 p-3 space-y-2">
|
|
{renderSectionSearch(filterSectionSearch.name, (value) =>
|
|
setFilterSectionSearch({ name: value })
|
|
)}
|
|
<div className="space-y-0.5">
|
|
{visibleNameOptions.length === 0 ? (
|
|
<p className="py-2 text-[12px] text-muted-foreground">No brands found.</p>
|
|
) : (
|
|
visibleNameOptions.map((brand) => {
|
|
const id = normalizeId(brand.brand_id);
|
|
return renderCheckboxOption(
|
|
draftFilters.brandIds.includes(id),
|
|
() => toggleDraftListValue('brandIds', id),
|
|
brand.name,
|
|
renderBrandAvatar(brand, 'sm')
|
|
);
|
|
})
|
|
)}
|
|
</div>
|
|
{filteredNameOptions.length > visibleNameOptions.length && (
|
|
<button
|
|
type="button"
|
|
onClick={() =>
|
|
setFilterVisibleCounts((prev) => ({ name: prev.name + FILTER_PAGE_SIZE }))
|
|
}
|
|
className="text-[12px] font-medium text-primary underline underline-offset-2 cursor-pointer"
|
|
>
|
|
Load More
|
|
</button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div className="border-b border-border">
|
|
<button
|
|
type="button"
|
|
onClick={() => toggleFilterSection('deviceTypes')}
|
|
className="w-full flex items-center gap-2 px-4 py-3 text-[13px] font-semibold text-foreground hover:bg-muted/20 cursor-pointer"
|
|
>
|
|
<ChevronRight className={`w-3.5 h-3.5 transition-transform ${expandedFilterSections.deviceTypes ? 'rotate-90' : ''}`} />
|
|
Device Types
|
|
</button>
|
|
{expandedFilterSections.deviceTypes && (
|
|
<div className="px-4 pb-4">
|
|
<div className="crm-radius-control border border-border bg-muted/20 p-3 space-y-1">
|
|
{DEVICE_TYPES.map((dt) =>
|
|
renderCheckboxOption(
|
|
draftFilters.deviceTypes.includes(dt),
|
|
() => toggleDraftListValue('deviceTypes', dt),
|
|
dt.charAt(0).toUpperCase() + dt.slice(1)
|
|
)
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<div>
|
|
<button
|
|
type="button"
|
|
onClick={() => toggleFilterSection('status')}
|
|
className="w-full flex items-center gap-2 px-4 py-3 text-[13px] font-semibold text-foreground hover:bg-muted/20 cursor-pointer"
|
|
>
|
|
<ChevronRight className={`w-3.5 h-3.5 transition-transform ${expandedFilterSections.status ? 'rotate-90' : ''}`} />
|
|
Status
|
|
</button>
|
|
{expandedFilterSections.status && (
|
|
<div className="px-4 pb-4">
|
|
<div className="crm-radius-control border border-border bg-muted/20 p-3 space-y-1">
|
|
{renderCheckboxOption(
|
|
draftFilters.statuses.includes('active'),
|
|
() => toggleDraftListValue('statuses', 'active'),
|
|
'Active'
|
|
)}
|
|
{renderCheckboxOption(
|
|
draftFilters.statuses.includes('inactive'),
|
|
() => toggleDraftListValue('statuses', 'inactive'),
|
|
'Inactive'
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-3 px-4 py-3 border-t border-border">
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setDraftFilters(EMPTY_FILTERS);
|
|
setActiveFilters(EMPTY_FILTERS);
|
|
setShowFilterPanel(false);
|
|
}}
|
|
className="flex-1 h-9 crm-radius-control border border-border bg-card text-[13px] font-medium text-foreground hover:bg-muted cursor-pointer"
|
|
>
|
|
Reset
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setActiveFilters(draftFilters);
|
|
setShowFilterPanel(false);
|
|
}}
|
|
className="flex-1 h-9 crm-radius-control bg-primary text-white text-[13px] font-semibold cursor-pointer hover:bg-primary/90"
|
|
>
|
|
Filter
|
|
</button>
|
|
</div>
|
|
</motion.div>
|
|
)}
|
|
</AnimatePresence>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
const manageColumnsControl = (
|
|
<div className="relative shrink-0" ref={columnsRef}>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
const next = !showColumnsPanel;
|
|
setShowFilterPanel(false);
|
|
setShowSortPanel(false);
|
|
setShowDatePanel(false);
|
|
setShowColumnsPanel(next);
|
|
}}
|
|
className="inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control text-[13px] font-medium cursor-pointer transition-colors bg-primary/10 text-primary border border-primary/25 hover:bg-primary/15"
|
|
>
|
|
<Columns3 className="w-3.5 h-3.5" />
|
|
Manage Columns
|
|
</button>
|
|
{showColumnsPanel && (
|
|
<div className="absolute right-0 top-full mt-1.5 z-50 w-[240px] crm-radius-card border border-border bg-card shadow-lg py-1.5 overflow-hidden">
|
|
{COLUMN_OPTIONS.map((col) => (
|
|
<div key={col.key} className="flex items-center gap-2 px-3 py-1.5">
|
|
<GripVertical className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
|
|
<span className="flex-1 text-[13px] text-foreground truncate">{col.label}</span>
|
|
<button
|
|
type="button"
|
|
role="switch"
|
|
aria-checked={visibleColumns[col.key]}
|
|
aria-label={`Toggle ${col.label}`}
|
|
disabled={col.locked}
|
|
title={col.locked ? 'Brand Name stays visible' : `Toggle ${col.label}`}
|
|
onClick={() => toggleColumn(col.key)}
|
|
className={`relative w-8 h-[18px] rounded-full shrink-0 transition-colors ${
|
|
visibleColumns[col.key] ? 'bg-primary' : 'bg-muted'
|
|
} ${col.locked ? 'opacity-60 cursor-not-allowed' : 'cursor-pointer'}`}
|
|
>
|
|
<span
|
|
className={`absolute top-[2px] w-3.5 h-3.5 rounded-full bg-white shadow-xs transition-all ${
|
|
visibleColumns[col.key] ? 'left-[14px]' : 'left-[2px]'
|
|
}`}
|
|
/>
|
|
</button>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
|
|
const sortControl = (
|
|
<div className="relative shrink-0" ref={sortRef}>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
const next = !showSortPanel;
|
|
setShowFilterPanel(false);
|
|
setShowColumnsPanel(false);
|
|
setShowDatePanel(false);
|
|
setShowSortPanel(next);
|
|
}}
|
|
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control border border-border text-[13px] font-medium cursor-pointer transition-colors ${
|
|
showSortPanel || sortConfig.field !== DEFAULT_SORT.field || sortConfig.dir !== DEFAULT_SORT.dir
|
|
? 'bg-muted text-foreground'
|
|
: 'bg-card text-foreground hover:bg-muted'
|
|
}`}
|
|
>
|
|
<ArrowUpDown className="w-3.5 h-3.5" />
|
|
Sort By
|
|
<ChevronDown className={`w-3.5 h-3.5 text-muted-foreground transition-transform ${showSortPanel ? 'rotate-180' : ''}`} />
|
|
</button>
|
|
{showSortPanel && (
|
|
<div className="absolute left-0 top-full mt-1.5 z-50 w-56 crm-radius-card border border-border bg-card shadow-lg py-1 overflow-hidden">
|
|
{SORT_OPTIONS.map((option) => {
|
|
const active = option.field === sortConfig.field && option.dir === sortConfig.dir;
|
|
return (
|
|
<button
|
|
key={`${option.field}-${option.dir}`}
|
|
type="button"
|
|
onClick={() => {
|
|
setSortConfig({ field: option.field, dir: option.dir });
|
|
setShowSortPanel(false);
|
|
}}
|
|
className={`w-full text-left px-3 py-1.5 text-[13px] cursor-pointer ${
|
|
active ? 'bg-primary/10 text-primary font-medium' : 'text-foreground hover:bg-muted'
|
|
}`}
|
|
>
|
|
{option.label}
|
|
</button>
|
|
);
|
|
})}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
|
|
const dateControl = (
|
|
<div className="relative shrink-0" ref={dateRef}>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
const next = !showDatePanel;
|
|
setShowFilterPanel(false);
|
|
setShowColumnsPanel(false);
|
|
setShowSortPanel(false);
|
|
if (next) {
|
|
setDraftDateFrom(dateFrom || DEFAULT_DATE_FROM);
|
|
setDraftDateTo(dateTo || DEFAULT_DATE_TO);
|
|
setShowDatePanel(true);
|
|
} else {
|
|
setShowDatePanel(false);
|
|
}
|
|
}}
|
|
className={`inline-flex items-center gap-1.5 h-9 px-3 crm-radius-control border border-border text-[13px] font-medium cursor-pointer transition-colors ${
|
|
showDatePanel || dateFilterEnabled ? 'bg-muted text-foreground' : 'bg-card text-foreground hover:bg-muted'
|
|
}`}
|
|
>
|
|
<Calendar className="w-3.5 h-3.5" />
|
|
{dateRangeLabel}
|
|
</button>
|
|
{showDatePanel && (
|
|
<div className="absolute left-0 top-full mt-1.5 z-50 w-72 crm-radius-card border border-border bg-card shadow-lg overflow-hidden">
|
|
<div className="px-3.5 py-3 space-y-2.5">
|
|
<div>
|
|
<label className="block text-[10px] font-semibold tracking-wide text-muted-foreground uppercase mb-1">From</label>
|
|
<input
|
|
type="date"
|
|
value={draftDateFrom}
|
|
onChange={(e) => setDraftDateFrom(e.target.value)}
|
|
className="w-full h-8 px-2.5 crm-radius-control border border-border bg-card text-[13px] text-foreground outline-none focus:border-primary"
|
|
/>
|
|
</div>
|
|
<div>
|
|
<label className="block text-[10px] font-semibold tracking-wide text-muted-foreground uppercase mb-1">To</label>
|
|
<input
|
|
type="date"
|
|
value={draftDateTo}
|
|
onChange={(e) => setDraftDateTo(e.target.value)}
|
|
className="w-full h-8 px-2.5 crm-radius-control border border-border bg-card text-[13px] text-foreground outline-none focus:border-primary"
|
|
/>
|
|
</div>
|
|
</div>
|
|
<div className="flex items-center justify-between gap-2 px-3.5 py-2.5 border-t border-border">
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setDateFrom(DEFAULT_DATE_FROM);
|
|
setDateTo(DEFAULT_DATE_TO);
|
|
setDraftDateFrom(DEFAULT_DATE_FROM);
|
|
setDraftDateTo(DEFAULT_DATE_TO);
|
|
setDateFilterEnabled(false);
|
|
setShowDatePanel(false);
|
|
}}
|
|
className="h-8 px-3 crm-radius-control border border-border bg-card text-[12px] font-medium text-foreground hover:bg-muted cursor-pointer"
|
|
>
|
|
Clear
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
if (!draftDateFrom || !draftDateTo) {
|
|
toast.error('Choose a start date and an end date');
|
|
return;
|
|
}
|
|
if (draftDateFrom > draftDateTo) {
|
|
toast.error('Start date must be earlier than the end date');
|
|
return;
|
|
}
|
|
setDateFrom(draftDateFrom);
|
|
setDateTo(draftDateTo);
|
|
setDateFilterEnabled(true);
|
|
setShowDatePanel(false);
|
|
}}
|
|
className="h-8 px-3 crm-radius-control bg-primary text-primary-foreground text-[12px] font-medium cursor-pointer hover:bg-primary/90"
|
|
>
|
|
Apply
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
|
|
const emptyMessage =
|
|
searchQuery || filtersActive || dateFilterEnabled
|
|
? 'No brands match your search.'
|
|
: 'No brands found.';
|
|
|
|
return (
|
|
<div className="flex flex-col gap-5 min-w-0">
|
|
<div className="flex flex-wrap items-start justify-between gap-3 min-w-0">
|
|
<div className="min-w-0">
|
|
<div className="flex items-center gap-2">
|
|
<h1 className="text-lg font-semibold text-foreground">Brands</h1>
|
|
<span className="inline-flex items-center justify-center min-w-5 h-5 px-1.5 crm-radius-toggle bg-primary/10 text-primary text-[11px] font-semibold leading-none">
|
|
{brands.length}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-3 shrink-0">
|
|
<div className="relative" ref={exportRef}>
|
|
<button
|
|
type="button"
|
|
onClick={() => setShowExportMenu((open) => !open)}
|
|
className="inline-flex items-center gap-1.5 h-8 px-2.5 crm-radius-control border border-border bg-card text-[13px] font-medium text-foreground hover:bg-muted cursor-pointer"
|
|
>
|
|
<Box className="w-3.5 h-3.5" />
|
|
Export
|
|
<ChevronDown className="w-3.5 h-3.5 text-muted-foreground" />
|
|
</button>
|
|
{showExportMenu && (
|
|
<div className="absolute right-0 top-full mt-1.5 z-50 w-48 crm-radius-card border border-border bg-card shadow-lg py-1 overflow-hidden">
|
|
<button
|
|
type="button"
|
|
onClick={handleExportPDF}
|
|
className="w-full flex items-center gap-2 px-3 py-2 text-[13px] text-muted-foreground hover:bg-muted hover:text-foreground cursor-pointer"
|
|
>
|
|
<FileText className="w-4 h-4 text-destructive" />
|
|
Export as PDF
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleExportExcel}
|
|
className="w-full flex items-center gap-2 px-3 py-2 text-[13px] text-muted-foreground hover:bg-muted hover:text-foreground cursor-pointer"
|
|
>
|
|
<FileSpreadsheet className="w-4 h-4 text-green-600" />
|
|
Export as Excel
|
|
</button>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
<button
|
|
type="button"
|
|
onClick={fetchData}
|
|
className="w-8 h-8 crm-radius-control border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted cursor-pointer transition-colors flex items-center justify-center"
|
|
title="Reload Data"
|
|
>
|
|
<RefreshCw className="w-3.5 h-3.5" />
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
{viewMode === 'grid' ? (
|
|
<div className={dataCardShell}>
|
|
<div className="px-5 pt-5">
|
|
<div className="-mx-5 px-5 flex flex-wrap items-center justify-between gap-3 min-w-0 pb-4 border-b border-border">
|
|
<div className="flex flex-wrap items-center gap-3 min-w-0 flex-1">
|
|
{renderFilterControl('left')}
|
|
{searchField}
|
|
</div>
|
|
<div className="flex items-center gap-3 shrink-0">
|
|
{viewToggle}
|
|
{addBrandButton}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{loading ? (
|
|
<div className="flex flex-col items-center justify-center py-16 gap-2.5">
|
|
<RefreshCw className="w-6 h-6 text-primary animate-spin" />
|
|
<span className="text-[13px] text-muted-foreground">Loading brands...</span>
|
|
</div>
|
|
) : filteredBrands.length === 0 ? (
|
|
<div className="py-12 text-center text-[13px] text-muted-foreground">{emptyMessage}</div>
|
|
) : (
|
|
<div className="p-5 mt-4">
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
|
{pager.items.map((b) => (
|
|
<div
|
|
key={b.brand_id}
|
|
className="relative crm-radius-section border border-border bg-card p-5 min-w-0 shadow-sm hover:shadow-md transition-shadow"
|
|
>
|
|
<div className="absolute top-4 right-4 z-10">
|
|
<RowActionsMenu
|
|
open={openActionId === b.brand_id}
|
|
onOpenChange={(open) => setOpenActionId(open ? b.brand_id : null)}
|
|
onEdit={() => handleOpenEdit(b)}
|
|
onDelete={() => openDeleteModal(b.brand_id, b.name)}
|
|
/>
|
|
</div>
|
|
<div className="flex items-start gap-3 pr-8 min-w-0">
|
|
{renderBrandAvatar(b)}
|
|
<div className="min-w-0">
|
|
<p className="text-[14px] font-semibold text-foreground truncate">{b.name}</p>
|
|
<p className="text-[12px] text-muted-foreground truncate mt-0.5">{b.slug}</p>
|
|
</div>
|
|
</div>
|
|
<div className="mt-4">
|
|
{renderDeviceTypeBadges(b.device_types)}
|
|
</div>
|
|
<div className="mt-4 flex flex-wrap items-center gap-2">
|
|
{renderStatusBadge(coerceFlag(b.is_active))}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
<TablePagination {...pager} />
|
|
</div>
|
|
) : (
|
|
<div className={dataCardShell}>
|
|
<div className="px-5 pt-5">
|
|
<div className="flex flex-wrap items-center justify-between gap-4 w-full min-w-0 pb-4 border-b border-border">
|
|
{searchField}
|
|
{addBrandButton}
|
|
</div>
|
|
<div className="flex flex-wrap lg:flex-nowrap items-center justify-between gap-3 w-full min-w-0 py-4">
|
|
<div className="flex flex-wrap items-center gap-2 min-w-0">
|
|
{sortControl}
|
|
{dateControl}
|
|
</div>
|
|
<div className="flex flex-wrap items-center gap-2 shrink-0">
|
|
{renderFilterControl('right')}
|
|
{manageColumnsControl}
|
|
{viewToggle}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{loading ? (
|
|
<div className="flex flex-col items-center justify-center py-16 gap-2.5 border-t border-border">
|
|
<RefreshCw className="w-6 h-6 text-primary animate-spin" />
|
|
<span className="text-[13px] text-muted-foreground">Loading brands...</span>
|
|
</div>
|
|
) : (
|
|
<div className="overflow-x-auto border-t border-border">
|
|
<table className="crm-data-table min-w-[720px]">
|
|
<thead>
|
|
<tr className="bg-gray-50 border-y border-gray-200">
|
|
{visibleColumns.brandName && (
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700 whitespace-nowrap">
|
|
{renderSortLabel('Brand Name', 'name')}
|
|
</th>
|
|
)}
|
|
{visibleColumns.slug && (
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700 whitespace-nowrap">
|
|
{renderSortLabel('Slug / Path', 'slug')}
|
|
</th>
|
|
)}
|
|
{visibleColumns.deviceTypes && (
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700 whitespace-nowrap">
|
|
{renderSortLabel('Device Types')}
|
|
</th>
|
|
)}
|
|
{visibleColumns.status && (
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700 whitespace-nowrap">
|
|
{renderSortLabel('Status', 'status')}
|
|
</th>
|
|
)}
|
|
{visibleColumns.actions && (
|
|
<th className="px-5 py-3 text-center text-[13px] font-semibold text-gray-700 whitespace-nowrap">
|
|
{renderSortLabel('Action')}
|
|
</th>
|
|
)}
|
|
</tr>
|
|
</thead>
|
|
<tbody className="bg-card">
|
|
{filteredBrands.length === 0 ? (
|
|
<tr>
|
|
<td colSpan={Math.max(visibleColumnCount, 1)} className="text-center py-12 text-[13px] text-muted-foreground">
|
|
{emptyMessage}
|
|
</td>
|
|
</tr>
|
|
) : (
|
|
pager.items.map((b) => (
|
|
<tr key={b.brand_id} className="border-t border-border hover:bg-muted/10 transition-colors">
|
|
{visibleColumns.brandName && (
|
|
<td className="px-5 py-3.5">
|
|
<div className="flex items-center gap-3 min-w-0">
|
|
{renderBrandAvatar(b, 'sm')}
|
|
<div className="min-w-0">
|
|
<p className="text-[13px] font-semibold text-foreground truncate">{b.name}</p>
|
|
<p className="text-[11px] text-muted-foreground truncate">{b.slug}</p>
|
|
</div>
|
|
</div>
|
|
</td>
|
|
)}
|
|
{visibleColumns.slug && (
|
|
<td className="px-5 py-3.5 text-[13px] font-mono text-muted-foreground">{b.slug}</td>
|
|
)}
|
|
{visibleColumns.deviceTypes && (
|
|
<td className="px-5 py-3.5">{renderDeviceTypeBadges(b.device_types)}</td>
|
|
)}
|
|
{visibleColumns.status && (
|
|
<td className="px-5 py-3.5">{renderStatusBadge(coerceFlag(b.is_active))}</td>
|
|
)}
|
|
{visibleColumns.actions && (
|
|
<td className="px-5 py-3.5">
|
|
<div className="flex items-center justify-center">
|
|
<RowActionsMenu
|
|
open={openActionId === b.brand_id}
|
|
onOpenChange={(open) => setOpenActionId(open ? b.brand_id : null)}
|
|
onEdit={() => handleOpenEdit(b)}
|
|
onDelete={() => openDeleteModal(b.brand_id, b.name)}
|
|
/>
|
|
</div>
|
|
</td>
|
|
)}
|
|
</tr>
|
|
))
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
<TablePagination {...pager} />
|
|
</div>
|
|
)}
|
|
|
|
{deleteTarget && (
|
|
<div
|
|
className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 p-4"
|
|
onClick={closeDeleteModal}
|
|
>
|
|
<div
|
|
role="dialog"
|
|
aria-modal="true"
|
|
aria-labelledby="delete-brand-title"
|
|
className="bg-card border border-border shadow-2xl w-full max-w-sm overflow-hidden crm-radius-none"
|
|
onClick={(e) => e.stopPropagation()}
|
|
>
|
|
<div className="flex items-start justify-between gap-3 px-5 pt-5 pb-2">
|
|
<div className="flex items-start gap-3 min-w-0">
|
|
<div className="w-10 h-10 rounded-full bg-destructive/10 text-destructive flex items-center justify-center shrink-0">
|
|
<AlertTriangle className="w-5 h-5" />
|
|
</div>
|
|
<div className="min-w-0">
|
|
<h3 id="delete-brand-title" className="text-[15px] font-semibold text-foreground">
|
|
Delete Brand
|
|
</h3>
|
|
<p className="text-[13px] text-muted-foreground mt-1 leading-relaxed">
|
|
Are you sure you want to delete{' '}
|
|
<span className="font-semibold text-foreground">"{deleteTarget.name}"</span> and all its
|
|
related products, models, and series?
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<button
|
|
type="button"
|
|
aria-label="Close delete dialog"
|
|
onClick={closeDeleteModal}
|
|
disabled={isDeleting}
|
|
className="w-8 h-8 rounded-full border border-border text-muted-foreground hover:bg-muted cursor-pointer transition-colors flex items-center justify-center shrink-0 disabled:opacity-50"
|
|
>
|
|
<X className="w-4 h-4" />
|
|
</button>
|
|
</div>
|
|
<div className="flex items-center justify-end gap-2 px-5 pb-5 pt-3">
|
|
<button
|
|
type="button"
|
|
onClick={closeDeleteModal}
|
|
disabled={isDeleting}
|
|
className="h-9 px-4 crm-radius-control border border-border bg-card text-[13px] font-medium text-foreground hover:bg-muted cursor-pointer transition-colors disabled:opacity-50"
|
|
>
|
|
Cancel
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={handleConfirmDelete}
|
|
disabled={isDeleting}
|
|
className="h-9 px-4 crm-radius-control bg-destructive hover:bg-destructive/90 text-white text-[13px] font-semibold cursor-pointer transition-colors disabled:opacity-50 inline-flex items-center gap-2"
|
|
>
|
|
{isDeleting ? (
|
|
<>
|
|
<RefreshCw className="w-3.5 h-3.5 animate-spin" />
|
|
Deleting...
|
|
</>
|
|
) : (
|
|
<>
|
|
<Trash2 className="w-3.5 h-3.5" />
|
|
Delete Brand
|
|
</>
|
|
)}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<SlideOver
|
|
open={showBrandModal}
|
|
onClose={closeBrandDrawer}
|
|
title={editingBrand ? 'Edit Brand' : 'Create Brand'}
|
|
icon={<Tag className="w-4 h-4 text-primary shrink-0" />}
|
|
>
|
|
<form onSubmit={handleSubmitBrand} className="flex min-h-0 flex-1 flex-col">
|
|
<div className="flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4">
|
|
<div>
|
|
<label className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">
|
|
Brand Name <span className="text-primary">*</span>
|
|
</label>
|
|
<input
|
|
type="text"
|
|
placeholder="e.g. Samsung, OnePlus"
|
|
value={brandName}
|
|
onChange={(e) => setBrandName(e.target.value)}
|
|
className="w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary transition-colors"
|
|
/>
|
|
</div>
|
|
|
|
<div className="flex items-start gap-3 p-3 bg-muted/30 border border-border crm-radius-card">
|
|
<input
|
|
type="checkbox"
|
|
id="hasMultipleDevices"
|
|
checked={hasMultipleDevices}
|
|
onChange={(e) => {
|
|
setHasMultipleDevices(e.target.checked);
|
|
if (!e.target.checked) setSelectedDeviceTypes([]);
|
|
}}
|
|
className="mt-0.5 rounded border-border text-primary focus:ring-primary cursor-pointer"
|
|
/>
|
|
<label htmlFor="hasMultipleDevices" className="cursor-pointer">
|
|
<span className="block text-[13px] font-semibold text-foreground">Multiple Device Support</span>
|
|
<span className="block text-[12px] text-muted-foreground mt-0.5">
|
|
Enable when this brand supports different device categories.
|
|
</span>
|
|
</label>
|
|
</div>
|
|
|
|
{hasMultipleDevices && (
|
|
<div className="crm-radius-control border border-border bg-muted/20 p-3 space-y-2">
|
|
<label className="block text-[10px] font-semibold text-muted-foreground uppercase">Supported Devices</label>
|
|
<div className="flex flex-wrap items-center gap-4">
|
|
{DEVICE_TYPES.map((dt) => (
|
|
<label key={dt} className="flex items-center gap-2 text-[13px] text-foreground cursor-pointer select-none capitalize">
|
|
<input
|
|
type="checkbox"
|
|
checked={selectedDeviceTypes.includes(dt)}
|
|
onChange={(e) => {
|
|
if (e.target.checked) {
|
|
setSelectedDeviceTypes([...selectedDeviceTypes, dt]);
|
|
} else {
|
|
setSelectedDeviceTypes(selectedDeviceTypes.filter((x) => x !== dt));
|
|
}
|
|
}}
|
|
className="rounded border-border text-primary focus:ring-primary cursor-pointer"
|
|
/>
|
|
{dt}
|
|
</label>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<div>
|
|
<label className="block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5">Brand Logo</label>
|
|
<ImageUpload
|
|
entityType="brand"
|
|
entityId={editingBrand?.brand_id || ''}
|
|
value={brandLogo}
|
|
onUploadSuccess={(url) => setBrandLogo(url)}
|
|
onClear={() => setBrandLogo('')}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="shrink-0 border-t border-border px-5 py-3 flex items-center justify-end gap-2 bg-card">
|
|
<button
|
|
type="button"
|
|
onClick={closeBrandDrawer}
|
|
disabled={isSubmitting}
|
|
className="h-8 px-3.5 bg-card hover:bg-muted border border-border text-foreground crm-radius-control text-[13px] font-medium transition-colors cursor-pointer disabled:opacity-50"
|
|
>
|
|
Cancel
|
|
</button>
|
|
<button
|
|
type="submit"
|
|
disabled={isSubmitting}
|
|
className="h-8 px-3.5 bg-primary hover:bg-primary/90 text-primary-foreground crm-radius-control text-[13px] font-medium transition-colors cursor-pointer disabled:opacity-60"
|
|
>
|
|
{isSubmitting ? 'Saving...' : editingBrand ? 'Save Changes' : 'Create Brand'}
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</SlideOver>
|
|
</div>
|
|
);
|
|
}
|