import React, { FC, useEffect } from 'react';
import { Field } from '@orchard/frontend-react-components';
import { Button, Form } from '@theorchard/suite-components';
import { formatMessage, Page } from '@theorchard/suite-frontend';
import { useForm, SubmitHandler } from 'react-hook-form';
import { useCreateSoundRecordingMutation } from 'src/data/mutations';
import {
    CreateNrSoundRecording_createNrSoundRecording as CreatedSong
} from 'src/data/mutations/soundRecording/__generated__/CreateNrSoundRecording';
import { Song } from 'src/data/queries';
import DataSection from '../dataSection';

export const CLASSNAME = 'BasicMetadata';

interface FormFields {
    isrc: string;
    songName: string;
    label: string;
}

interface Props {
    setSongCreated: React.Dispatch<React.SetStateAction<CreatedSong | undefined>>
    songOption?: Song;
}

const BasicMetadataContent: FC<Props> = ({ setSongCreated, songOption }) => {
    const { createSong, data: songResult } = useCreateSoundRecordingMutation(
        { isrc: '', originalLabel: '', recordingTitle: '' }
    );

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

    const onSubmit: SubmitHandler<FormFields> = data => {
        createSong({
            variables: {
                isrc: data.isrc,
                originalLabel: data.label,
                recordingTitle: data.songName
            }
        });
    };

    useEffect(() => {
        setValue('songName', songOption ? songOption?.name : '');
        setValue('isrc', songOption?.isrc ? songOption.isrc : '');
        setValue('label', songOption?.imprint ?? '');
        if (songResult)
            setSongCreated(songResult);
    }, [setSongCreated, setValue, songOption, songResult]);

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

    return (
        <div className={CLASSNAME} data-testid={CLASSNAME}>
            <Form onSubmit={handleSubmit(onSubmit)} className={`${CLASSNAME}-form`}>
                <Field
                    controlId="songName"
                    labelText={formatMessage('basicMetadata.recordingTitle')}
                    isRequired
                >
                    <Form.Control
                        className={`${CLASSNAME}-song-name-field`}
                        {...register('songName', { required: true })}
                        placeholder={formatMessage('basicMetadata.enterSongName')}
                        type="text"
                    />
                </Field>
                <Field controlId="isrc" labelText={formatMessage('basicMetadata.isrc')}>
                    <Form.Control
                        className={`${CLASSNAME}-isrc-field`}
                        {...register('isrc')}
                        placeholder={formatMessage('basicMetadata.enterIsrc')}
                        type="text"
                    />
                </Field>
                <Field controlId="label" labelText={formatMessage('basicMetadata.label')}>
                    <Form.Control
                        className={`${CLASSNAME}-label-field`}
                        {...register('label')}
                        placeholder={formatMessage('basicMetadata.enterLabel')}
                        type="text"
                    />
                </Field>
                <Button
                    type="next"
                    disabled={isError}
                    className={`${CLASSNAME}-next-button`}
                >
                    {formatMessage('repertoire.next')}
                </Button>
                {isError && (
                    <Page.Col className={`${CLASSNAME}-error-message`}>
                        {formatMessage('basicMetadata.newSongError')}
                    </Page.Col>
                )}
            </Form>
        </div>
    );
};

const BasicMetadata: FC<Props> = ({ setSongCreated, songOption }) => (
    <DataSection
        props={{ setSongCreated, songOption }}
        headerText={formatMessage('basicMetadata.basicMetadata')}
        Content={BasicMetadataContent}
        className="BasicMetadataSection"
    />
);

export default BasicMetadata;
