import React, { useState } from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  Modal,
  TouchableHighlight,
  Image,
  FlatList,
  Linking,
} from 'react-native';

import { useHeaderHeight } from '@react-navigation/stack';
import {
  Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import styles from './styles/morestyles'
import liststyles from './styles/liststyles'
import { url } from './resources/fetchInfo.json'
import LinearGradient from 'react-native-linear-gradient';
import StudentWeek from './StudentWeek';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
import Announcements from './Announcements'
import AsyncStorage from '@react-native-community/async-storage'
//import I18n from './i18n';


const getCurrentDate=()=>{
  var date = new Date().getDate();
  var month = new Date().getMonth() + 1;
  var year = new Date().getFullYear();

  return year + ',' + month + ',' + date;
}
const getWeekDate=()=>{
  var date = new Date().getDate()-8;
  var month = new Date().getMonth()+1;
  var year = new Date().getFullYear();

  return year + ',' + month + ',' + date;
}

const STORAGE_KEY = "teacherAnnouncements"
const Stack = createStackNavigator()

const Announcement = ({item}) => {
	const date = new Date
	const dateStr = `${date.getMonth()+1}/${date.getDate()}/${date.getFullYear()}`
	const dateInfo = dateStr===item.item.date&&item.item.time!==undefined?item.item.time:item.item.date;
	return (
		<View style={liststyles.item1}>
			<View style = {{display: 'flex', flexDirection: 'row', justifyContent: 'space-between'}}>
				<View style = {{width: '75%'}}>
					<Text style={liststyles.title3}>{item.item.message}</Text>
				</View>
				<View style = {{display: 'flex', flexDirection: 'row'}}>
					{dateInfo!==undefined?<Text style={{fontSize: 16, alignSelf: 'center'}}>{dateInfo}</Text>:<></>}
				</View>
			</View>
			
		</View>
	)
}

export const TeacherList = ({route}) => {
	return (
		<View style={{}}>
			<FlatList
				data={route.params.data}
				renderItem={item=><Announcement item={item}/>}
				keyExtractor={item=>JSON.stringify(item)}
			/>
		</View>
	)
}

export const whatsNew = ({route}) => {
  const item = route.params
  return (
    <View style={{display:'flex',  paddingHorizontal: '2%', backgroundColor: 'white', height: '100%'}}>
      <View style={{height: '33%'}}>
        <Text style={[liststyles.homeTitle, {marginBottom: '2%'}]}>Today</Text>
        <ScrollView horizontal='true' style={{height: '100%', display: 'flex', flexDirection: 'row', paddingHorizontal: '2%'}}>
          <View style={{display:'flex', flexDirection: 'row'}}>
            <FlatList
            data={item.data}
            renderItem={item=><Today item={item}/>}
            keyExtractor={item=>JSON.stringify(item)}
            horizontal
            />
          </View>
        </ScrollView>
      </View>
      <View style={{height: '33%'}}>
        <Text style={[liststyles.homeTitle, {marginBottom: '2%'}]}>Future</Text>
        <ScrollView horizontal='true' style={{height: '100%', display: 'flex', flexDirection: 'row', paddingHorizontal: '2%'}}>
          <View style={{display:'flex', flexDirection: 'row'}}>
            <FlatList
            data={item.data}
            renderItem={item=><Future item={item}/>}
            keyExtractor={item=>JSON.stringify(item)}
            horizontal
            />
          </View>
        </ScrollView>
      </View>
      <View style={{height: '33%'}}>
        <Text style={[liststyles.homeTitle, {marginBottom: '2%'}]}>Past Week</Text>
        <ScrollView horizontal='true' style={{height: '100%', display: 'flex', flexDirection: 'row', paddingHorizontal: '2%'}}>
          <View style={{display:'flex', flexDirection: 'row'}}>
            <FlatList
            data={item.data}
            renderItem={item=><PastWeek item={item}/>}
            keyExtractor={item=>JSON.stringify(item)}
            horizontal
            />
          </View>
        </ScrollView>
      </View>
    </View>
  )
}

const Today = ({item}) => {
  const newIconURI = item.item.icon !== undefined?`data:image/png;charset=utf-8;base64,${item.item.icon}`:''
  const today = new Date(getCurrentDate())
  const itemDate = new Date(item.item.date)

  if (itemDate.getTime() == today.getTime()) {
    return (
      <View style={{display:'flex', borderWidth:2, borderColor: 'black', borderRadius: 8, width: 120, height: '100%', marginRight: 10}} onPress={()=>setVisible(!visible)} activeOpacity={0.8}>
        <Image source = {{newIconURI}} style = {{height: '76%', width: '100%', borderTopLeftRadius: 8, borderTopRightRadius: 8}}/>
        <View style={{height: '24%', paddingHorizontal: '2%', borderTopWidth: 1}}>
          <Text style={{fontSize: 16}}>{item.item.name}</Text>
          <Text style={{fontSize: 12}}>{item.item.date}</Text>
        </View>
		  </View>
    )
  }
  else {
    return (
      null
    )
  }
}
const Future = ({item}) => {
  const newIconURI = item.item.icon !== undefined?`data:image/png;charset=utf-8;base64,${item.item.icon}`:''
  const today = new Date(getCurrentDate())
  const itemDate = new Date(item.item.date)

  if (itemDate.getTime() > today.getTime()) {
    return (
      <View style={{display:'flex', borderWidth:2, borderColor: 'black', borderRadius: 8, width: 120, height: '100%', marginRight: 10}} onPress={()=>setVisible(!visible)} activeOpacity={0.8}>
        <Image source = {{newIconURI}} style = {{height: '76%', width: '100%', borderTopLeftRadius: 8, borderTopRightRadius: 8}}/>
        <View style={{height: '24%', paddingHorizontal: '2%', borderTopWidth: 1}}>
          <Text style={{fontSize: 16}}>{item.item.name}</Text>
          <Text style={{fontSize: 12}}>{item.item.date}</Text>
        </View>
		  </View>
    )
  }
  else {
    return (
      null
    )
  }
}
const PastWeek = ({item}) => {
  const newIconURI = item.item.icon !== undefined?`data:image/png;charset=utf-8;base64,${item.item.icon}`:''
  const today = new Date(getCurrentDate())
  const week = new Date(getWeekDate())
  const itemDate = new Date(item.item.date)

  if (itemDate.getTime() >= week.getTime() && today.getTime()>itemDate.getTime()) {
    return (
      <View style={{display:'flex', borderWidth:2, borderColor: 'black', borderRadius: 8, width: 120, height: '100%', marginRight: 10}} onPress={()=>setVisible(!visible)} activeOpacity={0.8}>
        <Image source = {{newIconURI}} style = {{height: '76%', width: '100%', borderTopLeftRadius: 8, borderTopRightRadius: 8}}/>
        <View style={{height: '24%', paddingHorizontal: '2%', borderTopWidth: 1}}>
          <Text style={{fontSize: 16}}>{item.item.name}</Text>
          <Text style={{fontSize: 12}}>{item.item.date}</Text>
        </View>
		  </View>
    )
  }
  else {
    return (
      null
    )
  }
}

const AnnouncementToday = ({item}) => {
	const date = new Date
	const dateStr = `${date.getMonth()+1}/${date.getDate()}/${date.getFullYear()}`
  const dateInfo = dateStr===item.item.date&&item.item.time!==undefined?item.item.time:'';
  const itemDate = new Date(item.item.date)
  const today = new Date(getCurrentDate())
  const teacher = item.item.teacher !==""?item.item.teacher:"No Teacher"

  if (itemDate.getTime()===today.getTime()) {
    return (
      <View style = {{display: 'flex', flexDirection: 'row', alignItems: 'center', paddingVertical: '2%', justifyContent: 'space-between', borderBottomWidth: 1, borderTopWidth: 1}}>
        <View style = {{width: '75%'}}>
          <Text style={{fontSize: 18}}>{item.item.message}</Text>
        </View>
        <View style = {{width: '25%', display: 'flex', flexDirection: 'row'}}>
          <Text style={{fontSize: 14, alignSelf: 'center'}}>{teacher}{'\t'}{dateInfo}</Text>
        </View>
      </View>
    )
  }
  else {
    return (
      null
    )
  }
}

const New = ({item}) => {
  const calendarIconURI = item.item.icon !== undefined?`data:image/png;charset=utf-8;base64,${item.item.icon}`:''
  const today = new Date(getCurrentDate())
  const week = new Date(getWeekDate())
  const itemDate = new Date(item.item.date)

  if (itemDate.getTime() >= today.getTime()) {
    return (
      <View style={{display:'flex', borderWidth:2, borderColor: 'black', borderRadius: 8, width: 120, height: '95%', marginRight: 10}} onPress={()=>setVisible(!visible)} activeOpacity={0.8}>
        <Image source = {{calendarIconURI}} style = {{height: '76%', width: '100%', borderTopLeftRadius: 8, borderTopRightRadius: 8, borderTopWidth: 1}}/>
        <View style={{height: '24%', paddingHorizontal: '2%', borderTopWidth: 2}}>
          <Text style={{fontSize: 16}}>{item.item.name}</Text>
          <Text style={{fontSize: 12}}>{item.item.date}</Text>
        </View>
		  </View>
    )
  }
  else if (itemDate.getTime() >= week.getTime()){
    return (
      <View style={{backgroundColor: '#e3e3e', display:'flex', borderWidth:1, borderColor: 'black', borderRadius: 8, width: 120, height: '95%', marginRight: 10}} onPress={()=>setVisible(!visible)} activeOpacity={0.8}>
        <Image source = {{calendarIconURI}} style = {{height: '76%', width: '100%', borderTopLeftRadius: 8, borderTopRightRadius: 8}}/>
        <View style={{height: '24%', paddingHorizontal: '2%', backgroundColor: '#e3e3e3', borderBottomLeftRadius: 8, borderBottomRightRadius: 8, borderTopWidth: 1}}>
          <Text style={{fontSize: 16}}>{item.item.name}</Text>
          <Text style={{fontSize: 12}}>{item.item.date}</Text>
        </View>
    </View>
	  )
  }
  else {
    return (
      null
    )
  }
}

function Home1() {
  const [modalVisible, setModalVisible] = useState(false);

  return (
    <View>
      <View>
        <Modal animationType="slide" transparent={true} visible={modalVisible}>
          <View style={styles.modal}>
            <View style={{display: 'flex', flexDirection:'row', justifyContent: 'flex-end'}}>
              <TouchableHighlight onPress={() => {setModalVisible(false);}}>
                <Image source = {require('./assets/exit.png')} style = {{height: 40, width: 40}}/>
              </TouchableHighlight>
            </View>  
            <View>
              <Image source = {require('./assets/blair_logo.png')} style = {{alignSelf: 'center', marginTop: '5%', height: 325, width: 325}}/>
              <Text style={styles.modalText}>{url}</Text>
            </View>
          </View>
        </Modal>
      </View>
    </View>
  )
}
const background = (<LinearGradient
  colors={['#f99', 'white']}
  style = {{flex:1,borderBottomColor:'black',borderBottomWidth:0.5}}
  />)

function HomeStack() {
  return (
    <NavigationContainer independent={true}>
      <Stack.Navigator>
        <Stack.Screen 
          name="Home"
          component={Home}
          options={{
            title:'Blair',
            headerTitleStyle:styles.headerTitle,
            headerBackground: ()=>background
          }}
        />
        <Stack.Screen 
          name="new"
          component={whatsNew}
          options={({route})=> ({
            title:"What's New",
            headerTitleStyle:styles.headerTitle,
            headerBackground: ()=>background
          })}
        />
        <Stack.Screen 
          name="Announcements"
          component={Announcements}
          options={({route})=> ({
            title:"Announcements",
            headerTitleStyle:styles.headerTitle,
            headerBackground: ()=>background
          })}
        />
        <Stack.Screen 
						name="TeacherList" 
						component={TeacherList}
						options={({route})=>({
							headerTitleStyle:[styles.headerTitle,{alignSelf:'center',fontSize:Math.min(24,24*23/route.params.name.length)}],
							title:route.params.name,
							headerRight:()=>(<></>),
							headerBackground: ()=>background
						})}
					/>
        <Stack.Screen 
          name="Polls"
          component={Home}
          options={{
            title:'Blair',
            headerTitleStyle:styles.headerTitle,
            headerBackground: ()=>background
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  )
}

function HomeScreen (props) {
  const iconURI = props.studentData.icon !== undefined?`data:image/png;charset=utf-8;base64,${props.studentData.icon}`:`data:image/png;base64,[encoded data, 7900 characters]`;
  global.headerHeight = useHeaderHeight();
  return(
    <ScrollView style={{height: '100%', backgroundColor: 'white'}}>
      <View style={{height: 275, backgroundColor: 'white', padding: '2%'}}>
        <View style={{display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: '2%'}}>
          <Text style={liststyles.homeTitle}>Whats New</Text>
          <TouchableOpacity onPress={()=>props.navigation.navigate('new', {data:props.data})}>
            <Text style={{color: 'blue', textDecorationLine: 'underline'}}>View All</Text>
          </TouchableOpacity>
        </View>
        <ScrollView horizontal='true' style={{display: 'flex', flexDirection: 'row', paddingHorizontal: '2%'}}></ScrollView>
          <View style={{display:'flex', flexDirection: 'row', padding: '2%'}}>
            <FlatList
            data={props.data}
            renderItem={item=><New item={item}/>}
            keyExtractor={item=>JSON.stringify(item)}
            horizontal
            />
          </View>
        
      </View>

      <View style={{height: 275, backgroundColor: 'white', padding: '2%'}}>
        <Text style={liststyles.homeTitle}>Student of the Week</Text>
        <View style={{display: 'flex', flexDirection: 'row', paddingTop: '5%', paddingHorizontal: '2%', justifyContent: 'space-between'}}>
          <View style={{display: 'flex', borderWidth: 1, borderColor: 'black', borderRadius: 8, width: '32%', height: '100%'}}>
            <View style={{height:'70%'}}>
              <Image source = {{iconURI}} style = {{height:'100%', width: '100%', borderTopRightRadius: 8, borderTopLeftRadius:8}}/>
            </View>
            <View style ={{paddingHorizontal: '2%', height: '15%', borderTopWidth: 1}}>
              <Text style={{fontWeight: 'bold', fontSize: 18}}>{props.studentData.name}</Text>
              <Text>Grade {props.studentData.year}</Text>
            </View>
          </View>
          <View style={{borderWidth: 1, borderColor: 'black', borderRadius: 8, width: '64%', height: '100%', padding: '2%'}}>
            <Text style={{fontSize: 16}}><Text style={{fontWeight: 'bold'}}>Hobbies: </Text>{props.studentData.hobbies}</Text>
            <Text style={{fontSize: 16}}><Text style={{fontWeight: 'bold'}}>Achievements: </Text>{props.studentData.achievements}</Text>
            <Text style={{fontSize: 16}}><Text style={{fontWeight: 'bold'}}>Messages: </Text>{props.studentData.messages}</Text>
          </View>
        </View>
      </View>

      <View style={{padding: '2%'}}>
        <View style ={{display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: '2%'}}>
          <Text style={liststyles.homeTitle}>Announcements</Text>
          <TouchableOpacity onPress={()=>props.navigation.navigate(Announcements)}>
            <Text style={{color: 'blue', textDecorationLine: 'underline'}}>View All</Text>
          </TouchableOpacity>
        </View>
        <FlatList
          data={props.annData}
          renderItem={item=><AnnouncementToday item={item}/>}
          keyExtractor={item=>JSON.stringify(item)}
        />
      </View>
    </ScrollView>
  )
}
/*function HomeScreen (props) {
  const iconURI = props.studentData.icon !== undefined?`data:image/png;charset=utf-8;base64,${props.studentData.icon}`:`data:image/png;base64,[encoded data, 7900 characters]`;
  global.headerHeight = useHeaderHeight();
  return(
    <ScrollView style={{height: '100%', backgroundColor: 'white'}}>
      <View style={{height: 275, backgroundColor: 'white', padding: '2%'}}>
        <View style={{display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: '2%'}}>
          <Text style={liststyles.homeTitle}>Whats New</Text>
          <TouchableOpacity onPress={()=>props.navigation.navigate('new', {data:props.data})}>
            <Text style={{color: 'blue', textDecorationLine: 'underline'}}>View All</Text>
          </TouchableOpacity>
        </View>
        <ScrollView horizontal='true' style={{display: 'flex', flexDirection: 'row', paddingHorizontal: '2%'}}></ScrollView>
          <View style={{display:'flex', flexDirection: 'row', padding: '2%'}}>
            <FlatList
            data={props.data}
            renderItem={item=><New item={item}/>}
            keyExtractor={item=>JSON.stringify(item)}
            horizontal
            />
          </View>
        
      </View>

      <View style={{height: 275, backgroundColor: 'white', padding: '2%'}}>
        <Text style={liststyles.homeTitle}>Student of the Week</Text>
        <View style={{display: 'flex', flexDirection: 'row', paddingTop: '5%', paddingHorizontal: '2%', justifyContent: 'space-between'}}>
          <View style={{display: 'flex', borderWidth: 1, borderColor: 'black', borderRadius: 8, width: '32%', height: '100%'}}>
            <View style={{height:'70%'}}>
              <Image source = {{iconURI}} style = {{height:'100%', width: '100%', borderTopRightRadius: 8, borderTopLeftRadius:8}}/>
            </View>
            <View style ={{paddingHorizontal: '2%', height: '15%', borderTopWidth: 1}}>
              <Text style={{fontWeight: 'bold', fontSize: 18}}>{props.studentData.name}</Text>
              <Text>Grade {props.studentData.year}</Text>
            </View>
          </View>
          <View style={{borderWidth: 1, borderColor: 'black', borderRadius: 8, width: '64%', height: '100%', padding: '2%'}}>
            <Text style={{fontSize: 16}}><Text style={{fontWeight: 'bold'}}>Hobbies: </Text>{props.studentData.hobbies}</Text>
            <Text style={{fontSize: 16}}><Text style={{fontWeight: 'bold'}}>Achievements: </Text>{props.studentData.achievements}</Text>
            <Text style={{fontSize: 16}}><Text style={{fontWeight: 'bold'}}>Messages: </Text>{props.studentData.messages}</Text>
          </View>
        </View>
      </View>

      <View style={{padding: '2%'}}>
        <View style ={{display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: '2%'}}>
          <Text style={liststyles.homeTitle}>Announcements</Text>
          <TouchableOpacity onPress={()=>props.navigation.navigate(Announcements)}>
            <Text style={{color: 'blue', textDecorationLine: 'underline'}}>View All</Text>
          </TouchableOpacity>
        </View>
        <FlatList
          data={props.annData}
          renderItem={item=><AnnouncementToday item={item}/>}
          keyExtractor={item=>JSON.stringify(item)}
        />
      </View>
      
      <View style={{height: 220, display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between'}}>
        <View style={{display: 'flex', alignItems: 'center', width: '50%'}}>
          <TouchableOpacity onPress={() => Linking.openURL(props.challengeData.link)}>
            <Image source={require('./assets/challenge.png')} style={{height: 200, width: 200}}/>
          </TouchableOpacity>
          
        </View>
        <View style={{display: 'flex', alignItems: 'center', width: '50%'}}>
          <TouchableOpacity onPress={() => Linking.openURL(props.pollData.link)}>
            <Image source={require('./assets/polls.png')} style={{height: 200, width: 200}}/>
          </TouchableOpacity>
        </View>
      </View>

    </ScrollView>
  )
}*/

class Home extends React.Component {
  constructor(props) {
		super(props)
		this.state = {
      studentData: [],
      annData:[],
      data:[],
      pollData:[],
      challengeData:[],
      teacherNames: [],
			favoriteNames: [],
			isLoading:true  
		}
	}
	addFavorite = (name) => {
		const favoriteNames = this.state.favoriteNames.slice().map(({name})=>name)
		const index = favoriteNames.indexOf(name)
		if (index < 0) {
			favoriteNames.push(name)
		}
		else {
			favoriteNames.splice(index,1)
		}
		favoriteNames.sort()
		this.setState({favoriteNames:favoriteNames.map(name=>({name:name}))})
		AsyncStorage.setItem(STORAGE_KEY,JSON.stringify(favoriteNames)).catch(console.log).done()
	}
	componentDidMount() {
    fetch(`${url}/api/en/challenge`,{
		  headers: {
			'Cache-Control': 'no-cache'
		  }}
		).then((response) => {
			return response.text();
		}).then((json) => {
			this.setState({challengeData: JSON.parse(json),isLoading:false});
    }).catch((error) => console.error(error))
    
		fetch(`${url}/api/en/student`,{
		  headers: {
			'Cache-Control': 'no-cache'
		  }}
		).then((response) => {
			return response.text();list 
		}).then((json) => {
			this.setState({studentData: JSON.parse(json),isLoading:false});
    }).catch((error) => console.error(error))
    
    this.getData()
		this.props.navigation.addListener(
			'focus',
			() => {
				this.getData()
			}
    );

    this.getData1()
		AsyncStorage.getItem(STORAGE_KEY)
			.then(value=>value==null?[]:JSON.parse(value).map(x=>({name:x})))
			.then(names=>this.setState({favoriteNames:names}))
			.catch(console.log)
			.done()
  }

  getData() {
		fetch(`${url}/api/en/new`,{
		  headers: {
			'Cache-Control': 'no-cache'
		  } })
		  .then((response) => {
			return response.text();
		  })
		  .then((json) => {
			const data = JSON.parse(json).data
			data.sort((a,b)=>new Date(b.date).getTime()-new Date(a.date).getTime())
			this.setState({data: data});
		  })
		  .catch((error) => console.error(error))
	}

  getData1() {
		fetch(`${url}/api/en/announcements`,{
			headers: {
				'Cache-Control': 'no-cache'
			}
			}
		)
		.then((response) => {
			return response.text()
		})
		.then((txt) => {
			const data = JSON.parse(txt).data;
			const teacherNames = [...new Set(data.filter(x=>x.teacher!=null&&x.teacher.trim()!=='').map(x=>x.teacher))];
			teacherNames.sort()
			this.setState({annData: data, teacherNames: teacherNames.map(x=>({name:x})),isLoading:false});
    })
   
    .catch((error) => console.error(error))
    
	}
  
	render() {
    
    return (
      <View>
        <Home1></Home1>
        <HomeScreen navigation={this.props.navigation} annData={this.state.annData} studentData={this.state.studentData} data={this.state.data} challengeData = {this.state.challengeData}></HomeScreen>
      </View>
		)
	}
}
export default HomeStack;