import { SyntheticEvent, Fragment, useCallback, FC } from 'react';
import { observer } from 'mobx-react';

import { Form, LayoutProps, Text } from '@servicetitan/design-system';
import { InputFieldState } from '@servicetitan/form';
import { SettingsSection } from '../settings-section';

export interface CompanyEmailSender {
    senderName: InputFieldState<string | undefined>;
    senderEmail: InputFieldState<string | undefined>;
    layout?: LayoutProps['type'];
    className?: string;
}

export const CompanyEmailSender: FC<CompanyEmailSender> = observer(
    ({ senderName, senderEmail, layout, className }) => {
        const handleSenderNameChange = useCallback(
            (_0: SyntheticEvent<HTMLInputElement, Event>, data: { value: string }) => {
                if (data.value.length > 80) {
                    return;
                }

                senderName.onChange(data.value);
            },
            [senderName],
        );

        const handleSenderEmailBlur = useCallback(() => {
            senderEmail.validate();
        }, [senderEmail]);

        return (
            <SettingsSection
                layout={layout}
                className={className}
                title="Sender"
                text="Configure sender name and email."
                qaPrefix="qa-settings-sender"
            >
                <Form className="m-b-0-i">
                    <Form.Group widths="equal" className="m-b-0-i">
                        <Form.Input
                            width={6}
                            className="m-b-0-i qa-settings-sender-name"
                            value={senderName.value}
                            onChange={handleSenderNameChange}
                            error={senderName.hasError}
                            label={
                                <Fragment>
                                    Sender Name &nbsp;&nbsp;
                                    <Text inline size={2} subdued>
                                        max 80 characters
                                    </Text>
                                </Fragment>
                            }
                            placeholder="John Doe"
                            fluid
                        />
                        <Form.Input
                            width={6}
                            className="m-b-0-i qa-settings-sender-email"
                            value={senderEmail.value}
                            onChange={senderEmail.onChangeHandler}
                            error={senderEmail.hasError}
                            onBlur={handleSenderEmailBlur}
                            label="Sender Email"
                            placeholder="name@company.com"
                            fluid
                        />
                    </Form.Group>
                </Form>
            </SettingsSection>
        );
    },
);
