import React, { type ChangeEventHandler, useContext, useEffect } from 'react';
import { Col, Label, Row } from '@theorchard/suite-components';
import LabelSearchableSelect from 'src/components/shared/label-searchable-select';
import {
    SET_DEFAULT_CONDITION,
    SET_CONTRACT_TERM_ATTACHMENTS,
} from 'src/constants';
import { ContractTermContext } from 'src/contexts/contract-term-context';
import { ContractTermConditionsList } from './contract-term-conditions-list';

const LabelBaseTermsForm = () => {
    const { state, dispatch } = useContext(ContractTermContext);

    const formChangeHandler: ChangeEventHandler<HTMLInputElement> = e => {
        const {
            target: { value },
        } = e;
        const attachments = value || [];
        dispatch({ type: SET_CONTRACT_TERM_ATTACHMENTS, attachments });
    };

    useEffect(() => {
        if (state.attachments.length > 0 && state.conditions.length === 0)
            dispatch({ type: SET_DEFAULT_CONDITION });
    }, [state.attachments]);

    return (
        <div className="ContractLabelTermsForm-block">
            <Row className="BaseRateHorizontalRow">
                <Col sm={2}>
                    <Label text="Label" />
                </Col>
                <Col sm={5}>
                    <LabelSearchableSelect
                        onChange={formChangeHandler}
                        vendorCatalogIds={state.attachments}
                    />
                </Col>
            </Row>
            {(state.attachments.length > 0 || state.conditions.length > 0) && (
                <ContractTermConditionsList />
            )}
        </div>
    );
};

export default LabelBaseTermsForm;
