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

class DDLCompany extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selectedValue: props.multiple
                ? (props.value || [])
                : (props.value || null),
            companies: [],
            isLoading: false,
        };
    }

    componentDidMount() {
        this.getCompanyActive();
    }

    componentDidUpdate(prevProps, prevState) {
        // Value dikontrol parent
        if (prevProps.value !== this.props.value) {
            this.syncValueWithCompanies(this.props.value);
        }

        // Companies berubah (hasil API)
        if (prevState.companies !== this.state.companies) {
            this.syncValueWithCompanies(this.props.value);
        }
    }

    setLoading = (isLoading) => {
        this.setState({ isLoading });
    }

    getCompanyActive = async () => {
        try {
            this.setLoading(true);
            const response = await api.create().getPerusahaanActive();
            const data = response?.data?.data || [];

            const companies = data.map(item => ({
                id: String(item.company_id),
                name: item.company_name,
            }));

            this.setState({ companies });
        } catch (err) {
            console.error('Failed to load companies', err);
            this.setState({ companies: [] });
        } finally {
            this.setLoading(false);
        }
    };

    // Sinkron value → referensi object dari companies
    syncValueWithCompanies = (value) => {
        const { companies } = this.state;
        const { multiple } = this.props;

        if (!value || companies.length === 0) {
            this.setState({
                selectedValue: multiple ? [] : null,
            });
            return;
        }

        if (multiple) {
            const synced = value
                .map(v =>
                    companies.find(c => String(c.id) === String(v.id))
                )
                .filter(Boolean);

            this.setState({ selectedValue: synced });
        } else {
            const matched = companies.find(
                c => String(c.id) === String(value.id)
            );
            this.setState({ selectedValue: matched || null });
        }
    };

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

        this.setState({ selectedValue: newValue });

        // Standard handler
        if (onChange) {
            onChange(event, newValue, name);
        }

        // Backward compatibility
        if (onCompanyChange) {
            if (multiple) {
                onCompanyChange(newValue.map(v => v.id));
            } else {
                onCompanyChange(newValue ? newValue.id : null);
            }
        }
    };

    getSelectedCompanyValue = () => {
        const { selectedValue } = this.state;
        const { multiple } = this.props;

        return multiple
            ? selectedValue.map(v => v.id)
            : selectedValue?.id || null;
    };

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

        const { selectedValue, companies, isLoading } = this.state;

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

DDLCompany.propTypes = {
    value: PropTypes.oneOfType([
        PropTypes.object,
        PropTypes.array,
    ]),
    onChange: PropTypes.func,
    onCompanyChange: 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,

    multiple: PropTypes.bool,
};

DDLCompany.defaultProps = {
    label: 'Company',
    placeholder: 'Select Company',
    style: { width: 250 },
    multiple: false,
};

export default DDLCompany;
