#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/TreeWalker.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/DOM/NodeFilter.h>
#include <LibWeb/DOM/TreeWalker.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

void TreeWalkerConstructor::initialize(JS::Realm& realm, JS::NativeFunction& object)
{
    auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;

    
    object.define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "TreeWalker"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<TreeWalkerPrototype>(realm, "TreeWalker"_fly_string), 0);
}

JS::ThrowCompletionOr<GC::Ref<JS::Object>> TreeWalkerConstructor::construct([[maybe_unused]] InterfaceConstructor& constructor, [[maybe_unused]] JS::FunctionObject& new_target)
{
    WebIDL::log_trace(constructor.vm(), "TreeWalkerConstructor::construct");
    return constructor.vm().throw_completion<JS::TypeError>(JS::ErrorType::NotAConstructor, "TreeWalker");
}

void TreeWalkerPrototype::initialize(JS::Realm& realm, JS::Object& object)
{
    [[maybe_unused]] auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable;

    object.set_prototype(realm.intrinsics().object_prototype());

    auto root_id = "root"_utf16_fly_string;
    auto native_root_getter = JS::NativeFunction::create(realm, root_getter, 0, root_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_root_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto root_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(root_id, native_root_getter, native_root_setter, root_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto what_to_show_id = "whatToShow"_utf16_fly_string;
    auto native_what_to_show_getter = JS::NativeFunction::create(realm, what_to_show_getter, 0, what_to_show_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_what_to_show_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto what_to_show_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(what_to_show_id, native_what_to_show_getter, native_what_to_show_setter, what_to_show_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto filter_id = "filter"_utf16_fly_string;
    auto native_filter_getter = JS::NativeFunction::create(realm, filter_getter, 0, filter_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_filter_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto filter_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(filter_id, native_filter_getter, native_filter_setter, filter_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    auto current_node_id = "currentNode"_utf16_fly_string;
    auto native_current_node_getter = JS::NativeFunction::create(realm, current_node_getter, 0, current_node_id, &realm, "get"sv);
    auto native_current_node_setter = JS::NativeFunction::create(realm, current_node_setter, 1, current_node_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto current_node_attributes = default_attributes;

    // 5. Let desc be the PropertyDescriptor{[[Get]]: getter, [[Set]]: setter, [[Enumerable]]: true, [[Configurable]]: configurable}.

    // 7. Perform ! DefinePropertyOrThrow(target, id, desc).
    object.define_direct_accessor(current_node_id, native_current_node_getter, native_current_node_setter, current_node_attributes);

    // 8. FIXME: If attr’s type is an observable array type with type argument T, then set target’s backing observable array exotic object for attr to the result of creating an observable array exotic object in realm, given T, attr’s set an indexed value algorithm, and attr’s delete an indexed value algorithm.
    object.define_native_function(realm, "parentNode"_utf16_fly_string, parent_node, 0, default_attributes);

    object.define_native_function(realm, "firstChild"_utf16_fly_string, first_child, 0, default_attributes);

    object.define_native_function(realm, "lastChild"_utf16_fly_string, last_child, 0, default_attributes);

    object.define_native_function(realm, "previousSibling"_utf16_fly_string, previous_sibling, 0, default_attributes);

    object.define_native_function(realm, "nextSibling"_utf16_fly_string, next_sibling, 0, default_attributes);

    object.define_native_function(realm, "previousNode"_utf16_fly_string, previous_node, 0, default_attributes);

    object.define_native_function(realm, "nextNode"_utf16_fly_string, next_node, 0, default_attributes);

    object.define_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "TreeWalker"_utf16), JS::Attribute::Configurable);
}

void TreeWalkerPrototype::define_unforgeable_attributes(JS::Realm& realm, [[maybe_unused]] JS::Object& object)
{
    [[maybe_unused]] auto& vm = realm.vm();
    [[maybe_unused]] u8 default_attributes = JS::Attribute::Enumerable;
}

[[maybe_unused]] static JS::ThrowCompletionOr<DOM::TreeWalker*> impl_from(JS::VM& vm, JS::Value js_value)
{

    if (auto impl = js_value.as_if<DOM::TreeWalker>())
        return impl.ptr();
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "TreeWalker");
}

[[maybe_unused]] static JS::ThrowCompletionOr<DOM::TreeWalker*> impl_from(JS::VM& vm)
{
    auto this_value = vm.this_value();
    if (this_value.is_nullish())
        this_value = &vm.current_realm()->global_object();
    return impl_from(vm, this_value);
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::root_getter)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::root_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->root(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::what_to_show_getter)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::what_to_show_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->what_to_show(); }));

    return JS::Value(static_cast<WebIDL::UnsignedLong>(R));
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::filter_getter)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::filter_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->filter(); }));

    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(R->callback().callback);
    }();
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::current_node_getter)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::current_node_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto* idl_object = TRY(impl_from(vm));


    auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->current_node(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::current_node_setter)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::current_node_setter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // 1. Let V be undefined.
    auto V = JS::js_undefined();

    // 2. If any arguments were passed, then set V to the value of the first argument passed.
    if (vm.argument_count() > 0)
        V = vm.argument(0);

    // 3. Let id be attribute’s identifier.

    // 4. Let idlObject be null.
    [[maybe_unused]] DOM::TreeWalker* idl_object = nullptr;

    // 5. If attribute is a regular attribute:

    // 1. Let jsValue be the this value, if it is not null or undefined, or realm’s global object otherwise. (This will subsequently cause a TypeError in a few steps, if the global object does not implement target and [LegacyLenientThis] is not specified.)
    auto js_value = vm.this_value();
    if (js_value.is_nullish())
        js_value = &realm.global_object();

    // 2. FIXME: If jsValue is a platform object, then perform a security check, passing jsValue, attribute’s identifier, and "setter".

    // 3. Let validThis be true if jsValue implements target, or false otherwise.
    auto maybe_idl_object = impl_from(vm, js_value);

    // 4. If validThis is false and attribute was not specified with the [LegacyLenientThis] extended attribute, then throw a TypeError.
    idl_object = TRY(maybe_idl_object);

    auto original_steps = [&]() -> JS::ThrowCompletionOr<JS::Value> {
        // 6. Let idlValue be determined as follows:
        // -> Otherwise, idlValue is the result of converting V to an IDL value of attribute’s type.
        auto idl_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<GC::Ref<DOM::Node>> {
        if (auto impl = V.as_if<DOM::Node>())
            return *impl;
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "Node");
    }(); }));

        // 7. Run the setter steps of attribute with idlObject as this and idlValue as the value.
        auto setter_result = [&]() -> JS::ThrowCompletionOr<void> {
            TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->set_current_node(idl_value); }));
    return {};
        }();

        if (setter_result.is_error())
            return setter_result.release_error();

        return JS::js_undefined();
    };

    // 8. Return undefined.
    return TRY(original_steps());
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::parent_node)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::parent_node");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::TreeWalker* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->parent_node(); }));
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::first_child)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::first_child");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::TreeWalker* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->first_child(); }));
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::last_child)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::last_child");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::TreeWalker* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->last_child(); }));
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::previous_sibling)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::previous_sibling");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::TreeWalker* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->previous_sibling(); }));
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::next_sibling)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::next_sibling");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::TreeWalker* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->next_sibling(); }));
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::previous_node)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::previous_node");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::TreeWalker* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->previous_node(); }));
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

JS_DEFINE_NATIVE_FUNCTION(TreeWalkerPrototype::next_node)
{
    WebIDL::log_trace(vm, "TreeWalkerPrototype::next_node");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] DOM::TreeWalker* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->next_node(); }));
    return [&]() -> JS::Value {
        // 1. If the IDL nullable type T? value is null, then the JavaScript value is null.
        if (!R)
            return JS::js_null();

        // 2. Otherwise, the JavaScript value is the result of converting the IDL nullable type value to the inner IDL type T.
        return JS::Value(JS::Value(R));
    }();
}

} // namespace Web::Bindings
