import { useMutation, useQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
import { createColumnHelper } from "@tanstack/react-table";
import axios from "axios";
import { Activity, ArrowDown, ArrowUp } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@/components/ui/select";

import { getCompanies } from "@/lib/querys/forklifts/getCompanies";
import TableNoExpand from "@/lib/tableStuff/TableNoExpand";
import { cn } from "@/lib/utils";

type Company = {
	id: string;
	name: string;
	active: boolean;
};
export const Route = createFileRoute("/_app/_forklifts/forklifts/companies")({
	component: RouteComponent,
});

const updateCompanyItem = async (
	id: string,
	data: Record<string, string | number | boolean | null>,
) => {
	try {
		const res = await axios.patch(`/lst/api/forklifts/companies/${id}`, data, {
			withCredentials: true,
		});
		toast.success(`Company just updated`);
		return res;
	} catch (err) {
		toast.error("Error in updating company");
		return err;
	}
};

function RouteComponent() {
	const {
		data: companyData = [],
		isLoading,
		refetch,
	} = useQuery(getCompanies());
	const columnHelper = createColumnHelper<Company>();
	const submitting = useRef(false);

	const updateCompany = useMutation({
		mutationFn: ({
			id,
			field,
			value,
		}: {
			id: string;
			field: string;
			value: string | number | boolean | null;
		}) => updateCompanyItem(id, { [field]: value }),

		onSuccess: () => {
			// refetch or update cache
			refetch();
		},
	});
	const columns = [
		columnHelper.accessor("name", {
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">Name</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
			cell: ({ row, getValue }) => {
				const initialValue = String(getValue() ?? "");
				const [localValue, setLocalValue] = useState(initialValue);
				const id = row.original.id;
				const field = "name";

				useEffect(() => setLocalValue(initialValue), [initialValue]);

				const handleSubmit = (newValue: string) => {
					if (newValue !== initialValue) {
						setLocalValue(newValue);
						updateCompany.mutate({ id, field, value: newValue });
					}
				};

				return (
					<Input
						value={localValue}
						onChange={(e) => setLocalValue(e.currentTarget.value)}
						onBlur={(e) => {
							if (!submitting.current) {
								submitting.current = true;
								handleSubmit(e.currentTarget.value.trim());
								setTimeout(() => (submitting.current = false), 100); // reset after slight delay
							}
						}}
						onKeyDown={(e) => {
							if (e.key === "Enter") {
								e.preventDefault();
								submitting.current = true;
								handleSubmit(e.currentTarget.value.trim());
								e.currentTarget.blur(); // will trigger blur, but we ignore it
								setTimeout(() => (submitting.current = false), 100);
							}
						}}
					/>
				);
			},
		}),
		columnHelper.accessor("active", {
			header: ({ column }) => {
				return (
					<Button
						variant="ghost"
						onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
					>
						<span className="flex flex-row gap-2">
							<Activity />
							Active
						</span>
						{column.getIsSorted() === "asc" ? (
							<ArrowUp className="ml-2 h-4 w-4" />
						) : (
							<ArrowDown className="ml-2 h-4 w-4" />
						)}
					</Button>
				);
			},
			cell: ({ row, getValue }) => {
				const active = getValue<boolean>();
				const id = row.original.id;
				const field = "active";

				return (
					<Select
						value={active ? "true" : "false"}
						onValueChange={(value) => {
							const newValue = value === "true";
							updateCompany.mutate({ id, field, value: newValue });
						}}
					>
						<SelectTrigger
							className={cn(
								"w-[100px]",
								active
									? "border-green-500 text-green-600"
									: "border-gray-400 text-gray-500",
							)}
						>
							<SelectValue />
						</SelectTrigger>
						<SelectContent>
							<SelectItem value="true">True</SelectItem>
							<SelectItem value="false">False</SelectItem>
						</SelectContent>
					</Select>
				);
			},
		}),
	];

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