#include <AK/String.h>
#include <AK/TypeCasts.h>
#include <AK/Variant.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/Promise.h>
#include <LibJS/Runtime/Realm.h>
#include <LibJS/Runtime/VM.h>
#include <LibJS/Runtime/Value.h>
#include <LibJS/Runtime/ValueInlines.h>
#include <LibWeb/Bindings/CSSStyleSheet.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/PlatformObject.h>
#include <LibWeb/Bindings/StyleSheet.h>
#include <LibWeb/CSS/CSSRule.h>
#include <LibWeb/CSS/CSSRuleList.h>
#include <LibWeb/CSS/CSSStyleSheet.h>
#include <LibWeb/CSS/MediaList.h>
#include <LibWeb/WebIDL/AbstractOperations.h>
#include <LibWeb/WebIDL/Promise.h>
#include <LibWeb/WebIDL/Tracing.h>
#include <LibWeb/WebIDL/Types.h>

namespace Web::Bindings {

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

    object.set_prototype(&ensure_web_constructor<StyleSheetPrototype>(realm, "StyleSheet"_fly_string));
    object.define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.name, JS::PrimitiveString::create(vm, "CSSStyleSheet"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<CSSStyleSheetPrototype>(realm, "CSSStyleSheet"_fly_string), 0);
}

JS::ThrowCompletionOr<GC::Ref<JS::Object>> CSSStyleSheetConstructor::construct([[maybe_unused]] InterfaceConstructor& constructor, [[maybe_unused]] JS::FunctionObject& new_target)
{
    WebIDL::log_trace(constructor.vm(), "CSSStyleSheetConstructor::construct");
    auto& vm = constructor.vm();
    [[maybe_unused]] auto& realm = *vm.current_realm();

    // To internally create a new object implementing the interface CSSStyleSheet:

    // 3.2. Let prototype be ? Get(newTarget, "prototype").
    auto prototype = TRY(new_target.get(vm.names.prototype));

    // 3.3. If Type(prototype) is not Object, then:
    if (!prototype.is_object()) {
        // 1. Let targetRealm be ? GetFunctionRealm(newTarget).
        auto* target_realm = TRY(JS::get_function_realm(vm, new_target));

        // 2. Set prototype to the interface prototype object for interface in targetRealm.
        VERIFY(target_realm);
        prototype = &Bindings::ensure_web_prototype<CSSStyleSheetPrototype>(*target_realm, "CSSStyleSheet"_fly_string);
    }

    auto arg0 = vm.argument(0);
    CSSStyleSheetInit options = CSSStyleSheetInit {};
    if (!arg0.is_undefined())
        options = TRY(throw_dom_exception_if_needed(vm, [&] { return convert_to_idl_value_for_css_style_sheet_init(vm, arg0); }));

    auto impl = TRY(throw_dom_exception_if_needed(vm, [&] { return CSS::CSSStyleSheet::construct_impl(realm, options); }));

    // 7. Set instance.[[Prototype]] to prototype.
    VERIFY(prototype.is_object());
    impl->set_prototype(&prototype.as_object());

    // FIXME: Steps 8...11. of the "internally create a new object implementing the interface CSSStyleSheet" algorithm
    // (https://webidl.spec.whatwg.org/#js-platform-objects) are currently not handled, or are handled within CSS::CSSStyleSheet::construct_impl().

    return *impl;
}

