import React from 'react'
import AppHeader from './../components/Header';
import { ToastAndroid, ListView, ActivityIndicator, StyleSheet, TouchableOpacity } from 'react-native'
import { Container, Icon, Content, Form, Input, Button, Item, View, Text } from 'native-base'
import { signToken, verifyToken, searchMedication } from './../network/HttpManager'

class SearchMedicineListScreen extends React.Component {

	constructor(props) {
		super(props);
		let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
		this.state = {
			apiKey: "",
			queryString: "",
			isLoading: false,
			dataSource: ds.cloneWithRows([])
		};
	}

	async componentWillMount() {
		let token = await signToken().then(response => {
			console.log(response)
			return response.data["token"]
		})
		this.setState({ apiKey: token })
	}

	render() {

		const { navigation } = this.props;
        const { goBack } = navigation
		const { searchBox, searchInput, listItem, separator } = styles

		if (this.state.isLoading) {
			return (
				<View style={{ flex: 1, paddingTop: 20 }}>
					<ActivityIndicator />
				</View>
			);
		}

		return (
			<Container>
				<AppHeader
					headerLeft={
						<Button onPress={() => goBack()}>
							<Icon name='arrow-back' />
						</Button>
					}
					headerText={"ค้นหาข้อมูลยา"}
				/>
				<View>
					<Form style={searchBox}>
						<Item rounded style={searchInput}>
							<Input
								placeholder="ชื่อยาที่ต้องการค้นหา"
								onChangeText={(text) => this.setState({ queryString: text })}
								value={this.state.queryString}
								returnKeyType="search"
								onEndEditing={() => {
									this._searchMedication()
									ToastAndroid.show(this.state.queryString, ToastAndroid.SHORT)
								}}
							/>
						</Item>
					</Form>
					<ListView
						dataSource={this.state.dataSource}
						renderSeparator={(sectionId, rowId) => <View key={rowId} style={separator} />}
						renderRow={(rowData) =>
							<View style={listItem}>
								<TouchableOpacity onPress={() => this.onPressMedicationItem(rowData)}>
									<View>
										<Text>{rowData.regno}</Text>
										<Text>{rowData.tradenamename}</Text>
										<Text>{rowData.genericname}</Text>
										<Text>{rowData.licenseename}</Text>
										<Text>{rowData.genericnameweight}</Text>
									</View>
								</TouchableOpacity>
							</View>}
						enableEmptySections={true}
					/>
				</View>

			</Container>
		);
	}

	onPressMedicationItem(data) {
		this.props.navigation.navigate("MedicationDetail", {data: data})
	}

	async _searchMedication() {
		this.setState({ isLoading: true })

		let status = await verifyToken(this.state.apiKey).then(response => {
			console.log(response)
			return response.data["statusToken"]
		})

		if (status = "OK") {
			let results = await searchMedication(this.state.apiKey, this.state.queryString).then(response => {
				console.log(response)
				this.setState({ isLoading: false })
				return response.data["results"]
			})
			console.log(results)
			let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
			this.setState({ dataSource: ds.cloneWithRows(results) })
		}

	}

}


const styles = {
	searchBox: {
		backgroundColor: '#4154AF',
		padding: 10
	},
	searchInput: {
		backgroundColor: 'white'
	},
	listItem: {
		backgroundColor: 'white',
		padding: 10
	},
	separator: {
		flex: 1,
		height: StyleSheet.hairlineWidth,
		backgroundColor: '#8E8E8E',
	},
}

export default SearchMedicineListScreen;