import React, { useState } from 'react';
import { View, Text, Modal, TouchableOpacity, TextInput, ScrollView, Alert } from 'react-native';
import DateTimePicker, { DateType, useDefaultStyles } from 'react-native-ui-datepicker';
import { TimeOffRequest, TimeOffRequestType } from '@/types/types';
import { X } from 'lucide-react-native';
import { TimePickerModal } from './TimePickerModal';
import api from '@/utils/api';

interface RequestPermitModalProps {
    visible: boolean;
    types: TimeOffRequestType[];
    onClose: () => void;
    onSubmit: (data: any) => void;
}

export default function RequestPermitModal({ visible, types, onClose, onSubmit }: RequestPermitModalProps) {
    const defaultStyles = useDefaultStyles();
    const [type, setType] = useState<TimeOffRequestType | undefined>(types[0]); // Default to first type
    const [date, setDate] = useState<DateType>();
    const [range, setRange] = useState<{
        startDate: DateType;
        endDate: DateType;
    }>({ startDate: undefined, endDate: undefined });

    const [showStartPicker, setShowStartPicker] = useState(false);
    const [showEndPicker, setShowEndPicker] = useState(false);
    const [startTime, setStartTime] = useState('');
    const [endTime, setEndTime] = useState('');

    // Funzione per resettare le selezioni di data
    const clearCalendar = () => {
        setDate(undefined);
        setRange({ startDate: undefined, endDate: undefined });
        setStartTime(''); setEndTime('');
        setType(types[0]);
    };

    const saveRequest = async (requestData: any) => {
        try {
            // Chiamata API per salvare la richiesta
            const response = await api.post('/time-off-request/save-request', requestData);
            Alert.alert('Successo', 'La tua richiesta è stata inviata con successo.');
        } catch (error) {
            console.error('Errore nell\'invio della richiesta:', error);
            Alert.alert('Errore', 'Impossibile inviare la richiesta. Riprova più tardi.');
        }
    };

    // Funzione per inviare la richiesta
    const handleSubmit = (
        type: TimeOffRequestType | undefined,
        date: DateType | undefined,
        range: { startDate: DateType | undefined; endDate: DateType | undefined },
        startTime: string,
        endTime: string
    ) => {

        if (!type) {
            alert('Seleziona una tipologia di assenza.');
            return;
        }

        // Validazioni
        if (type.time_required === 0) {
            if (!range.startDate && !range.endDate) {
                alert('Seleziona almeno una data.');
                return;
            }
        } else {
            if (!date) {
                alert('Seleziona una data.');
                return;
            }
            if (!startTime || !endTime) {
                alert('Seleziona l\'orario di inizio e fine.');
                return;
            } else if (startTime >= endTime) {
                alert('L\'orario di fine deve essere successivo all\'orario di inizio.');
                return;
            }
        }

        // Costruzione oggetto request
        const requestData = {
            id_type: type.id,
            start_date: type.time_required === 0 ? range.startDate : date,
            end_date: type.time_required === 0 ? range.endDate : null,
            start_time: type.time_required === 1 ? startTime : null,
            end_time: type.time_required === 1 ? endTime : null,
        };

        saveRequest(requestData);
        onSubmit(requestData);
        onClose();
    };


    return (
        <Modal
            visible={visible}
            transparent={true}
            animationType="slide"
            statusBarTranslucent
        >
            <View className="flex-1 bg-black/60 justify-end sm:justify-center">
                <View className="bg-white w-full rounded-t-[2.5rem] p-6 shadow-2xl h-[85%] sm:h-auto">
                    {/* Header Modale */}
                    <View className="flex-row justify-between items-center mb-6">
                        <Text className="text-2xl font-bold text-gray-800">Nuova Richiesta</Text>
                        <TouchableOpacity onPress={onClose} className="p-2 bg-gray-100 rounded-full">
                            <X size={24} color="#4b5563" />
                        </TouchableOpacity>
                    </View>

                    <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{ paddingBottom: 40 }}>
                        <View className="space-y-6 gap-6">
                            {/* Tipologia */}
                            <View>
                                <Text className="text-lg font-bold text-gray-700 mb-3">Tipologia Assenza</Text>
                                <ScrollView
                                    horizontal
                                    showsHorizontalScrollIndicator={false}
                                    contentContainerStyle={{ paddingHorizontal: 0, gap: 12 }}
                                >
                                    {types.map((t) => (
                                        <TouchableOpacity
                                            key={t.id}
                                            onPress={() => setType(t)}
                                            className={`py-4 px-5 rounded-xl border-2 items-center justify-center ${type?.id === t.id ? 'border-[#099499] bg-teal-50' : 'border-gray-100 bg-white'
                                                }`}
                                        >
                                            <Text className={`text-sm font-bold ${type?.id === t.id ? 'text-[#099499]' : 'text-gray-500'}`}>
                                                {t.name}
                                            </Text>
                                        </TouchableOpacity>
                                    ))}
                                </ScrollView>
                            </View>

                            {/* Date and Time Selection */}
                            {type?.time_required === 0 ? (
                                <DateTimePicker
                                    mode="range"
                                    startDate={range.startDate}
                                    endDate={range.endDate}
                                    onChange={(params) => setRange(params)}
                                    timeZone='Universal'
                                    locale='it'
                                    styles={{
                                        ...defaultStyles,
                                        selected: { backgroundColor: '#099499' }
                                    }}
                                />
                            ) : (
                                <View className='flex-column'>
                                    <DateTimePicker
                                        mode="single"
                                        date={date}
                                        onChange={({ date }) => setDate(date)}
                                        timeZone='Universal'
                                        locale='it'
                                        styles={{
                                            ...defaultStyles,
                                            selected: { backgroundColor: '#099499' }
                                        }}
                                    />

                                    <View className="flex-row gap-4 p-4 bg-orange-50 rounded-xl border border-orange-100">
                                        <View className="flex-1">
                                            <Text className="text-xs font-bold text-orange-800 mb-2 uppercase">Dalle Ore</Text>
                                            <TouchableOpacity onPress={() => setShowStartPicker(true)}>
                                                <TextInput
                                                    placeholder="09:00"
                                                    className="w-full p-3 bg-white rounded-lg border border-orange-200 font-bold text-gray-800 text-center"
                                                    value={startTime}
                                                    onChangeText={setStartTime}
                                                    editable={false}
                                                />
                                            </TouchableOpacity>
                                        </View>
                                        <View className="flex-1">
                                            <Text className="text-xs font-bold text-orange-800 mb-2 uppercase">Alle Ore</Text>
                                            <TouchableOpacity onPress={() => setShowEndPicker(true)}>
                                                <TextInput
                                                    placeholder="18:00"
                                                    className="w-full p-3 bg-white rounded-lg border border-orange-200 font-bold text-gray-800 text-center"
                                                    value={endTime}
                                                    onChangeText={setEndTime}
                                                    editable={false}
                                                />
                                            </TouchableOpacity>
                                        </View>
                                    </View>
                                </View>
                            )}

                            <TimePickerModal
                                visible={showStartPicker}
                                initialDate={new Date()}
                                title="Seleziona Ora Inizio"
                                onConfirm={(time) => setStartTime(time)}
                                onClose={() => setShowStartPicker(false)}
                            />
                            <TimePickerModal
                                visible={showEndPicker}
                                initialDate={new Date()}
                                title="Seleziona Ora Fine"
                                onConfirm={(time) => setEndTime(time)}
                                onClose={() => setShowEndPicker(false)}
                            />

                            <View className="flex-row gap-4">
                                <TouchableOpacity
                                    onPress={() => {
                                        clearCalendar();
                                        onClose();
                                    }}
                                    className="flex-1 py-4 bg-gray-200 rounded-2xl shadow-sm active:bg-gray-300"
                                >
                                    <Text className="text-gray-700 text-center font-bold text-lg">Annulla Richiesta</Text>
                                </TouchableOpacity>

                                <TouchableOpacity
                                    onPress={() => {
                                        handleSubmit(type, date, range, startTime, endTime);
                                    }}
                                    className="flex-1 py-4 bg-[#099499] rounded-2xl shadow-lg active:scale-[0.98]"
                                >
                                    <Text className="text-white text-center font-bold text-lg">Invia Richiesta</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </ScrollView>
                </View>
            </View>
        </Modal>
    );
};