'use client';

import { useState, useMemo } from 'react';
import {
	useReactTable,
	getCoreRowModel,
	getSortedRowModel,
	getPaginationRowModel,
	getFilteredRowModel,
	ColumnDef,
	SortingState,
	ColumnFiltersState,
	FilterFn,
} from '@tanstack/react-table';
import { rankItem } from '@tanstack/match-sorter-utils';

// Типы данных
type Person = {
	id: number;
	name: string;
	age: number;
	email: string;
	department: string;
	salary: number;
};

// Кастомная функция фильтрации
const fuzzyFilter: FilterFn<Person> = (row, columnId, value, addMeta) => {
	const itemRank = rankItem(row.getValue(columnId), value);
	addMeta({ itemRank });
	return itemRank.passed;
};

// Определяем тип для фильтров
declare module '@tanstack/react-table' {
	interface FilterFns {
		fuzzy: FilterFn<unknown>;
	}
}

export default function DataTable() {
	// Данные
	const [data] = useState<Person[]>([
		{ id: 1, name: 'Иван Петров', age: 28, email: 'ivan@example.com', department: 'IT', salary: 80000 },
		{ id: 2, name: 'Анна Сидорова', age: 32, email: 'anna@example.com', department: 'HR', salary: 65000 },
		{ id: 3, name: 'Сергей Иванов', age: 45, email: 'sergey@example.com', department: 'Финансы', salary: 95000 },
		{ id: 4, name: 'Мария Кузнецова', age: 26, email: 'maria@example.com', department: 'Маркетинг', salary: 60000 },
		{ id: 5, name: 'Алексей Смирнов', age: 38, email: 'alex@example.com', department: 'IT', salary: 85000 },
		{ id: 6, name: 'Ольга Васнецова', age: 29, email: 'olga@example.com', department: 'HR', salary: 62000 },
		{ id: 7, name: 'Дмитрий Орлов', age: 41, email: 'dmitry@example.com', department: 'Финансы', salary: 92000 },
		{ id: 8, name: 'Екатерина Новикова', age: 35, email: 'ekaterina@example.com', department: 'Маркетинг', salary: 70000 },
	]);

	// Состояния
	const [sorting, setSorting] = useState<SortingState>([]);
	const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
	const [globalFilter, setGlobalFilter] = useState('');
	const [rowSelection, setRowSelection] = useState({});

	// Определение колонок
	const columns = useMemo<ColumnDef<Person>[]>(
		() => [
			{
				id: 'select',
				header: ({ table }) => (
					<input
						type="checkbox"
						checked={table.getIsAllPageRowsSelected()}
						onChange={table.getToggleAllPageRowsSelectedHandler()}
					/>
				),
				cell: ({ row }) => (
					<input
						type="checkbox"
						checked={row.getIsSelected()}
						onChange={row.getToggleSelectedHandler()}
					/>
				),
				enableSorting: false,
				enableColumnFilter: false,
			},
			{
				accessorKey: 'id',
				header: 'ID',
				cell: (info) => info.getValue(),
			},
			{
				accessorKey: 'name',
				header: 'Имя',
				cell: (info) => info.getValue(),
				filterFn: fuzzyFilter,
			},
			{
				accessorKey: 'age',
				header: 'Возраст',
				cell: (info) => info.getValue(),
			},
			{
				accessorKey: 'email',
				header: 'Email',
				cell: (info) => info.getValue(),
			},
			{
				accessorKey: 'department',
				header: 'Отдел',
				cell: (info) => info.getValue(),
			},
			{
				accessorKey: 'salary',
				header: 'Зарплата',
				cell: (info) => `$${Number(info.getValue()).toLocaleString()}`,
			},
		],
		[]
	);

	// Создание таблицы
	const table = useReactTable({
		data,
		columns,
		filterFns: {
			fuzzy: fuzzyFilter,
		},
		state: {
			sorting,
			columnFilters,
			globalFilter,
			rowSelection,
		},
		onSortingChange: setSorting,
		onColumnFiltersChange: setColumnFilters,
		onGlobalFilterChange: setGlobalFilter,
		onRowSelectionChange: setRowSelection,
		getCoreRowModel: getCoreRowModel(),
		getSortedRowModel: getSortedRowModel(),
		getPaginationRowModel: getPaginationRowModel(),
		getFilteredRowModel: getFilteredRowModel(),
		globalFilterFn: fuzzyFilter, // Используем саму функцию, а не строку
	});

	return (
		<div className="p-6 max-w-6xl mx-auto">
			<h1 className="text-2xl font-bold mb-6">Таблица сотрудников</h1>

			{/* Глобальный поиск */}
			<div className="mb-4">
				<input
					type="text"
					placeholder="Поиск по всем полям..."
					value={globalFilter}
					onChange={(e) => setGlobalFilter(e.target.value)}
					className="px-4 py-2 border rounded-md w-full max-w-md"
				/>
			</div>

			{/* Фильтры по колонкам */}
			<div className="flex gap-4 mb-4 flex-wrap">
				{table.getAllColumns()
					.filter(column => column.getCanFilter() && column.id !== 'select')
					.map(column => (
						<div key={column.id} className="flex flex-col">
							<label className="text-sm font-medium mb-1">
								{typeof column.columnDef.header === 'string'
									? column.columnDef.header
									: column.id}
							</label>
							{column.id === 'department' ? (
								<select
									value={(column.getFilterValue() as string) || ''}
									onChange={e => column.setFilterValue(e.target.value)}
									className="px-3 py-1 border rounded"
								>
									<option value="">Все отделы</option>
									<option value="IT">IT</option>
									<option value="HR">HR</option>
									<option value="Финансы">Финансы</option>
									<option value="Маркетинг">Маркетинг</option>
								</select>
							) : column.id === 'age' ? (
								<input
									type="number"
									placeholder="Возраст от..."
									value={(column.getFilterValue() as number) || ''}
									onChange={e => column.setFilterValue(e.target.value ? parseInt(e.target.value) : undefined)}
									className="px-3 py-1 border rounded w-32"
								/>
							) : (
								<input
									type="text"
									placeholder={`Фильтр ${column.id}`}
									value={(column.getFilterValue() as string) || ''}
									onChange={e => column.setFilterValue(e.target.value)}
									className="px-3 py-1 border rounded"
								/>
							)}
						</div>
					))}
			</div>

			{/* Таблица */}
			<div className="overflow-x-auto border rounded-lg">
				<table className="min-w-full divide-y divide-gray-200">
					<thead className="bg-gray-50">
						{table.getHeaderGroups().map(headerGroup => (
							<tr key={headerGroup.id}>
								{headerGroup.headers.map(header => (
									<th
										key={header.id}
										className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer"
										onClick={header.column.getToggleSortingHandler()}
									>
										<div className="flex items-center">
											{header.isPlaceholder
												? null
												: typeof header.column.columnDef.header === 'string'
													? header.column.columnDef.header
													: header.column.id}
											{{
												asc: ' 🔼',
												desc: ' 🔽',
											}[header.column.getIsSorted() as string] ?? null}
										</div>
									</th>
								))}
							</tr>
						))}
					</thead>
					<tbody className="bg-white divide-y divide-gray-200">
						{table.getRowModel().rows.map(row => (
							<tr key={row.id} className="hover:bg-gray-50">
								{row.getVisibleCells().map(cell => (
									<td key={cell.id} className="px-6 py-4 whitespace-nowrap">
										{typeof cell.column.columnDef.cell === 'function'
											? cell.column.columnDef.cell(cell.getContext())
											: cell.getValue() as string}
									</td>
								))}
							</tr>
						))}
					</tbody>
				</table>
			</div>

			{/* Пагинация */}
			<div className="flex items-center justify-between mt-4">
				<div className="flex items-center gap-2">
					<button
						className="px-3 py-1 border rounded disabled:opacity-50"
						onClick={() => table.setPageIndex(0)}
						disabled={!table.getCanPreviousPage()}
					>
						⟪
					</button>
					<button
						className="px-3 py-1 border rounded disabled:opacity-50"
						onClick={() => table.previousPage()}
						disabled={!table.getCanPreviousPage()}
					>
						⟨
					</button>
					<button
						className="px-3 py-1 border rounded disabled:opacity-50"
						onClick={() => table.nextPage()}
						disabled={!table.getCanNextPage()}
					>
						⟩
					</button>
					<button
						className="px-3 py-1 border rounded disabled:opacity-50"
						onClick={() => table.setPageIndex(table.getPageCount() - 1)}
						disabled={!table.getCanNextPage()}
					>
						⟫
					</button>
				</div>

				<div className="flex items-center gap-4">
					<span>
						Страница{' '}
						<strong>
							{table.getState().pagination.pageIndex + 1} из {table.getPageCount()}
						</strong>
					</span>
					<select
						value={table.getState().pagination.pageSize}
						onChange={e => table.setPageSize(Number(e.target.value))}
						className="px-2 py-1 border rounded"
					>
						{[5, 10, 20, 30, 40, 50].map(pageSize => (
							<option key={pageSize} value={pageSize}>
								Показать {pageSize}
							</option>
						))}
					</select>
					<span>
						Всего строк: {data.length} | Отфильтровано: {table.getFilteredRowModel().rows.length}
					</span>
				</div>
			</div>
		</div>
	);
}