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

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

    componentDidMount() {
        this.generateYearOptions();
        
        // Set default value if enabled and no value provided
        if (this.props.useCurrentYearAsDefault && !this.props.value) {
            setTimeout(() => this.setDefaultYear(), 0);
        } else if (this.props.value) {
            setTimeout(() => this.syncValueWithYears(this.props.value), 0);
        }
    }

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

        // Update if year range props change
        if (prevProps.startYear !== this.props.startYear ||
            prevProps.endYear !== this.props.endYear ||
            prevProps.showDescending !== this.props.showDescending ||
            prevProps.filterYears !== this.props.filterYears) {
            this.generateYearOptions();
        }

        // Sync value after years regenerated
        if (prevState.years !== this.state.years) {
            if (this.props.value) {
                this.syncValueWithYears(this.props.value);
            } else if (this.props.useCurrentYearAsDefault) {
                this.setDefaultYear();
            }
        }
    }

    // Set default year (current year)
    setDefaultYear = () => {
        const { years } = this.state;
        const { onChange, name } = this.props;
        
        if (years.length === 0) return;
        
        const currentYear = new Date().getFullYear();
        const defaultYear = years.find(y => Number(y.id) === currentYear);
        
        if (defaultYear) {
            this.setState({ selectedValue: defaultYear });
            
            // Notify parent component
            if (onChange) {
                onChange(null, defaultYear, name);
            }
        }
    };

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

        const { years } = this.state;

        // Cari objek yang id-nya sama dari years array
        const matchedYear = years.find(y => y.id === value.id || String(y.id) === String(value.id));

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

    generateYearOptions = () => {
        const {
            startYear = 2000,
            endYear,
            showDescending = false,
            filterYears,
        } = this.props;

        const currentYear = new Date().getFullYear();
        const actualEndYear = endYear !== undefined ? endYear : currentYear;

        // Validate year range
        if (startYear > actualEndYear) {
            console.warn(`startYear (${startYear}) cannot be greater than endYear (${actualEndYear})`);
            this.setState({ years: [] });
            return;
        }

        // Generate years array
        let years = [];
        for (let year = startYear; year <= actualEndYear; year++) {
            years.push({
                id: String(year),
                name: String(year),
            });
        }

        // Apply filter if provided
        if (filterYears && typeof filterYears === 'function') {
            years = years.filter(filterYears);
        }

        // Sort based on preference
        years.sort((a, b) => showDescending ? Number(b.id) - Number(a.id) : Number(a.id) - Number(b.id));

        this.setState({ years });
    };

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

        this.setState({ selectedValue: newValue });

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

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

    getCurrentYear = () => {
        return new Date().getFullYear();
    };

    getYearsCount = () => {
        const { years } = this.state;
        return years.length;
    };

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

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

        const { selectedValue, years } = this.state;

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

DDLYear.propTypes = {
    value: PropTypes.object,
    onChange: PropTypes.func,
    onYearChange: 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,
    startYear: PropTypes.number,
    endYear: PropTypes.number,
    showDescending: PropTypes.bool,
    filterYears: PropTypes.func,
    useCurrentYearAsDefault: PropTypes.bool, // NEW: Enable default current year
};

DDLYear.defaultProps = {
    label: 'Year',
    placeholder: 'Select year',
    startYear: 2000,
    showDescending: false,
    style: { width: 250 },
    useCurrentYearAsDefault: false, // NEW: Default is false (opt-in)
};

export default DDLYear;