import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { CreateItem } from "../../shared/types";
import {
	ApiError,
	apiDelete,
	apiGet,
	apiPost,
	apiPut,
	apiUpload,
} from "../lib/api";

interface Item {
	id: number;
	name: string;
	weightGrams: number | null;
	priceCents: number | null;
	quantity: number;
	categoryId: number;
	notes: string | null;
	productUrl: string | null;
	imageFilename: string | null;
	imageSourceUrl: string | null;
	createdAt: string;
	updatedAt: string;
}

interface ItemWithCategory {
	id: number;
	name: string;
	weightGrams: number | null;
	priceCents: number | null;
	quantity: number;
	categoryId: number;
	notes: string | null;
	productUrl: string | null;
	imageFilename: string | null;
	globalItemId: number | null;
	brand: string | null;
	createdAt: string;
	updatedAt: string;
	categoryName: string;
	categoryIcon: string;
}

export function useItems() {
	return useQuery({
		queryKey: ["items"],
		queryFn: () => apiGet<ItemWithCategory[]>("/api/items"),
	});
}

export function useItem(id: number | null) {
	return useQuery({
		queryKey: ["items", id],
		queryFn: () => apiGet<ItemWithCategory>(`/api/items/${id}`),
		enabled: id != null,
		retry: (count, error) =>
			error instanceof ApiError && error.status === 404 ? false : count < 3,
	});
}

export function useCreateItem() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (data: CreateItem) =>
			apiPost<ItemWithCategory>("/api/items", data),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["items"] });
			queryClient.invalidateQueries({ queryKey: ["totals"] });
		},
	});
}

export function useUpdateItem() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: ({ id, ...data }: { id: number } & Partial<CreateItem>) =>
			apiPut<ItemWithCategory>(`/api/items/${id}`, data),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["items"] });
			queryClient.invalidateQueries({ queryKey: ["totals"] });
			queryClient.invalidateQueries({ queryKey: ["setups"] });
		},
	});
}

export function useDeleteItem() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (id: number) =>
			apiDelete<{ success: boolean }>(`/api/items/${id}`),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["items"] });
			queryClient.invalidateQueries({ queryKey: ["totals"] });
			queryClient.invalidateQueries({ queryKey: ["setups"] });
		},
	});
}

export function useDuplicateItem() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (id: number) => apiPost<Item>(`/api/items/${id}/duplicate`, {}),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["items"] });
			queryClient.invalidateQueries({ queryKey: ["totals"] });
		},
	});
}

export function useExportItems() {
	return function exportItems() {
		window.location.href = "/api/items/export";
	};
}

interface ImportResult {
	imported: number;
	createdCategories: string[];
	errors: string[];
}

export function useImportItems() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (file: File) =>
			apiUpload<ImportResult>("/api/items/import", file),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["items"] });
			queryClient.invalidateQueries({ queryKey: ["totals"] });
		},
	});
}
