import React, { FC } from 'react';
import { Field } from '@orchard/frontend-react-components';
import { Button, Form } from '@theorchard/suite-components';
import { formatMessage } from '@theorchard/suite-frontend';
import { useForm, SubmitHandler } from 'react-hook-form';
import { useUpdateSoundRecordingMutation } from 'src/data/mutations';
import DataSection from '../dataSection';

export const CLASSNAME = 'RightsInfo';

interface FormFields {
    recordingYear: string;
}

interface Props {
    songId: string;
}

const RightsInfoContent: FC<Props> = ({ songId }) => {
    const { updateSong } = useUpdateSoundRecordingMutation({ id: '' });

    const {
        register, reset, handleSubmit, formState: { errors }
    } = useForm<FormFields>({ mode: 'onChange' });

    const onSubmit: SubmitHandler<FormFields> = data => {
        updateSong({
            variables: {
                id: songId,
                recordingYear: parseInt(data.recordingYear, 10)
            }
        }).then(() => reset());
    };

    const isError = Object.keys(errors).length > 0;

    return (
        <div className={CLASSNAME} data-testid={CLASSNAME}>
            <Form onSubmit={handleSubmit(onSubmit)} className={`${CLASSNAME}-form`}>
                <Field
                    controlId="recordingYear"
                    labelText={formatMessage('rightsInfo.recordingYear')}
                >
                    <Form.Control
                        className={`${CLASSNAME}-rec-year-field`}
                        {...register('recordingYear', { pattern: /^\d\d\d\d$/ })}
                        placeholder={formatMessage('rightsInfo.enterRecYear')}
                        type="text"
                    />
                </Field>
                <Button
                    type="submit"
                    disabled={isError}
                    className={`${CLASSNAME}-next-button`}
                >
                    {formatMessage('rightsInfo.submit')}
                </Button>
            </Form>
        </div>
    );
};

const RightsInfo: FC<Props> = ({ songId }) => (
    <DataSection
        props={{ songId }}
        headerText={formatMessage('rightsInfo.addRightsInfo')}
        Content={RightsInfoContent}
        className="RightsInfoSection"
    />
);

export default RightsInfo;
