import React, { useState } from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  Modal,
  TouchableHighlight,
  Image,
  FlatList,
  Dimensions,
  Linking,
  ImageBackground
} 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 LunchEvents from './LunchEvents'
import { TouchableOpacity } from 'react-native-gesture-handler';
import { NavigationContainer } from '@react-navigation/native'
import { createStackNavigator } from '@react-navigation/stack'
import Announcements from './Announcements'
import I18n from './i18n.js'
import AsyncStorage from '@react-native-async-storage/async-storage'

const STORAGE_KEY = "teacherAnnouncements"
const Stack = createStackNavigator()
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;

console.log(String(I18n.locale).split('-')[0])

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

	return new Date(year, month, date);
}

const Announcement = ({item}) => {
	const todayDate = getCurrentDate()
	const itemDate = new Date(item.item.date)
	const dateInfo = todayDate.getTime()===itemDate.getTime()&&item.item.time!==undefined?item.item.time:(item.item.date+", " + item.item.time)
	return (
		<View style={{borderWidth: 1, borderColor: '#323232', padding: '2%', marginHorizontal: '2%', marginBottom: '2%', borderRadius: 12}}>
			<View style = {{display: 'flex', flexDirection: 'column', justifyContent: 'space-between'}}>
				<View style = {{width: '100%'}}>
					<Text style={liststyles.title}>{item.item.message}</Text>
				</View>
				{dateInfo!==undefined?<Text style={{fontSize: 12, fontWeight: '200'}}>{dateInfo}</Text>:<></>}
			</View>
		</View>
	)
}

function NewTeacherList(props) {
  return (
    <View>
      <LinearGradient start={{x: 0.25, y: .5}} end={{x: 1, y: 1}} colors={['#FF8484', '#FF1111']} style={{backgroundColor: 'red', width: '20%', padding: '2%', borderTopRightRadius: 20, borderBottomRightRadius: 20, marginVertical: '2%'}}>
        <Text style={[liststyles.title, {color: 'white', fontWeight: 'bold'}]}>{I18n.t('dates.'+props.name)}</Text>
      </LinearGradient>
      <FlatList
        data={props.list}
        renderItem={item=><Announcement item={item}/>} 
        keyExtractor={item=>JSON.stringify(item)}
      />
    </View>
  )
}

export const TeacherList = ({route}) => {
  const todayDate = getCurrentDate()
	const weekPastDate = new Date();
	var pastDate = weekPastDate.getDate() - 7;
	weekPastDate.setDate(pastDate);
	const weekFutureDate = new Date();
	var futureDate = weekFutureDate.getDate() + 7;
	weekFutureDate.setDate(futureDate);
	const today = []
	const past = []
	const future = []
	var todayBoolean = true
	var pastBoolean = true
	var futureBoolean = true
	
	for (var i = 0; i < route.params.data.length; i++) {
		const itemDate = new Date(route.params.data[i].date)
		if (itemDate.getTime() == todayDate.getTime()) {
			today.push(route.params.data[i])
		}
		else if (itemDate.getTime() > todayDate.getTime() && itemDate.getTime() <= weekFutureDate.getTime()) {
			future.push(route.params.data[i])
		}
		//else if (itemDate >= weekPastDate && itemDate < todayDate) {
		else if (itemDate.getTime() < todayDate.getTime()) {
			past.push(route.params.data[i])
		}
	}
	if (today.length === 0) todayBoolean = false
	if (past.length === 0) pastBoolean = false
	if (future.length === 0) futureBoolean = false
	var noAnn = (todayBoolean||pastBoolean||futureBoolean)

	return (
		<ScrollView style={{flex: 1, backgroundColor: 'white'}}>
			{todayBoolean?<NewTeacherList name = 'today' list = {today} />:<></>}
			{pastBoolean?<NewTeacherList name = 'past' list = {past} />:<></>}
			{futureBoolean?<NewTeacherList name = 'future' list = {future} />:<></>}
			{!noAnn?<Text style={{textAlign: 'center', fontSize: 20, paddingTop: '2%'}}>{I18n.t('home.noAnnouncements')}</Text>:<></>}
		</ScrollView>
	)
}

