"use client";

import { useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { useTranslationStore } from "@/lib/store";
import { API_BASE } from "@/lib/config";
import type { AdminLoginResponse } from "./types";

const TIMEOUT_MS = 15000;

export function useAdminLogin() {
  const router = useRouter();
  const { setAdminToken } = useTranslationStore();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const login = async (password: string): Promise<void> => {
    setIsLoading(true);
    setError(null);

    try {
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS);

      const response = await fetch(`${API_BASE}/api/v1/admin/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password }),
        signal: controller.signal,
      });

      clearTimeout(timeoutId);

      const contentType = response.headers.get("content-type");
      const isJson = contentType?.includes("application/json");

      if (!response.ok) {
        const message = isJson
          ? (await response.json()).detail || "Mot de passe incorrect"
          : "Erreur de connexion au serveur";
        throw new Error(message);
      }

      const data: AdminLoginResponse = isJson ? await response.json() : {};
      const token = data.access_token;
      if (!token) {
        throw new Error("Réponse invalide du serveur");
      }

      setAdminToken(token);
      router.push("/admin");
    } catch (err: unknown) {
      if (err instanceof Error) {
        if (err.name === "AbortError") {
          setError("Délai de connexion dépassé. Veuillez réessayer.");
        } else {
          setError(err.message);
        }
      } else {
        setError("Erreur de connexion");
      }
    } finally {
      setIsLoading(false);
    }
  };

  const logout = useCallback(async (): Promise<void> => {
    const token = useTranslationStore.getState().settings.adminToken;
    
    if (token) {
      try {
        await fetch(`${API_BASE}/api/v1/admin/logout`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${token}`,
          },
        });
      } catch {
        // Ignore logout errors - proceed with local cleanup
      }
    }
    
    setAdminToken(undefined);
    router.push("/admin/login");
  }, [router, setAdminToken]);

  return { login, logout, isLoading, error };
}