void CSSStyleSheetPrototype::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(GC::Ref { ensure_web_prototype<StyleSheetPrototype>(realm, "StyleSheet"_fly_string) });

    auto owner_rule_id = "ownerRule"_utf16_fly_string;
    auto native_owner_rule_getter = JS::NativeFunction::create(realm, owner_rule_getter, 0, owner_rule_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_owner_rule_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto owner_rule_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(owner_rule_id, native_owner_rule_getter, native_owner_rule_setter, owner_rule_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 css_rules_id = "cssRules"_utf16_fly_string;
    auto native_css_rules_getter = JS::NativeFunction::create(realm, css_rules_getter, 0, css_rules_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_css_rules_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto css_rules_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(css_rules_id, native_css_rules_getter, native_css_rules_setter, css_rules_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 rules_id = "rules"_utf16_fly_string;
    auto native_rules_getter = JS::NativeFunction::create(realm, rules_getter, 0, rules_id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_rules_setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto rules_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(rules_id, native_rules_getter, native_rules_setter, rules_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, "insertRule"_utf16_fly_string, insert_rule, 1, default_attributes);

    object.define_native_function(realm, "deleteRule"_utf16_fly_string, delete_rule, 1, default_attributes);

    object.define_native_function(realm, "replace"_utf16_fly_string, replace, 1, default_attributes);

    object.define_native_function(realm, "replaceSync"_utf16_fly_string, replace_sync, 1, default_attributes);

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

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

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

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<CSS::CSSStyleSheet*> 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(CSSStyleSheetPrototype::owner_rule_getter)
{
    WebIDL::log_trace(vm, "CSSStyleSheetPrototype::owner_rule_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->owner_rule(); }));

    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(CSSStyleSheetPrototype::css_rules_getter)
{
    WebIDL::log_trace(vm, "CSSStyleSheetPrototype::css_rules_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->css_rules(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(CSSStyleSheetPrototype::rules_getter)
{
    WebIDL::log_trace(vm, "CSSStyleSheetPrototype::rules_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->css_rules(); }));

    return JS::Value(R);
}

JS_DEFINE_NATIVE_FUNCTION(CSSStyleSheetPrototype::insert_rule)
{
    WebIDL::log_trace(vm, "CSSStyleSheetPrototype::insert_rule");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] CSS::CSSStyleSheet* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "insertRule");

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

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

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->insert_rule(rule, index); }));
    return JS::Value(static_cast<WebIDL::UnsignedLong>(R));
}

JS_DEFINE_NATIVE_FUNCTION(CSSStyleSheetPrototype::delete_rule)
{
    WebIDL::log_trace(vm, "CSSStyleSheetPrototype::delete_rule");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] CSS::CSSStyleSheet* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "deleteRule");

    auto arg0 = vm.argument(0);
    auto index = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg0, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

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

JS_DEFINE_NATIVE_FUNCTION(CSSStyleSheetPrototype::replace)
{
    WebIDL::log_trace(vm, "CSSStyleSheetPrototype::replace");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    auto steps = [&realm, &vm]() -> JS::ThrowCompletionOr<GC::Ref<WebIDL::Promise>> {
        (void)realm;
    [[maybe_unused]] CSS::CSSStyleSheet* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "replace");

    auto arg0 = vm.argument(0);
    auto text = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_usv_string(vm, arg0));
    }(); }));

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

    auto maybe_R = steps();

    // And then, if an exception E was thrown:
    // 1. If op has a return type that is a promise type, then return ! Call(%Promise.reject%, %Promise%, «E»).
    // 2. Otherwise, end these steps and allow the exception to propagate.
    if (maybe_R.is_throw_completion())
        return WebIDL::create_rejected_promise(realm, maybe_R.error_value())->promise();

    return GC::Ref { as<JS::Promise>(*maybe_R.release_value()->promise()) };
}

JS_DEFINE_NATIVE_FUNCTION(CSSStyleSheetPrototype::replace_sync)
{
    WebIDL::log_trace(vm, "CSSStyleSheetPrototype::replace_sync");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] CSS::CSSStyleSheet* idl_object = TRY(impl_from(vm));

    if (vm.argument_count() < 1)
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::BadArgCountOne, "replaceSync");

    auto arg0 = vm.argument(0);
    auto text = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_usv_string(vm, arg0));
    }(); }));

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

JS_DEFINE_NATIVE_FUNCTION(CSSStyleSheetPrototype::add_rule)
{
    WebIDL::log_trace(vm, "CSSStyleSheetPrototype::add_rule");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] CSS::CSSStyleSheet* idl_object = TRY(impl_from(vm));

    auto arg0 = vm.argument(0);
    String selector = "undefined"_string;
    if (!arg0.is_undefined())
        selector = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg0));
    }(); }));

    auto arg1 = vm.argument(1);
    String style = "undefined"_string;
    if (!arg1.is_undefined())
        style = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, arg1));
    }(); }));

    auto arg2 = vm.argument(2);
    Optional<WebIDL::UnsignedLong> index {};
    if (!arg2.is_undefined())
        index = TRY(throw_dom_exception_if_needed(vm, [&] { return WebIDL::convert_to_int<WebIDL::UnsignedLong>(vm, arg2, WebIDL::EnforceRange::No, WebIDL::Clamp::No); }));

    [[maybe_unused]] auto R = TRY(throw_dom_exception_if_needed(vm, [&] { return idl_object->add_rule(selector, style, index); }));
    return JS::Value(static_cast<WebIDL::Long>(R));
}

