#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/CSSMathValue.h>
#include <LibWeb/Bindings/CSSNumericValue.h>
#include <LibWeb/Bindings/ExceptionOrUtils.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/CSS/CSSMathValue.h>
#include <LibWeb/WebIDL/Tracing.h>

namespace Web::Bindings {

void CSSMathValueConstructor::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<CSSNumericValuePrototype>(realm, "CSSNumericValue"_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, "CSSMathValue"_utf16), JS::Attribute::Configurable);
    object.define_direct_property(vm.names.prototype, &ensure_web_prototype<CSSMathValuePrototype>(realm, "CSSMathValue"_fly_string), 0);
}

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

void CSSMathValuePrototype::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<CSSNumericValuePrototype>(realm, "CSSNumericValue"_fly_string) });

    auto operator__id = "operator"_utf16_fly_string;
    auto native_operator__getter = JS::NativeFunction::create(realm, operator__getter, 0, operator__id, &realm, "get"sv);
    GC::Ptr<JS::NativeFunction> native_operator__setter;

    // 4. Let configurable be false if attr is unforgeable and true otherwise.
    auto operator__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(operator__id, native_operator__getter, native_operator__setter, operator__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_direct_property(vm.well_known_symbol_to_string_tag(), JS::PrimitiveString::create(vm, "CSSMathValue"_utf16), JS::Attribute::Configurable);
}

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

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

[[maybe_unused]] static JS::ThrowCompletionOr<CSS::CSSMathValue*> 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(CSSMathValuePrototype::operator__getter)
{
    WebIDL::log_trace(vm, "CSSMathValuePrototype::operator__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->operator_(); }));

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

// https://webidl.spec.whatwg.org/#idl-enumeration
JS::ThrowCompletionOr<CSSMathOperator> convert_to_idl_value_for_css_math_operator(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 == "sum"sv)
        return CSSMathOperator::Sum;
    if (value_as_string == "product"sv)
        return CSSMathOperator::Product;
    if (value_as_string == "negate"sv)
        return CSSMathOperator::Negate;
    if (value_as_string == "invert"sv)
        return CSSMathOperator::Invert;
    if (value_as_string == "min"sv)
        return CSSMathOperator::Min;
    if (value_as_string == "max"sv)
        return CSSMathOperator::Max;
    if (value_as_string == "clamp"sv)
        return CSSMathOperator::Clamp;
    return vm.throw_completion<JS::TypeError>(JS::ErrorType::InvalidEnumerationValue, value_as_string, "CSSMathOperator");
}

// https://webidl.spec.whatwg.org/#idl-enumeration
Utf16String idl_enum_to_string(CSSMathOperator 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 CSSMathOperator::Sum:
        return "sum"_utf16;
    case CSSMathOperator::Product:
        return "product"_utf16;
    case CSSMathOperator::Negate:
        return "negate"_utf16;
    case CSSMathOperator::Invert:
        return "invert"_utf16;
    case CSSMathOperator::Min:
        return "min"_utf16;
    case CSSMathOperator::Max:
        return "max"_utf16;
    case CSSMathOperator::Clamp:
        return "clamp"_utf16;
    }
    VERIFY_NOT_REACHED();
}

} // namespace Web::Bindings
