#include <AK/TypeCasts.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Promise.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/ViewTransition.h>
#include <LibWeb/ViewTransition/ViewTransition.h>
#include <LibWeb/WebIDL/Promise.h>
#include <LibWeb/WebIDL/Tracing.h>

namespace Web::Bindings {

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

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

void ViewTransitionPrototype::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 update_callback_done_id = "updateCallbackDone"_utf16_fly_string;
    auto native_update_callback_done_getter = JS::NativeFunction::create(realm, update_callback_done_getter, 0, update_callback_done_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_update_callback_done_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto update_callback_done_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(update_callback_done_id, native_update_callback_done_getter, native_update_callback_done_setter, update_callback_done_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 ready_id = "ready"_utf16_fly_string;
    auto native_ready_getter = JS::NativeFunction::create(realm, ready_getter, 0, ready_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_ready_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto ready_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(ready_id, native_ready_getter, native_ready_setter, ready_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 finished_id = "finished"_utf16_fly_string;
    auto native_finished_getter = JS::NativeFunction::create(realm, finished_getter, 0, finished_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_finished_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto finished_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(finished_id, native_finished_getter, native_finished_setter, finished_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, "skipTransition"_utf16_fly_string, skip_transition, 0, default_attributes);

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<ViewTransition::ViewTransition*> 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(ViewTransitionPrototype::update_callback_done_getter)
{
    WebIDL::log_trace(vm, "ViewTransitionPrototype::update_callback_done_getter");
    [[maybe_unused]] auto& realm = *vm.current_realm();

    auto steps = [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::Promise>> {
        // 1. Let idlObject be null.
        [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));
        auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->update_callback_done(); }));
        return R;
    };

    auto maybe_R = steps();

    // 2. And then, if an exception E was thrown:

    // 1. If attribute’s type is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).
    if (maybe_R.is_throw_completion())
        return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();

    // 2. Otherwise, end these steps and allow the exception to propagate.
    auto R = maybe_R.release_value();

    // 4. Return the result of converting R to a JavaScript value of the type attribute is declared as.
    return GC::Ref { as<JS::Promise>(*R->promise()) };
}

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

    auto steps = [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::Promise>> {
        // 1. Let idlObject be null.
        [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));
        auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->ready(); }));
        return R;
    };

    auto maybe_R = steps();

    // 2. And then, if an exception E was thrown:

    // 1. If attribute’s type is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).
    if (maybe_R.is_throw_completion())
        return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();

    // 2. Otherwise, end these steps and allow the exception to propagate.
    auto R = maybe_R.release_value();

    // 4. Return the result of converting R to a JavaScript value of the type attribute is declared as.
    return GC::Ref { as<JS::Promise>(*R->promise()) };
}

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

    auto steps = [&]() -> JS::ThrowCompletionOr<GC::Ptr<WebIDL::Promise>> {
        // 1. Let idlObject be null.
        [[maybe_unused]] auto* idl_object = TRY(impl_from(vm));
        auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->finished(); }));
        return R;
    };

    auto maybe_R = steps();

    // 2. And then, if an exception E was thrown:

    // 1. If attribute’s type is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).
    if (maybe_R.is_throw_completion())
        return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();

    // 2. Otherwise, end these steps and allow the exception to propagate.
    auto R = maybe_R.release_value();

    // 4. Return the result of converting R to a JavaScript value of the type attribute is declared as.
    return GC::Ref { as<JS::Promise>(*R->promise()) };
}

JS_DEFINE_NATIVE_FUNCTION(ViewTransitionPrototype::skip_transition)
{
    WebIDL::log_trace(vm, "ViewTransitionPrototype::skip_transition");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] ViewTransition::ViewTransition* idl_object = TRY(impl_from(vm));

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

} // namespace Web::Bindings
