import React, { useState } from 'react';
import { Modal, View, TouchableOpacity, Text } from 'react-native';
import DateTimePicker, { DateType, useDefaultStyles } from 'react-native-ui-datepicker';
import { X } from 'lucide-react-native';
import dayjs from 'dayjs';

interface TimePickerModalProps {
    visible: boolean;
    initialDate?: DateType;
    title?: string;
    onConfirm: (time: string) => void;
    onClose: () => void;
}

export const TimePickerModal = ({ visible, initialDate, title, onConfirm, onClose }: TimePickerModalProps) => {
    const defaultStyles = useDefaultStyles('light');
    const [selectedDate, setSelectedDate] = useState<DateType>(initialDate || new Date());

    const formatTime = (date?: DateType | null) => {
        if (!date) return "00:00";
        date = dayjs(date);
        const hour = date?.hour().toString().padStart(2, "0") ?? "00";
        const minute = date?.minute().toString().padStart(2, "0") ?? "00";
        return `${hour}:${minute}`;
    };

    const handleConfirm = () => {
        const time = formatTime(selectedDate);
        console.log("Selected time:", time);
        onConfirm(time);
        onClose();
    };

    return (
        <Modal visible={visible} transparent animationType="fade">
            <View className="flex-1 justify-center items-center bg-black/50">
                <View className="bg-white rounded-xl p-4 w-[90%] max-h-[400px]">

                    {/* Header */}
                    <View className="flex-row justify-between items-center mb-4">
                        <Text className="text-lg font-bold text-gray-800">{title}</Text>
                        <TouchableOpacity onPress={onClose} className="p-2 bg-gray-100 rounded-full">
                            <X size={20} color="#4b5563" pointerEvents="none" />
                        </TouchableOpacity>
                    </View>

                    {/* TimePicker */}
                    <DateTimePicker
                        mode="single"
                        timePicker
                        date={selectedDate}
                        initialView="time"
                        hideHeader
                        containerHeight={200}
                        styles={defaultStyles}
                        onChange={(d) => setSelectedDate(d.date || new Date())}
                    />

                    {/* Confirm Button */}
                    <TouchableOpacity
                        onPress={handleConfirm}
                        className="mt-4 w-full py-3 bg-[#1071C2] rounded-xl shadow-lg active:scale-[0.98]"
                    >
                        <Text className="text-white text-center font-bold text-lg">Applica</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </Modal>
    );
};
