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

class DDLCompany extends Component {
    state = {
        companies: [],
        selectedValue: this.props.multiple ? [] : null,
        isLoading: false,
    };

    componentDidMount() {
        this.getCompanyActive();
    }

    componentDidUpdate(prevProps, prevState) {
        // 🔁 value dari parent berubah ATAU companies selesai load
        if (
            prevProps.value !== this.props.value ||
            prevState.companies !== this.state.companies
        ) {
            this.syncValueWithCompanies(this.props.value);
        }
    }

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

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

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

            this.setState({ companies }, () => {
                // ⭐ optional auto select index 0
                if (
                    this.props.autoSelectFirst &&
                    !this.props.value &&
                    companies.length > 0
                ) {
                    this.handleChange(null, this.props.multiple ? [companies[0]] : companies[0]);
                }
            });
        } catch (e) {
            console.error(e);
            this.setState({ companies: [] });
        } finally {
            this.setLoading(false);
        }
    };

    // 🔑 SINKRON VALUE ↔ OPTIONS (INI KUNCI UTAMA)
    syncValueWithCompanies = (value) => {
        const { companies } = this.state;
        const { multiple } = this.props;

        if (!value || companies.length === 0) return;

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

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

    // 🔁 SELALU KIRIM BALIK KE PARENT
    handleChange = (event, newValue) => {
        const { onChange, onCompanyChange, name, multiple } = this.props;

        this.setState({ selectedValue: newValue });

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

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

    render() {
        const {
            label,
            placeholder,
            disabled,
            required,
            error,
            helperText,
            style,
            margin,
            multiple,
        } = this.props;

        const { companies, selectedValue, 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}
                loading={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,
    autoSelectFirst: PropTypes.bool,
};

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

export default DDLCompany;
