import { useQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
import {
	createColumnHelper,
	flexRender,
	getCoreRowModel,
	getPaginationRowModel,
	getSortedRowModel,
	type SortingState,
	useReactTable,
} from "@tanstack/react-table";
import {
	ArrowDown,
	ArrowUp,
	ChevronDown,
	ChevronRight,
	Mail,
	User,
} from "lucide-react";
import React, { useState } from "react";

import { Button } from "../../../../../components/ui/button";

import {
	Table,
	TableBody,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "../../../../../components/ui/table";
import { getUsers } from "../../../../../lib/querys/admin/getUsers";
import ExpandedRow from "../../-components/users/ExpandedRow";

type User = {
	username: string;
	email: string;
	roles: string | null;
};

export const Route = createFileRoute("/_app/_adminLayout/admin/_users/users")({
	component: RouteComponent,
});

function RouteComponent() {
	const { data, isLoading } = useQuery(getUsers());
	const [sorting, setSorting] = useState<SortingState>([]);
	const columnHelper = createColumnHelper<User>();

	const columns = [
		columnHelper.accessor("username", {
			cell: (i) => i.getValue(),
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">
							<User />
							Username
						</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
		}),

		columnHelper.accessor("email", {
			cell: (i) => i.getValue(),
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">
							<Mail />
							Email
						</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
		}),
		// password reset will do the email flow
		// change password an input for this one so well need inline editing for this dope one
		// trash can to delete user
		// last login -- need to get working on the server side as well.
		columnHelper.accessor("roles", {
			header: () => <span>Roles</span>,
			cell: ({ row }) => {
				return row.getCanExpand() ? (
					<button
						{...{
							onClick: row.getToggleExpandedHandler(),
							style: { cursor: "pointer" },
						}}
					>
						{row.getIsExpanded() ? (
							<span className="flex flex-row gap-2">
								Roles <ChevronDown />
							</span>
						) : (
							<span className="flex flex-row gap-2">
								Roles <ChevronRight />
							</span>
						)}
					</button>
				) : (
					"No expanding"
				);
			},
		}),
	];

	const table = useReactTable({
		data,
		columns,
		getCoreRowModel: getCoreRowModel(),
		getPaginationRowModel: getPaginationRowModel(),
		onSortingChange: setSorting,
		getSortedRowModel: getSortedRowModel(),
		//renderSubComponent: ({ row }: { row: any }) => <ExpandedRow row={row} />,
		getRowCanExpand: () => true,
		state: {
			sorting,
		},
	});

	if (isLoading) {
		return <div className="m-auto">Loading user data</div>;
	}

	// render the roles card and make ts happy by not including it in the useReactTable hook
	const renderSubComponent = ({ row }: { row: any }) => (
		<ExpandedRow row={row} />
	);

	return (
		<div className="p-4">
			<div className="w-1/2">
				<Table>
					<TableHeader>
						{table.getHeaderGroups().map((headerGroup) => (
							<TableRow key={headerGroup.id}>
								{headerGroup.headers.map((header) => {
									return (
										<TableHead key={header.id}>
											{header.isPlaceholder
												? null
												: flexRender(
														header.column.columnDef.header,
														header.getContext(),
													)}
										</TableHead>
									);
								})}
							</TableRow>
						))}
					</TableHeader>
					<TableBody>
						{table.getRowModel().rows.map((row) => (
							<React.Fragment key={row.id}>
								<TableRow
									key={row.id}
									data-state={row.getIsSelected() && "selected"}
								>
									{row.getVisibleCells().map((cell) => (
										<TableCell key={cell.id}>
											{flexRender(
												cell.column.columnDef.cell,
												cell.getContext(),
											)}
										</TableCell>
									))}
								</TableRow>

								{row.getIsExpanded() && (
									<TableRow>
										<TableCell colSpan={row.getVisibleCells().length}>
											{renderSubComponent({ row })}
										</TableCell>
									</TableRow>
								)}
							</React.Fragment>
						))}
					</TableBody>
				</Table>
				<div className="flex items-center justify-end space-x-2 py-4">
					<Button
						variant="outline"
						size="sm"
						onClick={() => table.previousPage()}
						disabled={!table.getCanPreviousPage()}
					>
						Previous
					</Button>
					<Button
						variant="outline"
						size="sm"
						onClick={() => table.nextPage()}
						disabled={!table.getCanNextPage()}
					>
						Next
					</Button>
				</div>
			</div>
		</div>
	);
}
