import type { ReactNode } from "react";
import { createContext, useContext, useState, useEffect } from "react";

// Import z Orval generovaného API
import { 
  apiAccountLoginCreate, 
  apiAccountLogoutCreate 
} from "@/api/generated/public/account";
import { apiAccountUserMeRetrieve } from "@/api/generated/private/account/account";

// Import typů z Orval
import type { CustomTokenObtainPair } from "@/api/generated/public/models/customTokenObtainPair";
import type { CustomUser } from "@/api/generated/private/models/customUser";

interface AuthContextType {
  user: CustomUser | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  login: (payload: CustomTokenObtainPair) => Promise<void>;
  logout: () => Promise<void>;
  refreshUser: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<CustomUser | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  const isAuthenticated = !!user;

  // Načíst uživatele při načtení aplikace (pokud má cookies)
  useEffect(() => {
    refreshUser();
  }, []);

  async function refreshUser() {
    try {
      const userData = await apiAccountUserMeRetrieve();
      setUser(userData);
    } catch (err: any) {
      const errorMessage = err.response?.data?.error || err.message;
      console.error("Failed to refresh user:", errorMessage);
      setUser(null);
    } finally {
      setIsLoading(false);
    }
  }

  async function login(payload: CustomTokenObtainPair) {
    setIsLoading(true);
    try {
      // Login endpoint automaticky nastaví HttpOnly cookies
      await apiAccountLoginCreate(payload);
      
      // Po úspěšném přihlášení načti informace o uživateli
      await refreshUser();
    } catch (err: any) {
      setIsLoading(false);
      const errorMessage = err.response?.data?.error || err.message;
      throw new Error(errorMessage);
    }
  }

  async function logout() {
    try {
      // Zavolej logout endpoint (smaže cookies na backendu)
      await apiAccountLogoutCreate();
    } catch (err: any) {
      console.error("Logout error:", err);
    } finally {
      setUser(null);
    }
  }

  return (
    <AuthContext.Provider value={{ user, isAuthenticated, isLoading, login, logout, refreshUser }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error("useAuth must be used inside AuthProvider");
  return ctx;
}