import AttendanceCard from '@/components/AttendanceCard';
import LoadingScreen from '@/components/LoadingScreen';
import api from '@/utils/api';
import { AuthContext } from '@/utils/authContext';
import { useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { FileText, QrCode, User } from 'lucide-react-native';
import React, { useContext, useEffect, useState } from 'react';
import { RefreshControl, ScrollView, Text, TouchableOpacity, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

export default function HomeScreen() {
    const router = useRouter();
    const { user } = useContext(AuthContext);
    const [isLoading, setIsLoading] = useState(true);
    const [refreshing, setRefreshing] = useState(false);
    
    const [updates, setUpdates] = useState<any[]>([]);
    const [attendances, setAttendances] = useState<any[]>([]);

    const fetchDashboardData = async () => {
        try {
            if (!refreshing) setIsLoading(true);
            
            const params = { range: null, place: null };
            
            // Parallel requests for journal and attendance data
            const [journalRes, attendanceRes] = await Promise.all([
                api.post('/journal/list', { params }),
                api.post('/attendance/list', { params })
            ]);

            // Select first element of journal (slice 0,1)
            if (journalRes.data?.success) {
                setUpdates(journalRes.data.result.slice(0, 1));
            }
            // Select first 2 elements of attendances (slice 0,2)
            if (attendanceRes.data?.success) {
                setAttendances(attendanceRes.data.result.slice(0, 2));
            }
            
        } catch (error) {
            console.error('Errore nel recupero dei dati della dashboard:', error);
        } finally {
            setIsLoading(false);
            setRefreshing(false);
        }
    };

    useEffect(() => {
        fetchDashboardData();
    }, []);

    const onRefresh = () => {
        setRefreshing(true);
        fetchDashboardData();
    };

    if (isLoading && !refreshing) {
        return (
            <LoadingScreen />
        );
    }

    return (
        <View className="flex-1 bg-primary-dark">
            <StatusBar style="light" />
            <SafeAreaView edges={['top']} className='pt-5'>
                {/* Custom Banner */}
                <View className="pb-6 px-6 shadow-sm z-10">
                    <View className="flex-row justify-between items-start">
                        <View className="flex-row items-center gap-4 flex-1 mr-4">
                            <View className="flex-1">
                                <Text className="text-neutral-50 text-md font-semibold uppercase tracking-wider mb-2">
                                    IP Costruzioni SRL
                                </Text>
                                <Text className="text-white text-4xl font-bold leading-tight">
                                    Ciao <Text className="text-yellow-400">{user?.firstName}</Text>
                                </Text>
                            </View>
                        </View>
                        <View className="flex-row gap-4 flex-shrink-0 items-center">
                            {/* Profile Avatar */}
                            <TouchableOpacity className="p-3 bg-white/10 rounded-full active:bg-white/20" onPress={() => router.push('/profile')}>
                                <User size={28} color="white" pointerEvents="none"/>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </SafeAreaView>

            {/* Scrollable Content */}
            <ScrollView
                className="flex-1 bg-gray-50 rounded-t-[2.5rem] px-5 pt-6"
                contentContainerStyle={{ paddingBottom: 50, gap: 24 }}
                showsVerticalScrollIndicator={false}
                refreshControl={
                    <RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#1071C2']} />
                }
            >

                {/* Quick Actions */}
                <View>
                    <Text className="text-gray-800 text-xl font-bold mb-4 px-1">Azioni Rapide</Text>
                    <View className="flex-row gap-5">
                        <TouchableOpacity
                            onPress={() => router.push('/attendance')}
                            className="flex-1 bg-white p-6 rounded-3xl shadow-sm items-center justify-center gap-4 border border-gray-100 active:scale-[0.98]"
                        >
                            <View className="w-20 h-20 rounded-full bg-blue-50 items-center justify-center mb-1">
                                <QrCode size={40} color="#1071C2" pointerEvents="none"/>
                            </View>
                            <Text className="text-lg font-bold text-gray-700 text-center">Nuova Presenza</Text>
                        </TouchableOpacity>

                        <TouchableOpacity
                            onPress={() => router.push('/journal/add')}
                            className="flex-1 bg-white p-6 rounded-3xl shadow-sm items-center justify-center gap-4 border border-gray-100 active:scale-[0.98]"
                        >
                            <View className="w-20 h-20 rounded-full bg-blue-50 items-center justify-center mb-1">
                                <FileText size={40} color="#1071C2" pointerEvents="none"/>
                            </View>
                            <Text className="text-lg font-bold text-gray-700 text-center">Nuovo{'\n'} Giornale</Text>
                        </TouchableOpacity>
                    </View>
                </View>

                {/* Journal */}
                <View>
                    <View className="flex-row justify-between items-center px-1 mb-4">
                        <Text className="text-gray-800 text-xl font-bold">Giornale di Cantiere</Text>
                    </View>
                    <View className="gap-4">
                        {updates.map((item, index) => (
                            <View key={index} className="bg-white p-5 rounded-3xl shadow-sm border border-gray-100 flex-row items-center">
                                <View className="bg-blue-50 p-4 rounded-full mr-4 flex-shrink-0">
                                    <FileText size={24} color="#1071C2" pointerEvents="none"/>
                                </View>
                                <View className="flex-1 mr-2">
                                    <Text className="text-base font-bold text-primary-dark mb-1 leading-tight uppercase" numberOfLines={2}>
                                        {item.place_name}
                                    </Text>
                                    <Text className="text-xs font-medium text-primary-dark mb-1 leading-tight" numberOfLines={2}>
                                        {item.place_address}
                                    </Text>
                                    <Text className="text-xs font-bold text-gray-400 mt-1">
                                        {item.date}
                                    </Text>
                                </View>
                            </View>
                        ))}
                        
                        {!isLoading && updates.length === 0 && (
                            <View className="bg-white p-6 rounded-3xl border border-gray-100 items-center justify-center border-dashed">
                                <Text className="text-gray-400 font-medium">Nessun aggiornamento recente</Text>
                            </View>
                        )}
                        {isLoading && updates.length === 0 && (
                            <View className="bg-white p-5 rounded-3xl border border-gray-100 h-24 justify-center items-center">
                                <Text className="text-gray-400">Caricamento...</Text>
                            </View>
                        )}
                    </View>
                </View>

                {/* Attendance */}
                <View>
                    <View className="flex-row justify-between items-center px-1 mb-4">
                        <Text className="text-gray-800 text-xl font-bold">Presenze</Text>
                    </View>
                    <View className="gap-4">
                        {attendances.map((item, index) => (
                            <AttendanceCard key={index} item={item} />
                        ))}
                        
                        {!isLoading && attendances.length === 0 && (
                            <View className="bg-white p-6 rounded-3xl border border-gray-100 items-center justify-center border-dashed">
                                <Text className="text-gray-400 font-medium">Nessuna presenza recente</Text>
                            </View>
                        )}
                        {isLoading && attendances.length === 0 && (
                            <View className="bg-white p-5 rounded-3xl border border-gray-100 h-24 justify-center items-center">
                                <Text className="text-gray-400">Caricamento...</Text>
                            </View>
                        )}
                    </View>
                </View>
                
            </ScrollView>
        </View>
    );
}
