"use client";
import React, { useEffect, isValidElement, ReactNode, PropsWithChildren } from "react";
import { CheckIcon } from "lucide-react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { CommandItem } from "@/components/ui/command";
import { useSelectContext } from "@/components/ui/field/select/select.context";
import { cn } from "@/lib/utils/cn";

export function extractTextFromReactNode(node: ReactNode): string {
    if(node === null || node === undefined || typeof node === "boolean") {
        return "";
    }

    if(typeof node === "string" || typeof node === "number") {
        return String(node);
    }

    if(Array.isArray(node)) {
        return node.map(extractTextFromReactNode).join("");
    }

    if(isValidElement(node) && node.props) {
        return extractTextFromReactNode((node.props as PropsWithChildren).children);
    }

    return "";
}

export type SelectItemProps = React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>;

export const SelectItem = React.forwardRef<HTMLDivElement, SelectItemProps>((props, ref) => {
    const {
        className,
        children,
        value,
        ...rest
    } = props;

    const {
        multiple,
        selectedValues,
        toggleValue,
        onItemAdded
    } = useSelectContext();

    useEffect(() => {
        onItemAdded(value, children);
    }, [multiple, value, children, onItemAdded]);

    const isSelected = value ? selectedValues.has(value) : false;

    return (
        <CommandItem
          {...rest}
          ref={ref}
          className={
            cn(
                "relative",
                "flex",
                // "data-[disabled]:pointer-events-none",
                // "data-[disabled]:opacity-50",
                // "relative flex w-full cursor-default items-center rounded-sm py-1.5 pr-8 pl-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
                className
            )
          }
          value={extractTextFromReactNode(children)}
          onSelect={() => {
            if(value) {
                toggleValue(value);
            }
          }}>
            <span>{children}</span>

            {isSelected && (
                <span className="absolute right-2 flex size-3.5 items-center justify-center">
                    <CheckIcon className="size-4" />
                </span>
            )}
        </CommandItem>
    );
});

SelectItem.displayName = "SelectItem";
