#include <AK/String.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/PrimitiveString.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/History.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/HTML/History.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

void HistoryConstructor::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, "History"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<HistoryPrototype>(realm, "History"_fly_string), 0);
}

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

void HistoryPrototype::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 length_id = "length"_utf16_fly_string;
    auto native_length_getter = JS::NativeFunction::create(realm, length_getter, 0, length_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_length_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto length_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(length_id, native_length_getter, native_length_setter, length_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 scroll_restoration_id = "scrollRestoration"_utf16_fly_string;
    auto native_scroll_restoration_getter = JS::NativeFunction::create(realm, scroll_restoration_getter, 0, scroll_restoration_id, &realm, "get"sv);
    auto native_scroll_restoration_setter = JS::NativeFunction::create(realm, scroll_restoration_setter, 1, scroll_restoration_id, &realm, "set"sv);

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto scroll_restoration_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(scroll_restoration_id, native_scroll_restoration_getter, native_scroll_restoration_setter, scroll_restoration_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 state_id = "state"_utf16_fly_string;
    auto native_state_getter = JS::NativeFunction::create(realm, state_getter, 0, state_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_state_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto state_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(state_id, native_state_getter, native_state_setter, state_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, "go"_utf16_fly_string, go, 0, default_attributes);

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

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

    object.define_native_function(realm, "pushState"_utf16_fly_string, push_state, 2, default_attributes);

    object.define_native_function(realm, "replaceState"_utf16_fly_string, replace_state, 2, default_attributes);

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

void HistoryPrototype::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<HTML::History*> impl_from(JS::VM& vm, JS::Value js_value)
{

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

[[maybe_unused]] static JS::ThrowCompletionOr<HTML::History*> 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(HistoryPrototype::length_getter)
{
    WebIDL::log_trace(vm, "HistoryPrototype::length_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->length(); }));

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

JS_DEFINE_NATIVE_FUNCTION(HistoryPrototype::scroll_restoration_getter)
{
    WebIDL::log_trace(vm, "HistoryPrototype::scroll_restoration_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->scroll_restoration(); }));

    return JS::PrimitiveString::create(vm, idl_enum_to_string(R));
}

JS_DEFINE_NATIVE_FUNCTION(HistoryPrototype::state_getter)
{
    WebIDL::log_trace(vm, "HistoryPrototype::state_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->state(); }));

    return R;
}

JS_DEFINE_NATIVE_FUNCTION(HistoryPrototype::scroll_restoration_setter)
{
    WebIDL::log_trace(vm, "HistoryPrototype::scroll_restoration_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]] HTML::History* 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:
        // -> attribute's type is an enumeration
        // 1. Let S be ? ToString(V).
        auto maybe_idl_value = throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_scroll_restoration(vm, V); });

        // 2. If S is not one of the enumeration's values, then return undefined.
        if (maybe_idl_value.is_error())
            return JS::js_undefined();

        // 3. Otherwise, idlValue is the enumeration value equal to S.
        auto idl_value = maybe_idl_value.release_value();

        // 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_scroll_restoration(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(HistoryPrototype::go)
{
    WebIDL::log_trace(vm, "HistoryPrototype::go");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HTML::History* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    WebIDL::Long delta = 0;
    if (!arg0.is_undefined())
        delta = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::Long>(vm, arg0, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->go(delta); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(HistoryPrototype::back)
{
    WebIDL::log_trace(vm, "HistoryPrototype::back");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HTML::History* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->back(); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(HistoryPrototype::forward)
{
    WebIDL::log_trace(vm, "HistoryPrototype::forward");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HTML::History* idl_object = TRY(impl_from(vm));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->forward(); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(HistoryPrototype::push_state)
{
    WebIDL::log_trace(vm, "HistoryPrototype::push_state");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HTML::History* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "pushState", "2");

    auto arg0 = vm.argument(0);
    auto data = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    auto arg1 = vm.argument(1);
    auto unused = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg1));
    }(); }));

    auto arg2 = vm.argument(2);
    Optional<String> url = OptionalNone {};
    if (!arg2.is_undefined())
        url = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Optional<String>> {
        Optional<String> value;

        if (!arg2.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_usv_string(vm, arg2));
    }());
        }
        return value;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->push_state(data, unused, url); }));
    return JS::js_undefined();
}

JS_DEFINE_NATIVE_FUNCTION(HistoryPrototype::replace_state)
{
    WebIDL::log_trace(vm, "HistoryPrototype::replace_state");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] HTML::History* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 2)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountMany, "replaceState", "2");

    auto arg0 = vm.argument(0);
    auto data = TRY(throw_dom_exception_if_needed(vm, [&] { return arg0; }));

    auto arg1 = vm.argument(1);
    auto unused = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg1));
    }(); }));

    auto arg2 = vm.argument(2);
    Optional<String> url = OptionalNone {};
    if (!arg2.is_undefined())
        url = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Optional<String>> {
        Optional<String> value;

        if (!arg2.is_nullish()) {

            value = TRY([&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_usv_string(vm, arg2));
    }());
        }
        return value;
    }(); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->replace_state(data, unused, url); }));
    return JS::js_undefined();
}

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<ScrollRestoration> convert_to_idl_value_for_scroll_restoration(JS::VM& vm, JS::Value value)
{
    // 1. Let S be the result of calling ? ToString(V).
    auto value_as_string = TRY(value.to_utf16_string(vm));

    // 2. If S is not one of E’s enumeration values, then throw a TypeError.
    // 3. Return the enumeration value of type E that is equal to S.
    if (value_as_string == "auto"sv)
        return ScrollRestoration::Auto;
    if (value_as_string == "manual"sv)
        return ScrollRestoration::Manual;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "ScrollRestoration");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(ScrollRestoration value)
{
    // The result of converting an IDL enumeration type value to a JavaScript value is the String value that represents the same sequence of code units as the enumeration value.
    switch (value) {
    case ScrollRestoration::Auto:
        return "auto"_utf16;
    case ScrollRestoration::Manual:
        return "manual"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
