import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "../lib/api-client";
import { useAuthStore } from "../stores/auth.store";
import type { ComponentProps } from "react";
import type { Ionicons } from "@expo/vector-icons";

type IoniconName = ComponentProps<typeof Ionicons>["name"];

// Icon mapping by category name — DB icon field is not used for rendering
export const CATEGORY_ICONS: Record<string, IoniconName> = {
  "Lebensmittel": "cart-outline",
  "Wohnen": "home-outline",
  "Transport": "car-outline",
  "Gesundheit": "medkit-outline",
  "Freizeit": "game-controller-outline",
  "Kinder": "happy-outline",
  "Urlaub": "airplane-outline",
  "Sonstiges": "ellipsis-horizontal-circle-outline",
  "Gehalt": "briefcase-outline",
  "Sonstiges Einkommen": "cash-outline",
};

const DEFAULT_EXPENSE_ICON: IoniconName = "ellipsis-horizontal-circle-outline";
const DEFAULT_INCOME_ICON: IoniconName = "cash-outline";

export type Category = {
  id: string;
  name: string;
  icon: IoniconName;
  color: string | null;
  type: "income" | "expense";
  isDefault: boolean;
};

type ApiCategory = {
  id: string;
  name: string;
  icon: string | null;
  color: string | null;
  type: "income" | "expense";
  isDefault: boolean;
};

function mapCategory(cat: ApiCategory): Category {
  return {
    ...cat,
    icon:
      CATEGORY_ICONS[cat.name] ??
      (cat.type === "income" ? DEFAULT_INCOME_ICON : DEFAULT_EXPENSE_ICON),
  };
}

export function useCategories() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  return useQuery({
    queryKey: ["categories", activeHouseholdId],
    queryFn: () =>
      apiRequest<{ categories: ApiCategory[] }>("/api/households/categories"),
    select: (data) => data.categories.map(mapCategory),
    enabled: !!activeHouseholdId,
  });
}

export function useCreateCategory() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: { name: string; icon?: string | null; color?: string | null; type: "income" | "expense" }) =>
      apiRequest<{ category: ApiCategory }>("/api/categories", {
        method: "POST",
        body: JSON.stringify(data),
      }).then((r) => mapCategory(r.category)),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["categories", activeHouseholdId] });
    },
  });
}

export function useUpdateCategory() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, ...data }: { id: string; name?: string; icon?: string | null; color?: string | null }) =>
      apiRequest<{ category: ApiCategory }>(`/api/categories/${id}`, {
        method: "PATCH",
        body: JSON.stringify(data),
      }).then((r) => mapCategory(r.category)),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["categories", activeHouseholdId] });
    },
  });
}

export function useDeleteCategory() {
  const activeHouseholdId = useAuthStore((s) => s.activeHouseholdId);
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      apiRequest<{ deleted: boolean }>(`/api/categories/${id}`, { method: "DELETE" }),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["categories", activeHouseholdId] });
    },
  });
}
