import React from 'react';
import { Dropdown } from 'primereact/dropdown';
import { Controller } from 'react-hook-form';
import { classNames } from 'primereact/utils';

const CategoryDropdown = ({
    name,
    control,
    rules = {},
    options = [],
    label = "Category",
    placeholder = "Select a category",
    required = false,
    disabled = false,
    showClear = false,
    filter = true,
    filterBy = "parentName,name",
    itemTemplate = null,
    optionDisabled = null,
    className = "w-full",
    errors = {},
    ...props
}) => {
    // Get nested error for the field
    const getNestedError = (errors, fieldPath) => {
        return fieldPath.split('.').reduce((error, key) => {
            return error && error[key] ? error[key] : null;
        }, errors);
    };

    const fieldError = getNestedError(errors, name);

    return (
        <div className="p-float-label">
            <Controller
                name={name}
                control={control}
                rules={{
                    ...(required && { required: `${label} field is required` }),
                    ...rules
                }}
                render={({ field }) => (
                    <>
                        <Dropdown
                            id={field.name}
                            options={options}
                            optionLabel="name"
                            optionValue="id"
                            filter={filter}
                            filterBy={filterBy}
                            showClear={showClear}
                            disabled={disabled}
                            placeholder={placeholder}
                            itemTemplate={itemTemplate}
                            optionDisabled={optionDisabled}
                            className={classNames(className, {
                                'p-invalid': fieldError
                            })}
                            {...field}
                            {...props}
                        />

                        <label htmlFor={field.name}>
                            {label}
                            {required && (
                                <span className="text-red-500 ml-1">*</span>
                            )}
                        </label>
                    </>
                )}
            />
            
            {fieldError && (
                <small className="p-error block mt-1">
                    {fieldError.message || fieldError}
                </small>
            )}
        </div>
    );
};

export default CategoryDropdown;