import React, { Component } from 'react';
import _ from 'lodash';
import { View, ViewPropTypes, StyleSheet, FlatList } from 'react-native';
import { TableCellPlaylist, TableCell, Switch, color } from 'nixplay-ui-kit';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { UPDATE_FRAME_PLAYLIST_ASSIGNMENT } from '~/store/actionTypes';
import { analytics } from '~/lib/utils';
import PlaylistTypeLabel from '~comp/playlistTypeLabel';

const styles = StyleSheet.create({
	container: {
		backgroundColor: color.white,
	},
	playlist: {
		paddingLeft: 16,
	},
	label: {
		left: 5,
	},
});

export class AssignPlaylistToFrame extends Component {
	static propTypes = {
		...ViewPropTypes,
		allPlaylists: PropTypes.array.isRequired,
		allPlaylistsLoading: PropTypes.bool.isRequired,
		frameId: PropTypes.number,
		framePlaylists: PropTypes.array,
		updateFrame: PropTypes.func.isRequired,
		onPlaylistsChange: PropTypes.func,
		isConnected: PropTypes.bool.isRequired,
	}

	static defaultProps = {
		onPlaylistsChange: () => { },
		frameId: -1,
		framePlaylists: [],
	}

	constructor(props) {
		super(props);

		this.state = {
			playlistsSwitch: {},
		};

		this.onTogglePlaylist = this.onTogglePlaylist.bind(this);
	}

	componentWillMount() {
		this.setInitialValues();
	}

	onTogglePlaylist(playlistId, value) {
		this.setState({
			playlistsSwitch: {
				...this.state.playlistsSwitch,
				[playlistId]: value,
			},
		}, () => {
			const playlistIds = _.filter(
				_.keys(this.state.playlistsSwitch),
				(k) => this.state.playlistsSwitch[k] === true,
			);
			this.props.onPlaylistsChange(_.map(playlistIds, _.parseInt), playlistId, value);
			if (this.props.frameId !== -1) {
				this.props.updateFrame(this.props.frameId, playlistId, value ? 'add' : 'remove');
				if (value) {
					analytics.logAction('add_playlist_to_frame');
				} else {
					analytics.logAction('remove_playlist_from_frame');
				}
			}
		});
	}

	setInitialValues() {
		const values = {};
		this.props.framePlaylists.forEach((f) => {
			values[f.id] = true;
		});
		this.setState({ playlistsSwitch: values });
	}

	render() {
		const {
			style,
			allPlaylists,
			allPlaylistsLoading,
			...others
		} = this.props;
		return (
			<View style={[styles.container, style]}>
				<FlatList
					{...others}
					data={allPlaylists}
					keyExtractor={(playlist) => `${playlist.id}`}
					loading={allPlaylistsLoading}
					renderItem={({ item: playlist, index }) => (
						<TableCellPlaylist
							playlist={playlist}
							style={styles.playlist}
							dynamicPlaylistLabel={() => _.isEqual(playlist.type, 'google') &&
								(<PlaylistTypeLabel type="googlePhotosAssign" containerStyle={styles.label} />)
							}
							showFrameCount
						>
							<TableCell.Actions>
								<Switch
									name={`frame.assign.playlist${index}`}
									testID={`FrameAssignPlaylist${index}`}
									value={this.state.playlistsSwitch[playlist.id]}
									onValueChange={(v) => { this.onTogglePlaylist(playlist.id, v); }}
									withEye
									disabled={!this.props.isConnected}
								/>
							</TableCell.Actions>
						</TableCellPlaylist>
					)}
				/>
			</View>
		);
	}
}

const mapStateToProps = (state) => ({
	allPlaylists: [...state.playlists.playlists].sort((a, b) => b.id - a.id),
	allPlaylistsLoading: state.playlists.meta.loading,
	isConnected: state.network.isConnected,
});

const mapActionsToProps = (dispatch) => ({
	updateFrame(frameId, playlistId, operation) {
		dispatch({
			type: UPDATE_FRAME_PLAYLIST_ASSIGNMENT,
			payload: {
				frameIds: [frameId],
				playlistIds: [playlistId],
				operation,
			},
		});
	},
});

export default connect(
	mapStateToProps,
	mapActionsToProps,
	null,
	{ forwardRef: true },
)(AssignPlaylistToFrame);
