// react
import React, { HTMLAttributes, useEffect, useRef } from "react";
// third-party
import classNames from "classnames";
// application
import useVehicleForm from "~/services/forms/vehicle";
import { IVehicle } from "~/interfaces/vehicle";

interface Props extends HTMLAttributes<HTMLElement> {
    onVehicleChange?: (event: IVehicle | null) => void;
    onValuesChange?: (values: { marca?: string; modelo?: string }) => void;
}

function VehicleSelect(props: Props) {
    const { onVehicleChange, onValuesChange, className, ...rootProps } = props;
    const rootClasses = classNames("vehicle-select", className);
    const form = useVehicleForm({
        onChange: onVehicleChange,
    });

    const onValuesChangeRef = useRef(onValuesChange);

    useEffect(() => {
        onValuesChangeRef.current = onValuesChange;
    });

    // Exponer los valores seleccionados cuando cambien
    useEffect(() => {
        if (!onValuesChangeRef.current) return;

        const brandItem = form.items.find((item) => item.key === "brand");
        const modelItem = form.items.find((item) => item.key === "model");

        const marca = brandItem && brandItem.value !== "none" ? brandItem.value : undefined;
        const modelo = modelItem && modelItem.value !== "none" ? modelItem.value : undefined;

        onValuesChangeRef.current({ marca, modelo });
    }, [form.items]);

    return (
        <div className={rootClasses} {...rootProps}>
            <div className="vehicle-select__list">
                {form.items.map((item, itemIdx) => {
                    const options = item.options as Array<number | string | IVehicle>;

                    return (
                        <div
                            key={itemIdx}
                            className={classNames("vehicle-select__item", {
                                "vehicle-select__item--loading": item.loading,
                            })}
                        >
                            <select
                                className={classNames("vehicle-select__item-control custom-rounded-select", {
                                    "custom-rounded-select--filled": item.value !== "none",
                                })}
                                aria-label={item.label}
                                name={item.key}
                                value={item.value}
                                disabled={item.disabled}
                                onChange={(e) => form.onItemValueChange(itemIdx, e.target.value)}
                            >
                                <option value="none" disabled>
                                    {itemIdx === 0
                                        ? "Selecciona Marca"
                                        : form.items[0]?.value && form.items[0].value !== "none"
                                          ? "Seleccionar Modelo"
                                          : "Primero selecciona marca"}
                                </option>
                                {options
                                    .filter((option) => option !== null && option !== undefined)
                                    .map((option, optionIdx) => {
                                        const optionValue = form.serializeOption(option, item);
                                        const optionLabel =
                                            typeof option === "object" && option !== null
                                                ? (option as any).name
                                                : option;

                                        // No renderizar opciones con valores vacíos
                                        if (!optionValue) {
                                            return null;
                                        }

                                        return (
                                            <option key={optionIdx} value={optionValue}>
                                                {optionLabel}
                                            </option>
                                        );
                                    })}
                            </select>
                            <div className="vehicle-select__item-loader" />
                        </div>
                    );
                })}
            </div>

            <style jsx>{`
                .vehicle-select__list {
                    gap: 12px; /* Espacio entre selects */
                }

                :global(.custom-rounded-select) {
                    border-radius: 50px !important;
                    padding-left: 20px !important;
                    padding-right: 35px !important;
                    border: 1.5px solid #000 !important;
                    transition: all 0.2s ease-in-out !important;
                    height: 45px !important;
                    background-color: #fff !important;
                    color: #333 !important;
                    cursor: pointer;
                }

                /* Sin selección: siempre blanco, aunque esté deshabilitado */
                :global(.custom-rounded-select:not(.custom-rounded-select--filled)),
                :global(.custom-rounded-select:not(.custom-rounded-select--filled):disabled) {
                    background-color: #fff !important;
                    color: #555 !important;
                    opacity: 1 !important;
                }

                /* Cuando ya seleccionaste una opción: blanco con letras negras */
                :global(.custom-rounded-select--filled) {
                    background-color: #fff !important;
                    color: #000 !important;
                    border-color: #000 !important;
                }
                :global(.custom-rounded-select--filled option) {
                    background-color: #fff;
                    color: #000;
                }

                :global(.custom-rounded-select:focus) {
                    border-color: #000 !important;
                    box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.15) !important;
                    outline: none !important;
                }

                :global(.vehicle-select__item) {
                    flex: 1;
                }
            `}</style>
        </div>
    );
}

export default VehicleSelect;
