// resources/js/Components/CustomInput.jsx

import React from 'react';

// Gunakan React.memo untuk mencegah re-render jika props tidak berubah
const CustomInput = React.memo(({ label, name, type = 'text', required = false, children, placeholder, inputProps = {}, data, setData, errors, isNumeric = false }) => {
    
    // Handler perubahan input yang disentralisasi
    const handleChange = (e) => {
        let value = e.target.value;

        // Logika pemfilteran untuk field angka
        if (isNumeric || name.includes('nik') || name.includes('no_hp') || name.includes('no_telepon') || name === 'angkatan') {
             // Hapus semua karakter non-angka
             value = value.replace(/[^0-9]/g, '');
        } 
        
        setData(name, value);
        
        // Panggil custom onChange dari inputProps jika ada
        if (inputProps.onChange) {
            inputProps.onChange(e);
        }
    };

    const finalInputProps = {
        name: name,
        value: data[name] || '', 
        required: required,
        placeholder: placeholder,
        className: "mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 disabled:bg-gray-50",
        ...inputProps,
    };

    // Tentukan handler dan type
    let finalType = type;
    if (isNumeric || name.includes('nik') || name.includes('no_hp') || name.includes('no_telepon') || name === 'angkatan') {
        finalType = 'text'; 
        finalInputProps.onChange = handleChange;
        if (type === 'number' || type === 'tel') {
            finalInputProps.inputMode = 'numeric';
            finalInputProps.pattern = '[0-9]*';
        }
    } else if (type === 'select') {
         // Select tidak perlu filter
         finalInputProps.onChange = (e) => setData(name, e.target.value);
    } else {
        finalInputProps.onChange = handleChange;
    }


    return (
        <div>
            <label className="block text-sm font-medium text-gray-700">
                {label} {required && '(*)'}
            </label>
            {type === 'select' ? (
                <select
                    {...finalInputProps}
                >
                    {children}
                </select>
            ) : type === 'textarea' ? (
                <textarea
                    rows="3"
                    {...finalInputProps}
                ></textarea>
            ) : (
                <input
                    type={finalType}
                    {...finalInputProps}
                />
            )}
            {errors[name] && <span className="text-red-500 text-xs mt-1 block">{errors[name]}</span>}
        </div>
    );
});

export default CustomInput;