'use client';
import { useColumnsResolver, useIsMobile } from '@/hooks';
import {
	Table as $Table,
	Switch,
	TableScrollContainer,
	TableTbody,
	TableTd,
	TableTh,
	TableThead,
	TableTr,
} from '@mantine/core';
import {
	flexRender,
	getCoreRowModel,
	useReactTable,
} from '@tanstack/react-table';
import { useTableStore } from '@/store';
import { useTranslations } from 'next-intl';
type Props<T> = {
	data: T[];
	colsSet: ColsSet;
};

export const Table = <T,>({ data, colsSet }: Props<T>) => {
	const columns = useColumnsResolver(colsSet);
	const table = useReactTable({
		columns,
		data,
		getCoreRowModel: getCoreRowModel(),
	});
	const isMobile = useIsMobile();
	const tableStore = useTableStore();
	const t = useTranslations();

	return (
		<>
			<Switch
				className="ms-auto w-max mb-4"
				checked={tableStore.isCards}
				onChange={tableStore.toggle}
				labelPosition="left"
				label={t('common.actions.changeTableViewToCards')}
			/>

			<TableScrollContainer minWidth="100%" className="@container">
				{tableStore.isCards ? (
					<>
						<div className="grid sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4 gap-y-8 gap-x-4">
							{table.getCoreRowModel().rows.map((row) => (
								<$Table key={row.id} withTableBorder>
									<TableTbody>
										{row.getVisibleCells().map((cell) => (
											<TableTr key={cell.id}>
												<TableTh>
													{flexRender(cell.column.columnDef.header, {})}
												</TableTh>
												<TableTd key={cell.id}>
													{flexRender(
														cell.column.columnDef.cell,
														cell.getContext(),
													)}
												</TableTd>
											</TableTr>
										))}
									</TableTbody>
								</$Table>
							))}
						</div>
					</>
				) : (
					<$Table striped className="min-w-max">
						<TableThead>
							{table.getHeaderGroups().map((headerGroup) => (
								<TableTr key={headerGroup.id}>
									{headerGroup.headers.map((header) => (
										<TableTh key={header.id}>
											{header.isPlaceholder
												? null
												: flexRender(
														header.column.columnDef.header,
														header.getContext(),
													)}
										</TableTh>
									))}
								</TableTr>
							))}
						</TableThead>
						<TableTbody>
							{table.getRowModel().rows.map((row) => (
								<TableTr key={row.id}>
									{row.getVisibleCells().map((cell) => (
										<TableTd key={cell.id}>
											{flexRender(
												cell.column.columnDef.cell,
												cell.getContext(),
											)}
										</TableTd>
									))}
								</TableTr>
							))}
						</TableTbody>
					</$Table>
				)}
			</TableScrollContainer>
		</>
	);
};