import { FC } from 'react';
import { observer } from 'mobx-react';
import { ComposibleValidatable, FormState, ValidatableMapOrArray } from 'formstate';

import { Banner } from '@servicetitan/design-system';
import classNames from 'classnames';

export interface FormErrorsListProps<T extends ValidatableMapOrArray = ValidatableMapOrArray> {
    className?: string;
    form: FormState<T>;
}

export const FormErrorsList: FC<FormErrorsListProps> = observer(
    ({ form, className }: FormErrorsListProps) => {
        const getErrors = () => {
            return Object.entries(form.$).map(
                ([key, field]: [key: string, field: ComposibleValidatable<unknown>]) => {
                    return field.hasError ? (
                        <li key={key} className="qa-settings-email-error-list-item">
                            {field.error}
                        </li>
                    ) : null;
                },
            );
        };

        if (!form.hasError) {
            return null;
        }

        return (
            <Banner
                status="critical"
                title="Missing Fields"
                icon
                className={classNames('m-b-2 qa-settings-email-error', className)}
            >
                <p>Please complete all required fields:</p>
                <ul className="qa-settings-email-error-list">{getErrors()}</ul>
            </Banner>
        );
    },
);
