import React, { useState, useEffect } from 'react';
import { Dialog, Grid, Typography, TextField, Button } from '@material-ui/core';
import { Autocomplete } from '@material-ui/lab';

var cloneDeep = require('lodash/cloneDeep');

export interface SongProperties {
    title: String,
    artistId: Number | undefined,
}

export interface ArtistProperties {
    name: String,
    id: Number,
}

export interface IProps {
    dialogOpen: boolean,
    onClose?: () => void,
    onChangeSongProperties?: (props: SongProperties) => void,
    songProperties: SongProperties,
    onSubmit?: () => void,
    artists: ArtistProperties[],
}

export default function EditSongDialog(props: IProps) {
    const onTitleChange = (title: String) => {
        if (props.onChangeSongProperties) {
            const p = cloneDeep(props.songProperties);
            p.title = title;
            props.onChangeSongProperties(p);
        }
    };
    const onArtistChange = (artist: Number | undefined) => {
        if (props.onChangeSongProperties) {
            const p = cloneDeep(props.songProperties);
            p.artistId = artist;
            props.onChangeSongProperties(p);
        }
    };

    return <Dialog
        open={props.dialogOpen}
        onClose={props.onClose}
    >
        <Typography variant='h6' gutterBottom>
            Song Details
        </Typography>
        <Grid container spacing={3}>
            <Grid item xs={12}>
                <TextField
                    label="Song Title"
                    value={props.songProperties.title}
                    onChange={(i: any) => onTitleChange(i.target.value)}
                    fullWidth
                />
            </Grid>
            <Grid item xs={12}>
                { // TODO: this autocomplete is not controlled but does send updates to the parent
                  // right away. In other words, there is no way to affect its value from outside
                  // the dialog.
                }
                <Autocomplete
                    options={props.artists}
                    getOptionLabel={(option) => option.name as string}
                    onChange={(event, newValue) => {
                        if(newValue) {
                            onArtistChange(newValue.id);
                        } else {
                            onArtistChange(undefined);
                        }
                    }}
                    renderInput={
                        (params) =>
                            <TextField {...params}
                            label="Artist"
                            fullWidth
                            />
                    }
                />
            </Grid>
        </Grid>
        <Button variant="contained" onClick={props.onSubmit}>Submit</Button>
    </Dialog>
}