import { Ionicons, MaterialCommunityIcons, MaterialIcons } from '@expo/vector-icons';
import { addDays, addWeeks, format, getMonth, getYear, isSameDay, startOfWeek, subWeeks } from 'date-fns';
import { useRouter } from 'expo-router';
import * as SecureStore from 'expo-secure-store';
import React, { useEffect, useState } from "react";
import { ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native";

const PRIMARY = '#A24BFA';
const BG = '#0c0a0a';

export default function Schedule() {
    const [currentWeek, setCurrentWeek] = useState(new Date());
    const [workdays, setWorkdays] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const router = useRouter();

    useEffect(() => {
        fetchWorkdays();
    }, [currentWeek]);

    async function fetchWorkdays() {
        setLoading(true);
        try {
            const token = await SecureStore.getItemAsync('token');
            if (!token) {
                throw new Error('Nincs elmentett token, kérlek jelentkezz be újra!');
            }

            // Az aktuális hét első és utolsó napja
            const weekStart = startOfWeek(currentWeek, { weekStartsOn: 1 });
            const weekEnd = addDays(weekStart, 6);
            const months = new Set([
                getMonth(weekStart) + 1,
                getMonth(weekEnd) + 1
            ]);
            const years = new Set([
                getYear(weekStart),
                getYear(weekEnd)
            ]);

            let allWorkdays: any[] = [];
            for (const year of years) {
                for (const month of months) {
                    const response = await fetch(`https://menuapi.devbeni.lol/api/@me/schedule?year=${year}&month=${month}`, {
                        method: 'GET',
                        headers: {
                            'Authorization': `Bearer ${token}`,
                            'Accept': 'application/json',
                        },
                    });
                    const data = await response.json();
                    if (data && data.data && Array.isArray(data.data.Data)) {
                        allWorkdays = allWorkdays.concat(data.data.Data);
                    }
                }
            }
            setWorkdays(allWorkdays);
        } catch (e) {
            const err = e as any;
            if (err.response) {
                console.log('API error response:', {
                    data: err.response.data,
                });
            } else {
                console.log('Network error:', e);
            }
            setWorkdays([]);
        } finally {
            setLoading(false);
        }
    }

    function renderCalendar() {
        const weekStart = startOfWeek(currentWeek, { weekStartsOn: 1 });
        const today = new Date();
        // 2 soros grid: első sor 4 nap, második sor 3 nap
        const weekDays = Array.from({ length: 7 }, (_, i) => addDays(weekStart, i));
        const firstRow = weekDays.slice(0, 4);
        const secondRow = weekDays.slice(4);

        function renderDayBox(day: string | number | Date) {
            const formattedDate = format(day, 'yyyy-MM-dd');
            const wd = workdays.find(w => w.WorkDay?.slice(0, 10) === formattedDate);
            let bg = '#ede7f6';
            let color = '#6a1b9a';
            let borderWidth = 0;
            if (isSameDay(day, today)) {
                borderWidth = 2;
                color = PRIMARY;
            }
            if (wd) {
                if (wd.Type === 1) {
                    bg = '#B388FF';
                    color = '#311b92';
                } else if (wd.Type === 10) {
                    bg = '#A24BFA';
                    color = '#fff';
                }
            }
            return (
                <View
                    key={day.toString()}
                    style={{
                        flex: 1,
                        margin: 6,
                        minWidth: 60,
                        minHeight: 70,
                        maxWidth: 120,
                        maxHeight: 120,
                        justifyContent: 'center',
                        alignItems: 'center',
                    }}
                >
                    <View style={{
                        backgroundColor: bg,
                        borderRadius: 18,
                        borderWidth,
                        borderColor: PRIMARY,
                        justifyContent: 'center',
                        alignItems: 'center',
                        width: '100%',
                        minHeight: 60,
                        paddingVertical: 10,
                        paddingHorizontal: 4,
                        shadowColor: '#a24bfa',
                        shadowOpacity: 0.10,
                        shadowRadius: 8,
                        shadowOffset: { width: 0, height: 2 },
                        overflow: 'hidden',
                    }}>
                        <Text style={{ color, fontWeight: 'bold', fontSize: 22, textAlign: 'center', width: '100%' }}>{format(day, 'd')}</Text>
                        {wd && wd.Type === 1 && (
                            <Text style={{ color, fontSize: 15, fontWeight: 'bold', marginTop: 4, textAlign: 'center', width: '100%' }} numberOfLines={2} ellipsizeMode="tail">PN</Text>
                        )}
                        {wd && wd.Type === 10 && wd.text && (
                            <Text style={{ color, fontSize: 15, fontWeight: 'bold', marginTop: 4, textAlign: 'center', width: '100%' }} numberOfLines={2} ellipsizeMode="tail">{wd.text}</Text>
                        )}
                    </View>
                </View>
            );
        }

        return (
            <View>
                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
                    <TouchableOpacity onPress={() => setCurrentWeek(subWeeks(currentWeek, 1))}><Ionicons name="chevron-back" size={28} color="#fff" /></TouchableOpacity>
                    <Text style={{ color: '#fff', fontSize: 18, fontWeight: 'bold' }}>{format(weekStart, 'yyyy. MMMM d.') + ' - ' + format(addDays(weekStart, 6), 'MMMM d.')}</Text>
                    <TouchableOpacity onPress={() => setCurrentWeek(addWeeks(currentWeek, 1))}><Ionicons name="chevron-forward" size={28} color="#fff" /></TouchableOpacity>
                </View>
                <View style={{ flexDirection: 'row', marginBottom: 4, width: '100%' }}>
                    {["H", "K", "Sz", "Cs", "P", "Szo", "V"].map(d => (
                        <Text key={d} style={{ flex: 1, color: '#bdbdbd', textAlign: 'center', fontWeight: 'bold' }}>{d}</Text>
                    ))}
                </View>
                {loading ? (
                    <Text style={{ color: '#fff', textAlign: 'center', marginTop: 24 }}>Betöltés…</Text>
                ) : (
                    <View style={{ width: '100%', alignItems: 'center', justifyContent: 'center' }}>
                        <View style={{ flexDirection: 'row', width: '100%', justifyContent: 'center' }}>
                            {firstRow.map(renderDayBox)}
                        </View>
                        <View style={{ flexDirection: 'row', width: '75%', justifyContent: 'center' }}>
                            {secondRow.map(renderDayBox)}
                        </View>
                    </View>
                )}
            </View>
        );
    }

    return (
        <ScrollView style={{ flex: 1, backgroundColor: BG }} contentContainerStyle={{ flexGrow: 1, justifyContent: 'center', alignItems: 'center', minHeight: '100%', paddingBottom: 80, width: '100%' }}>
            <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', width: '100%' }}>
                <View style={[styles.card, { alignSelf: 'center', marginTop: 48, marginBottom: 48, width: '100%' }]}> 
                    <Text style={styles.label}>Beosztás naptár</Text>
                    {(!loading && workdays.length === 0) && (
                        <Text style={{ color: '#ff5252', textAlign: 'center', marginBottom: 12, fontWeight: 'bold' }}>
                            Nincs beosztás vagy nem vagy bejelentkezve!
                        </Text>
                    )}
                    {renderCalendar()}
                </View>
            </View>
            <View style={styles.navBar}>
                <NavBar activeTab="schedule" />
            </View>
        </ScrollView>
    );
}

function NavBar({ activeTab }: { activeTab: string }) {
    const router = useRouter();
    return (
        <View style={styles.navBar}>
            <TouchableOpacity style={styles.navItem} onPress={() => router.push('/profile')}>
                <MaterialIcons name="person" size={28} color={activeTab === 'profile' ? PRIMARY : '#bdbdbd'} />
                <Text style={[styles.navLabel, { color: activeTab === 'profile' ? PRIMARY : '#bdbdbd' }]}>Profilom</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.navItem} onPress={() => router.push('/schedule')}>
                <MaterialCommunityIcons name="calendar-month" size={28} color={activeTab === 'schedule' ? PRIMARY : '#bdbdbd'} />
                <Text style={[styles.navLabel, { color: activeTab === 'schedule' ? PRIMARY : '#bdbdbd' }]}>Beosztás</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.navItem} onPress={() => router.push('/requests')}>
                <Ionicons name="mail" size={28} color={activeTab === 'requests' ? PRIMARY : '#bdbdbd'} />
                <Text style={[styles.navLabel, { color: activeTab === 'requests' ? PRIMARY : '#bdbdbd' }]}>Kérelmek</Text>
            </TouchableOpacity>
        </View>
    );
}

const styles = StyleSheet.create({
    card: {
        backgroundColor: 'rgba(24, 20, 28, 0.95)',
        borderRadius: 24,
        padding: 32,
        width: '90%',
        maxWidth: 400,
        shadowColor: '#000',
        shadowOpacity: 0.3,
        shadowRadius: 24,
        shadowOffset: { width: 0, height: 8 },
        elevation: 8,
        marginBottom: 32,
        marginTop: 32,
    },
    label: {
        color: '#bdbdbd',
        fontSize: 16,
        marginBottom: 16,
        fontWeight: 'bold',
        textAlign: 'center',
    },
    navBar: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        alignItems: 'center',
        backgroundColor: 'rgba(24, 20, 28, 0.98)',
        borderTopWidth: 1,
        borderTopColor: '#222',
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        height: 64,
        paddingHorizontal: 16,
    },
    navItem: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    navLabel: {
        fontSize: 13,
        marginTop: 2,
        fontWeight: 'bold',
    },
});
