"use client";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTranslationStore } from "@/lib/store";
import { API_BASE } from "@/lib/config";
import type { UpdateTierRequest, UpdateTierResponse, PlanType } from "./types";
import { QUERY_KEY, ADMIN_TIMEOUT_MS } from "./useAdminUsers";

async function updateUserTier(
  userId: string,
  plan: PlanType,
  adminToken: string | null | undefined
): Promise<UpdateTierResponse> {
  if (!adminToken) {
    throw new Error("AUTH_REQUIRED");
  }

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), ADMIN_TIMEOUT_MS);

  try {
    const response = await fetch(`${API_BASE}/api/v1/admin/users/${userId}`, {
      method: "PATCH",
      headers: {
        Authorization: `Bearer ${adminToken}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ plan } as UpdateTierRequest),
      signal: controller.signal,
    });

    clearTimeout(timeoutId);

    if (!response.ok) {
      if (response.status === 401) {
        throw new Error("UNAUTHORIZED");
      }
      if (response.status === 404) {
        throw new Error("USER_NOT_FOUND");
      }
      throw new Error(`HTTP_ERROR_${response.status}`);
    }

    return await response.json();
  } catch (err) {
    clearTimeout(timeoutId);
    throw err;
  }
}

export function useUpdateUserTier() {
  const { settings } = useTranslationStore();
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: ({ userId, plan }: { userId: string; plan: PlanType }) =>
      updateUserTier(userId, plan, settings.adminToken),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: QUERY_KEY });
    },
  });

  const getErrorMessage = (err: Error | null): string | null => {
    if (!err) return null;

    const errorMap: Record<string, string> = {
      AUTH_REQUIRED: "Veuillez vous connecter pour effectuer cette action",
      UNAUTHORIZED: "Session expirée. Veuillez vous reconnecter.",
      USER_NOT_FOUND: "Utilisateur non trouvé.",
      HTTP_ERROR_403: "Accès refusé. Droits administrateur requis.",
      HTTP_ERROR_400: "Plan invalide. Veuillez réessayer.",
      HTTP_ERROR_500: "Erreur serveur. Veuillez réessayer plus tard.",
    };

    const code = err.message;
    if (errorMap[code]) {
      return errorMap[code];
    }

    if (err.name === "AbortError") {
      return "Le serveur met trop de temps à répondre. Veuillez réessayer.";
    }

    return "Erreur lors de la mise à jour. Veuillez réessayer.";
  };

  const errorMessage = mutation.error ? getErrorMessage(mutation.error as Error) : null;

  return {
    isUpdating: mutation.isPending,
    result: mutation.data ?? null,
    error: errorMessage,
    updateTier: mutation.mutateAsync,
    reset: mutation.reset,
  };
}