function NewElement(props) {
  var name = props.name
  return (
    <View style={{}}>
      <LinearGradient start={{x: 0.25, y: .5}} end={{x: 1, y: 1}} colors={['#FF8484', '#FF1111']} style={{backgroundColor: 'red', width: '20%', padding: '2%', borderTopRightRadius: 20, borderBottomRightRadius: 20, marginVertical: '2%'}}>
        <Text style={[liststyles.title, {color: 'white', fontWeight: 'bold'}]}>{I18n.t('dates.'+props.name)}</Text>
      </LinearGradient>
      <View style={{display:'flex', flexDirection: 'row', paddingHorizontal: '5%'}}>
        <FlatList
        data={props.list}
        renderItem={item=><New item={item} navigation={props.navigation}/>}
        keyExtractor={item=>JSON.stringify(item)}
        horizontal
        />
      </View>
    </View>
  )
}

export const whatsNew = ({route}) => {
  const todayDate = getCurrentDate()
	const weekPastDate = new Date();
	var pastDate = weekPastDate.getDate() - 7;
	weekPastDate.setDate(pastDate);
	const weekFutureDate = new Date();
	var futureDate = weekFutureDate.getDate() + 7;
	weekFutureDate.setDate(futureDate);
	const today = []
	const past = []
	const future = []
	var todayBoolean = true
	var pastBoolean = true
	var futureBoolean = true
	
	for (var i = 0; i < route.params.data.length; i++) {
		const itemDate = new Date(route.params.data[i].date)
		if (itemDate.getTime() == todayDate.getTime()) {
			today.push(route.params.data[i])
		}
		else if (itemDate.getTime() > todayDate.getTime() && itemDate.getTime() <= weekFutureDate.getTime()) {
			future.push(route.params.data[i])
		}
		//else if (itemDate >= weekPastDate && itemDate < todayDate) {
		else if (itemDate.getTime() < todayDate.getTime()) {
			past.push(route.params.data[i])
		}
	}
	if (today.length === 0) todayBoolean = false
	if (past.length === 0) pastBoolean = false
	if (future.length === 0) futureBoolean = false

  const item = route.params
  return (
    <ScrollView style={{display:'flex',  backgroundColor: 'white', height: '100%'}}>
      {todayBoolean?<NewElement name = 'today' navigation = {route.params.navigation} list = {today}/>:<></>}
      {pastBoolean?<NewElement name = 'past' navigation = {route.params.navigation} list = {past}/>:<></>}
      {futureBoolean?<NewElement name = 'future' navigation = {route.params.navigation} list = {future}/>:<></>}
    </ScrollView>
  )
}

export const NewItem = ({route}) => {
  const item = route.params.data
  const iconURI = item.icon !== undefined?`data:image/png;charset=utf-8;base64,${item.icon}`:''
  
  return (
    <ScrollView style={{height: '100%', backgroundColor: 'white'}}>
      <View style={{backgroundColor: '#e3e3e3'}}>
        <Image source={require('./assets/blair_logo.png')} style={{width: windowWidth, height: windowHeight*.6, alignSelf: 'center'}}/>
      </View>
      <View style={{backgroundColor: 'white', marginTop: '-5%', padding: '5%', borderTopLeftRadius: 20, borderTopRightRadius: 20}}>
        <Text style={{fontSize: 14, fontWeight: '200', textAlign: 'center'}}>{item.date}</Text>
        <Text style={{fontSize: 20, textAlign: 'center', paddingBottom: '2%', fontWeight: 'bold'}}>{item.name}</Text>
      </View>
    </ScrollView>
  )
}

