import React, { Component } from 'react';
import PropTypes from 'prop-types';
import AutocompleteField from '../AutocompleteField';

class DDLMonth extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedValue: props.value || null,
            months: [],
        };
    }

    componentDidMount() {
        this.generateMonthOptions();
        
        // Set default value if enabled and no value provided
        if (this.props.useCurrentMonthAsDefault && !this.props.value) {
            setTimeout(() => this.setDefaultMonth(), 0);
        } else if (this.props.value) {
            setTimeout(() => this.syncValueWithMonths(this.props.value), 0);
        }
    }

    componentDidUpdate(prevProps, prevState) {
        // Update if value prop changes
        if (prevProps.value !== this.props.value) {
            this.syncValueWithMonths(this.props.value);
        }

        // Update if month format or locale changes
        if (prevProps.monthFormat !== this.props.monthFormat ||
            prevProps.locale !== this.props.locale ||
            prevProps.disabledMonths !== this.props.disabledMonths) {
            this.generateMonthOptions();
        }

        // Sync value after months regenerated
        if (prevState.months !== this.state.months) {
            if (this.props.value) {
                this.syncValueWithMonths(this.props.value);
            } else if (this.props.useCurrentMonthAsDefault) {
                this.setDefaultMonth();
            }
        }
    }

    // Set default month (current month)
    setDefaultMonth = () => {
        const { months } = this.state;
        const { onChange, name } = this.props;
        
        if (months.length === 0) return;
        
        const currentMonth = new Date().getMonth() + 1; // 1-12
        const defaultMonth = months.find(m => m.id === currentMonth);
        
        if (defaultMonth) {
            this.setState({ selectedValue: defaultMonth });
            
            // Notify parent component
            if (onChange) {
                onChange(null, defaultMonth, name);
            }
        }
    };

    // Sync value dengan months array untuk dapat referensi yang sama
    syncValueWithMonths = (value) => {
        if (!value) {
            this.setState({ selectedValue: null });
            return;
        }

        const { months } = this.state;

        // Cari objek yang id-nya sama dari months array
        const matchedMonth = months.find(m => m.id === value.id);

        if (matchedMonth) {
            // Set dengan objek dari months array (referensi yang sama)
            this.setState({ selectedValue: matchedMonth });
        } else {
            // Fallback: set value as-is
            this.setState({ selectedValue: value });
        }
    };

    generateMonthOptions = () => {
        const {
            monthFormat = 'short',
            locale = 'en-US',
            startMonth = 1,
            showAllMonths = true,
            filterMonths,
        } = this.props;

        const months = [];
        const date = new Date();

        const totalMonths = showAllMonths ? 12 : (12 - startMonth + 1);

        for (let i = 0; i < totalMonths; i++) {
            const monthNumber = startMonth + i;
            if (monthNumber > 12) break;

            date.setMonth(monthNumber - 1);

            let monthName;
            switch (monthFormat) {
                case 'full':
                    monthName = date.toLocaleString(locale, { month: 'long' });
                    break;
                case 'numeric':
                    monthName = String(monthNumber).padStart(2, '0');
                    break;
                case 'short':
                default:
                    monthName = date.toLocaleString(locale, { month: 'short' });
            }

            months.push({
                id: monthNumber,
                name: monthName,
            });
        }

        const filteredMonths = filterMonths ? months.filter(filterMonths) : months;

        this.setState({ months: filteredMonths });
    };

    handleChange = (event, newValue) => {
        const { onChange, name, onMonthChange } = this.props;

        this.setState({ selectedValue: newValue });

        if (onChange) {
            onChange(event, newValue, name);
        }

        if (onMonthChange) {
            onMonthChange(newValue ? newValue.id : null);
        }
    };

    getMonthName = (monthNumber, format = 'short') => {
        const date = new Date();
        date.setMonth(monthNumber - 1);

        switch (format) {
            case 'full':
                return date.toLocaleString(this.props.locale, { month: 'long' });
            case 'numeric':
                return String(monthNumber).padStart(2, '0');
            default:
                return date.toLocaleString(this.props.locale, { month: 'short' });
        }
    };

    getCurrentMonth = () => {
        return new Date().getMonth() + 1;
    };

    getSelectedMonthValue = () => {
        const { selectedValue } = this.state;
        return selectedValue ? selectedValue.id : null;
    };

    getSelectedMonthName = () => {
        const { selectedValue } = this.state;
        return selectedValue ? selectedValue.name : null;
    };

    render() {
        const {
            label = 'Month',
            placeholder = 'Select month',
            disabled = false,
            required = false,
            error = false,
            helperText,
            style = { width: 250 },
            margin = 'normal',
        } = this.props;

        const { selectedValue, months } = this.state;

        return (
            <AutocompleteField
                options={months}
                value={selectedValue}
                onChange={this.handleChange}
                label={label}
                placeholder={placeholder}
                disabled={disabled}
                required={required}
                error={error}
                helperText={helperText}
                style={style}
                margin={margin}
            />
        );
    }
}

DDLMonth.propTypes = {
    value: PropTypes.object,
    onChange: PropTypes.func,
    onMonthChange: PropTypes.func,
    name: PropTypes.string,
    label: PropTypes.string,
    placeholder: PropTypes.string,
    style: PropTypes.object,
    margin: PropTypes.string,
    disabled: PropTypes.bool,
    required: PropTypes.bool,
    error: PropTypes.bool,
    helperText: PropTypes.string,
    monthFormat: PropTypes.oneOf(['full', 'short', 'numeric']),
    locale: PropTypes.string,
    startMonth: PropTypes.number,
    showAllMonths: PropTypes.bool,
    disabledMonths: PropTypes.arrayOf(PropTypes.number),
    filterMonths: PropTypes.func,
    useCurrentMonthAsDefault: PropTypes.bool, // NEW: Enable default current month
};

DDLMonth.defaultProps = {
    label: 'Month',
    placeholder: 'Select month',
    monthFormat: 'short',
    locale: 'en-US',
    startMonth: 1,
    showAllMonths: true,
    style: { width: 250 },
    useCurrentMonthAsDefault: false, // NEW: Default is false (opt-in)
};

export default DDLMonth;