import { useAlert } from '@/components/AlertComponent';
import React, { useState } from 'react';
import { View, Text, Modal, TouchableOpacity, TextInput, ScrollView, Platform } from 'react-native';
import { TimeOffRequestType } from '@/types/types';
import { X } from 'lucide-react-native';
import { TimePickerModal } from './TimePickerModal';
import api from '@/utils/api';
import { formatPickerDate } from '@/utils/dateTime';
import { AppDatePicker } from '@/components/AppDatePicker';
import { KeyboardAwareScrollView } from 'react-native-keyboard-controller';

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

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

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

    // Clean up function to reset all fields
    const clearCalendar = () => {
        setDate(null);
        setRange({ startDate: null, endDate: null });
        setStartTime(''); setEndTime('');
        setMessage('');
        setType(types[0]);
    };

    // Function to validate the request
    function validateRequest(type: TimeOffRequestType, date: string | null | undefined, range: { startDate: string | null; endDate: string | null }, startTime: string, endTime: string): string | null {
        if (!type) return "Seleziona una tipologia di assenza.";

        if (type.time_required === 0) {
            if (!range.startDate) return "Seleziona una data di inizio.";
            return null;
        }

        if (!date) return "Seleziona una data.";
        if (!startTime || !endTime) return "Seleziona gli orari.";
        if (startTime >= endTime) return "L'orario di fine deve essere successivo a quello di inizio.";

        return null;
    }

    // Function to send the request to the API
    const saveRequest = async (requestData: any) => {
        try {
            const response = await api.post('/request/add', requestData);

            if (response.data.success) {
                alert.showAlert('success', 'Successo', response.data.message || 'La tua richiesta è stata inviata con successo.');
                onSubmit(requestData);
                onClose();
            } else {
                alert.showAlert('error', 'Errore', response.data.message || 'Impossibile inviare la richiesta.');
            }
        } catch (error: any) {
            console.error('Errore nell\'invio della richiesta:', error);
            throw new Error('Impossibile inviare la richiesta.');
        }
    };

    // Function to submit the request
    const handleSubmit = async () => {
        const error = validateRequest(type, date, range, startTime, endTime);
        if (error) {
            alert.showAlert("error", "Errore", error);
            return;
        }

        // Prepare the interval based on the type of request
        let interval = null;
        if (type.time_required === 0) {
            if (range.startDate) {
                interval = range.startDate;
            }
            if (range.endDate && range.endDate !== range.startDate) {
                if (interval) {
                    interval += ',';
                }
                interval += range.endDate;
            }
        } else {
            interval = date;
        }

        // Build the request data object
        const requestData = {
            type: type.name,
            interval: interval,
            startTime: type.time_required === 1 ? startTime : null,
            endTime: type.time_required === 1 ? endTime : null,
            message: message ? message : null
        };

        try {
            await saveRequest(requestData);
        } catch (e) {
            alert.showAlert("error", "Errore", "Impossibile inviare la richiesta.");
        }
    };

    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">
                    {/* Modal Header */}
                    <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" pointerEvents="none" />
                        </TouchableOpacity>
                    </View>

                    <KeyboardAwareScrollView
                        bottomOffset={Platform.OS === 'ios' ? 50 : 80}
                        disableScrollOnKeyboardHide={false}
                        enabled={true}
                        keyboardShouldPersistTaps="handled"
                        showsVerticalScrollIndicator={false}
                        contentContainerStyle={{
                            paddingBottom: 70,
                            flexGrow: 1
                        }}
                        className="flex-1"
                    >
                        <View className="space-y-6">
                                {/* Permit Type */}
                                <View className='mb-6'>
                                    <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-[#1071C2] bg-blue-50' : 'border-gray-100 bg-white'
                                                    }`}
                                            >
                                                <Text className={`text-sm font-bold ${type?.id === t.id ? 'text-[#1071C2]' : 'text-gray-500'}`}>
                                                    {t.name}
                                                </Text>
                                            </TouchableOpacity>
                                        ))}
                                    </ScrollView>
                                </View>

                                {/* Date and Time Selection */}
                                {type?.time_required === 0 ? (
                                    <AppDatePicker
                                        mode="range"
                                        startDate={range.startDate}
                                        endDate={range.endDate}
                                        onChange={(params) => {
                                            setRange({
                                                startDate: params.startDate ? formatPickerDate(params.startDate) : null,
                                                endDate: params.endDate ? formatPickerDate(params.endDate) : null
                                            })
                                        }}
                                    />
                                ) : (
                                    <AppDatePicker
                                        mode="single"
                                        date={date}
                                        onChange={({ date }) => setDate(date ? formatPickerDate(date) : null)}
                                    />
                                )}

                                <View className='flex-column bg-gray-50 rounded-xl border border-gray-100 mb-6'>
                                    {type?.time_required === 1 && (
                                        <View>
                                            <View className="flex-row gap-4 p-4">
                                                <View className="flex-1">
                                                    <Text className="text-sm font-bold text-gray-700 mb-2 uppercase">Dalle Ore</Text>
                                                    <TouchableOpacity onPress={() => setShowStartPicker(true)}>
                                                        <TextInput
                                                            placeholder="09:00"
                                                            placeholderTextColor="#9CA3AF"
                                                            className="w-full p-3 bg-white rounded-lg border border-gray-200 font-bold text-gray-800 text-center"
                                                            value={startTime}
                                                            onChangeText={setStartTime}
                                                            editable={false}
                                                            pointerEvents="none"
                                                        />
                                                    </TouchableOpacity>
                                                </View>
                                                <View className="flex-1">
                                                    <Text className="text-sm font-bold text-gray-700 mb-2 uppercase">Alle Ore</Text>
                                                    <TouchableOpacity onPress={() => setShowEndPicker(true)}>
                                                        <TextInput
                                                            placeholder="18:00"
                                                            placeholderTextColor="#9CA3AF"
                                                            className="w-full p-3 bg-white rounded-lg border border-gray-200 font-bold text-gray-800 text-center"
                                                            value={endTime}
                                                            onChangeText={setEndTime}
                                                            editable={false}
                                                            pointerEvents="none"
                                                        />
                                                    </TouchableOpacity>
                                                </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>
                                    )}

                                    {/* Reason field */}
                                    <View className="p-4 pt-2">
                                        <Text className="text-sm font-bold text-gray-700 mb-2 uppercase">Motivo</Text>
                                        <TextInput
                                            placeholder="(opzionale)"
                                            placeholderTextColor="#9CA3AF"
                                            className="w-full px-3 py-3 bg-white font-bold text-gray-800 rounded-lg border border-gray-200"
                                            textAlignVertical="top"
                                            value={message}
                                            onChangeText={setMessage}
                                            multiline
                                            numberOfLines={3}
                                        />
                                    </View>
                                </View>

                                {/* Actions */}
                                <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}
                                        className="flex-1 py-4 bg-[#1071C2] rounded-2xl shadow-lg active:scale-[0.98]"
                                    >
                                        <Text className="text-white text-center font-bold text-lg">Invia Richiesta</Text>
                                    </TouchableOpacity>
                                </View>
                        </View>
                    </KeyboardAwareScrollView>
                </View>
            </View>
        </Modal>
    );
};