const AnnouncementToday = ({item}) => {
  const teacher = item.item.teacher !==""?item.item.teacher:"No Teacher"

  return (
    <View style = {{display: 'flex', flexDirection: 'row', alignItems: 'center', padding: '2%', paddingVertical: '2.5%', justifyContent: 'space-between', borderBottomWidth: 1, borderColor: "#b2b2b2"}}>
      <View style = {{width: '72%'}}>
        <Text style={{fontSize: 18}}>{item.item.message}</Text>
        <Text style={{fontSize: 12, fontWeight: '200', paddingTop: '1%'}}>{item.item.time}</Text>
      </View>
      <View style = {{width: '25%', display: 'flex', flexDirection: 'row', justifyContent: 'flex-end'}}>
        <Text style={{fontSize: 14, alignSelf: 'center', fontWeight: '200'}}>{teacher}</Text>
      </View>
    </View>
  )
}

const New = (props) => {
  const item = props.item
  const iconURI = item.item.icon !== undefined?`data:image/png;charset=utf-8;base64,${item.item.icon}`:''
  const textLength = item.item.name.length
  var text = item.item.name
  if (textLength >=17) {
    text = text.substring(0, 14)+"..."
  }

  return (
    <View style={{paddingRight: '2%'}}>
      <TouchableOpacity onPress={()=>props.navigation.navigate('NewItem', {data:props.item.item})}>
        <ImageBackground style = {{width: windowWidth*.4, height: windowWidth*.55, backgroundColor:'#e3e3e3', borderRadius: 16, alignItems: 'baseline'}}source = {{iconURI}}>
          <View style={{padding: '5%', flex: 1, justifyContent: 'flex-end', width: windowWidth*.4, height: windowWidth*.2, shadowColor: '#323232', shadowOffset: {width: 0, height: 0}, shadowOpacity: 0.5}}>
            <Text style={{fontSize: 12, color: 'white', fontWeight: '700'}}>{item.item.date}</Text>
            <Text style={{fontSize: 16, color: 'white', fontWeight: 'bold'}}>{text}</Text>
          </View>
        </ImageBackground>
      </TouchableOpacity>
    </View>
  )
}

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

  return (
    <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>  
        <Image source = {require('./assets/blair_logo.png')} style = {{alignSelf: 'center', marginTop: '5%', height: 325, width: 325}}/>
        <Text style={styles.modalText}>{url}</Text>
      </View>
    </Modal>
  )
}

