import React, {useEffect, useState} from 'react';
import {StyleSheet, ScrollView, SafeAreaView, View, StatusBar, TouchableOpacity, Image} from 'react-native';
// @ts-ignore
import CalendarPicker from 'react-native-calendar-picker';
import Ionicons from '@expo/vector-icons/Ionicons';

import {ThemedText} from '@/components/ThemedText';
import {ThemedView} from '@/components/ThemedView';
import {Colors} from '@/constants/Colors';
import {useColorScheme} from '@/hooks/useColorScheme';
import {useToken} from '@/context/AppProvider';
import {Request} from '@/services/request';
import List from '@/components/List';
import { useIsFocused } from '@react-navigation/core';

export default function HomeScreen() {
  const colorScheme = useColorScheme() ?? 'light';
  const isFocused = useIsFocused();
  const {token, isLoading} = useToken();
  const [name, setName] = useState(' '); // Default empty space to prevent layout shifting
  const [dates, setDates] = useState<any | null>([]);
  const [types, setTypes] = useState<any | null>([]);

  useEffect(() => {
    if (token) {
      Request.post('calendar', {token: token}).then((response) => {
        if (response.success) {
          // Set name
          setName(response.name);

          // Set dates
          let calendarDates: any[] = [];
          response.dates.forEach((date: any) => {
            calendarDates.push({
              date: new Date(date.date),
              style: {backgroundColor: date.color},
              textStyle: {color: Colors.white},
              allowDisabled: true,
            })
          })
          setDates(calendarDates);

          // Set types
          setTypes(response.types);
        }
      })
    }
  }, [isFocused]);

  return (
    <SafeAreaView style={{flex: 1, backgroundColor: Colors[colorScheme].background,}}>
      <ThemedView style={styles.container}>
        <ScrollView>
          <ThemedView style={styles.titleContainer}>
            <ThemedText type="title">{getGreeting()},</ThemedText>
          </ThemedView>

          <ThemedView style={styles.titleContainer}>
            <ThemedText type="title" style={{color: Colors[colorScheme].tint}}>{name}</ThemedText>
          </ThemedView>

          <ThemedView style={styles.calendarContainer}>
            <CalendarPicker
              showDayStragglers={true}
              enableDateChange={false}
              customDatesStyles={dates}
              todayTextStyle={styles.today}
              previousComponent={
                <Ionicons size={28} name="chevron-back"/>
              }
              nextComponent={
                <Ionicons size={28} name="chevron-forward"/>
              }
              weekdays={["Zo", "Ma", "Di", "Woe", "Do", "Vrij", "Zat"]}
              months={[
                "Januari",
                "Februari",
                "Maart",
                "April",
                "Mei",
                "Juni",
                "Juli",
                "Augustus",
                "September",
                "Oktober",
                "November",
                "December",
              ]}
            />
          </ThemedView>

          <ThemedView style={styles.legendaContainer}>
            <ThemedText type='subtitle'>Legenda:</ThemedText>
            <List
              data={types}
              viewStyle={styles.legendaList}
              renderItem={(type: any, index: any) => (
                <View style={styles.legendaItem} key={index}>
                  <View style={{...styles.circle, backgroundColor: type.color}}/>
                  <ThemedText type="default">{ type.name }</ThemedText>
                </View>
              )}
            />
          </ThemedView>
        </ScrollView>
      </ThemedView>
    </SafeAreaView>
  );
}

function getGreeting() {
  const myDate = new Date();
  const hours = myDate.getHours();

  if (hours < 12) {
    return 'Goedemorgen';
  } else if (hours >= 12 && hours <= 17) {
    return 'Goedemiddag';
  } else if (hours >= 17 && hours <= 24) {
    return 'Goedenavond';
  }

  return 'Hallo';
}

const styles = StyleSheet.create({
  container: {
    padding: 25,
    marginTop: StatusBar.currentHeight,
  },
  titleContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    paddingBottom: 8,
  },
  calendarContainer: {
    marginTop: 15,
  },
  legendaContainer: {
    marginTop: 40,
  },
  legendaList: {
    marginTop: 15,
    flex: 1,
    flexDirection: 'column',
    alignContent: 'center',
    gap: 15,
  },
  legendaItem: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    flexGrow: 1,
  },
  circle: {
    width: 25,
    height: 25,
    borderRadius: 50,
  },
  today: {
    borderWidth: 3,
    borderColor: Colors.dark.grey,
    borderRadius: 25,
    textAlign: 'center',
    paddingTop: 8,
    width: 40,
    height: 40,
  },
});