JS_DEFINE_NATIVE_FUNCTION(CSSStyleSheetPrototype::remove_rule)
{
    WebIDL::log_trace(vm, "CSSStyleSheetPrototype::remove_rule");
    [[maybe_unused]] auto& realm = *vm.current_realm();
    [[maybe_unused]] CSS::CSSStyleSheet* idl_object = TRY(impl_from(vm));

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

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

// https://webidl.spec.whatwg.org/#es-dictionary
JS::ThrowCompletionOr<CSSStyleSheetInit> convert_to_idl_value_for_css_style_sheet_init(JS::VM& vm, JS::Value js_dict)
{
    // 1. If jsDict is not an Object and jsDict is neither undefined nor null, then throw a TypeError.
    if (!js_dict.is_object() && !js_dict.is_nullish())
        return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOfType, "CSSStyleSheetInit");

    // 2. Let idlDict be an empty ordered map, representing a dictionary of type D.
    // 3. Let dictionaries be a list consisting of D and all of D’s inherited dictionaries, in order from least to most derived.
    // 4. For each dictionary dictionary in dictionaries, in order:
    // NB: We defer construction until the return initializer because some members may not be default-constructible. Inherited dictionaries are represented by the generated C++ struct inheritance.

    // 5. Return idlDict.
    return CSSStyleSheetInit {
        .base_url = TRY([&]() -> JS::ThrowCompletionOr<Optional<String>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("baseURL"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Optional<String>> {
        Optional<String> value;

        if (!js_member_value.is_nullish()) {

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

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = OptionalNone {};

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        .disabled = TRY([&]() -> JS::ThrowCompletionOr<bool> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("disabled"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return js_member_value.to_boolean(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = false;

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
        .media = TRY([&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<CSS::MediaList>, String>> {
            // 1. Let key be the identifier of member.
            // 2. If jsDict is either undefined or null, then:
            //     1. Let jsMemberValue be undefined.
            // 3. Otherwise,
            //     1. Let jsMemberValue be ? Get(jsDict, key).
            auto js_member_value = JS::js_undefined();
            if (js_dict.is_object())
                js_member_value = TRY(js_dict.as_object().get("media"_utf16_fly_string));

            // 4. If jsMemberValue is not undefined, then:
            if (!js_member_value.is_undefined()) {
                // 1. Let idlMemberValue be the result of converting jsMemberValue to an IDL value whose type is the type member is declared to be of.
                auto idl_member_value = TRY(throw_dom_exception_if_needed(vm, [&] { return [&]() -> JS::ThrowCompletionOr<Variant<GC::Ref<CSS::MediaList>, String>> {

        if (js_member_value.is_object()) {
            [[maybe_unused]] auto& object = js_member_value.as_object();

            if (is<PlatformObject>(object)) {

                if (auto* result = as_if<CSS::MediaList>(object))
                    return Variant<GC::Ref<CSS::MediaList>, String> { GC::Ref { *result } };
            }
        }

        auto media_string = TRY([&]() -> JS::ThrowCompletionOr<String> {
        return TRY(WebIDL::to_string(vm, js_member_value));
    }());
        return Variant<GC::Ref<CSS::MediaList>, String> { media_string };

        return vm.throw_completion<JS::TypeError>("No union types matched"_utf16);
    }(); }));

                // 2. Set idlDict[key] to idlMemberValue.
                return idl_member_value;
            }
            // 5. Otherwise, if jsMemberValue is undefined but member has a default value, then:
            // 1. Let idlMemberValue be the result of converting member's default value to an IDL value whose type is the type member is declared to be of.
            auto idl_member_value = Variant<GC::Ref<CSS::MediaList>, String> { String {} };

            // 2. Set idlDict[key] to idlMemberValue.
            return idl_member_value;
        }()),
    };
}

} // namespace Web::Bindings