const background = (<LinearGradient
  colors={['#f99', 'white']}
  style = {{flex:1,borderBottomColor:'black',borderBottomWidth:0}}
  />)

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:I18n.t('home.whatsNew'),
            headerTitleStyle:styles.headerTitle,
            headerBackground: ()=>background,
            //headerLeft:null,
            headerBackTitleVisible:false,
            headerTintColor: 'black',
            headerTitleAlign: 'center'
          })}
        />
        <Stack.Screen 
          name="Announcements"
          component={Announcements}
          options={({route})=> ({
            title:I18n.t('home.Announcements'),
            headerTitleStyle:styles.headerTitle,
            headerBackground: ()=>background,
            //headerLeft:null,
            headerBackTitleVisible:false,
            headerTintColor: 'black',
            headerTitleAlign: 'center'
          })}
        />
        <Stack.Screen 
						name="TeacherList" 
						component={TeacherList}
						options={({route})=>({
							headerTitleStyle:[styles.headerTitle],
							title:route.params.name,
							headerRight:()=>(<></>),
							headerBackground: ()=>background,
							//headerLeft:null,
							headerBackTitleVisible:false,
							headerTintColor: 'black',
							headerTitleAlign: 'center'
						})}
					/>
        <Stack.Screen 
						name="LunchEvents" 
						component={LunchEvents}
						options={{
							title:I18n.t('home.lunch'),
							headerTitleStyle:styles.headerTitle,
							//headerLeft:null,
							headerBackground: ()=>background,
							headerTitleAlign: 'center',
							headerBackTitleVisible:false,
							headerTintColor: 'black'
						}}
					/>
        <Stack.Screen 
          name="StudentWeek"
          component={StudentWeek}
          options={{
            title:I18n.t('home.SOTW'),
            headerTitleStyle:styles.headerTitle,
            headerBackground: ()=>background,
            //headerLeft:null,
            headerBackTitleVisible:false,
            headerTintColor: 'black',
            headerTitleAlign: 'center'
          }}
        />
        <Stack.Screen 
          name = "NewItem"
          component = {NewItem}
          options={({route})=> ({
            headerTitleStyle:[styles.headerTitle],
            title:I18n.t('home.news'),
            headerRight:()=>(<></>),
            headerBackground: ()=>background,
            //headerLeft: null,
            headerBackTitleVisible:false,
            headerTintColor: 'black',
            headerTitleAlign: 'center'
          })}
        />
      </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();
  const todayDate = getCurrentDate()
  var todayAnn = []
  var todayNew = []
  var todayAnnBoolean = true
  var todayNewBoolean = true
  var showLunch = false
  for (var i = 0; i < props.annData.length; i++) {
    const itemDate = new Date(props.annData[i].date)
    if (itemDate == todayDate) todayAnn.push(props.annData[i])
    else todayAnn.push(props.annData[i])
  }

  for (var i = 0; i < props.data.length; i++) {
    const itemDate = new Date(props.data[i].date)
    if (itemDate == todayDate) todayNew.push(props.data[i])
  }

  if (todayAnn.length === 0) todayAnnBoolean = false
  if (todayNew.length ===0) todayNewBoolean = false
  todayAnn = todayAnn.slice(0, 4)

  var currentTime = new Date();
  var time = currentTime.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3").split(' ')
  var dayOfWeek = currentTime.getDay()
  var hourTime = parseInt(time[0].split(':')[0])

  if (dayOfWeek!=0 && dayOfWeek!=6 && ((hourTime>=10 && time[1]=='AM') || (hourTime ==12 && parseInt(time[0].split(':')[1])<=30 && time[1]=='PM'))) {
    showLunch = true
  }
  if (time[1]!='PM' && time[1]!='AM' && dayOfWeek!=0 && dayOfWeek!=6 && hourTime>=10 && (hourTime <=12 && parseInt(time[0].split(':')[1])<=30)) {
    showLunch = true
  }

  return (
    <ScrollView style={{paddingHorizontal:'5%', backgroundColor: 'white', height: '100%'}}>
      {showLunch? 
        <View style={{display: 'flex', flexDirection: 'row', paddingTop: '2%'}}>
          <Text style={{textAlign: 'center', alignSelf: 'center', fontSize: 16, fontWeight: '200'}}>{I18n.t('home.shortcut')} {'\t'}</Text>
          <TouchableOpacity onPress={()=>props.navigation.navigate(LunchEvents)}>
            <View style={{padding: '5%', borderRadius: 16, borderWidth: 1, borderColor: 'red'}}>
              <Text style={{fontWeight: '200', color: 'red', textAlign: 'center'}}>{I18n.t('home.seeLunch')}</Text>
            </View>
          </TouchableOpacity>
        </View>
      :<></>}

      <View style={{paddingTop: '2%'}}>
        <View style={{display: 'flex', flexDirection:'row', justifyContent: 'space-between', alignItems: 'center', paddingBottom: '5%'}}>
          <Text style={liststyles.homeTitle}>{I18n.t('home.whatsNew')}</Text>
          <TouchableOpacity style={{display: 'flex', flexDirection: 'row'}}onPress={()=>props.navigation.navigate('new', {data:props.data, navigation: props.navigation})}>
            <LinearGradient start={{x: 0, y: 0.25}} end={{x: .5, y: 1}} colors={['red', '#FF7373']} style={{borderRadius: 24, alignSelf: 'center'}}><Image source = {require('./assets/forward.png')} style={{tintColor: 'white'}}/></LinearGradient>
          </TouchableOpacity>
        </View>
        <View style={{backgroundColor: 'white', display: 'flex', flexDirection: 'row'}}>
            {!todayNewBoolean?<Text style={{fontWeight: '200', fontSize: 16, paddingTop: '2%'}}>{I18n.t('home.noNews')}</Text>:<FlatList
            data={todayNew}
            renderItem={item=><New item={item} navigation={props.navigation}/>}
            keyExtractor={item=>JSON.stringify(item)}
            horizontal
            />}
        </View>
      </View>

      <View style={{marginTop: '5%'}}>
        <View style={{display: 'flex', flexDirection:'row', justifyContent: 'space-between', alignItems: 'center', paddingBottom: '5%'}}>
          <Text style={liststyles.homeTitle}>{I18n.t('home.Announcements')}</Text>
          <TouchableOpacity style={{}}onPress={()=>props.navigation.navigate(Announcements)}>
          <LinearGradient start={{x: 0, y: 0.25}} end={{x: .5, y: 1}} colors={['red', '#FF7373']} style={{borderRadius: 24, alignSelf: 'center'}}><Image source = {require('./assets/forward.png')} style={{tintColor: 'white'}}/></LinearGradient>
          </TouchableOpacity>
        </View>
        {!todayAnnBoolean?<Text style={{fontWeight: '200', fontSize: 16, paddingTop: '2%'}}>{I18n.t('home.noAnnouncements')}</Text>:<FlatList
          data={todayAnn}
          renderItem={item=><AnnouncementToday item={item}/>}
          keyExtractor={item=>JSON.stringify(item)}
          />}
      </View>

      <View style={{marginTop: '5%', marginBottom: '10%'}}>
        <Text style={[liststyles.homeTitle, {paddingBottom: '5%'}]}>{I18n.t('home.SOTW')}</Text>
        <View style={{display: 'flex', flexDirection: 'row'}}>
          <View style={{backgroundColor: 'white', width: windowWidth*.30, height: windowWidth*.30, shadowColor: 'red', shadowOffset: {width: 0, height: 2}, shadowOpacity: 0.5, shadowRadius: 7, borderRadius: (windowWidth*.30)/2}}>
            <Image source = {{iconURI}} style = {{height:'100%', width: '100%', borderTopRightRadius: 8, borderTopLeftRadius:8}}/>
          </View>
          <View style ={{width: windowWidth*.60, display: 'flex', paddingLeft: '5%', paddingHorizontal: '2%', alignItems: 'center', justifyContent: 'space-around'}}>
            <Text style={{fontSize: 18, textAlign: 'center'}}>{props.studentData.name}, <Text style={{fontWeight: '200', textAlign: 'center'}}>Grade {props.studentData.year}</Text></Text>
            <TouchableOpacity onPress={()=>props.navigation.navigate(StudentWeek)}>
              <View style={{padding: '5%', borderRadius: 16, borderWidth: 1, borderColor: 'red'}}>
                <Text style={{fontWeight: '200', color: 'red', textAlign: 'center'}}>{I18n.t('home.moreOn')} {props.studentData.name}</Text>
              </View>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </ScrollView>
  )
}

class Home extends React.Component {
  constructor(props) {
		super(props)
		this.state = {
      studentData: [],
      annData:[],
      data:[],
      lunchData:[],
      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/`+String(I18n.locale).split('-')[0]+`/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))

    fetch(`${url}/api/`+String(I18n.locale).split('-')[0]+`/lunchEvents`,{
      headers: {
          'Cache-Control': 'no-cache'
      }}
    ).then((response) => {
      return response.text();
    }).then((json) => {
      this.setState({lunchData: JSON.parse(json)});
    }).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/`+String(I18n.locale).split('-')[0]+`/new`,{
		  headers: {
			'Cache-Control': 'no-cache'
		  } })
		  .then((response) => {
			return response.text();
		  })
		  .then((json) => {
        console.log(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/`+String(I18n.locale).split('-')[0]+`/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;