import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import React, { useEffect, useState } from 'react';
import {
    Alert,
    FlatList,
    Image,
    ImageBackground,
    Modal,
    ScrollView,
    StyleSheet,
    Switch,
    Text,
    TextInput,
    TouchableOpacity,
    View,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import { Images } from '@/constants/images';
import { createRoom } from '@/services/dimension';
import event from '@/utils/event';

const DateTimePickerModal = ({ visible, onClose, onConfirm }: any) => {
    const now = new Date();
    const [selDate, setSelDate] = useState(now.toISOString().split('T')[0]);
    const [selHour, setSelHour] = useState(String(now.getHours() + 1).padStart(2, '0'));
    const [selMin, setSelMin] = useState('00');

    const dates = Array.from({ length: 30 }, (_, i) => {
        const d = new Date();
        d.setDate(d.getDate() + i);
        return d.toISOString().split('T')[0];
    });
    // Handle wrap around for hours if needed, though simple 0-23 list is fine for selection
    const hours = Array.from({ length: 24 }, (_, i) => i.toString().padStart(2, '0'));
    const mins = ['00', '10', '20', '30', '40', '50'];

    useEffect(() => {
        if (visible) {
            if (!selDate) setSelDate(dates[0]);
        }
    }, [visible]);

    return (
        <Modal visible={visible} transparent animationType="slide" onRequestClose={onClose}>
            <TouchableOpacity style={styles.modalOverlay as any} activeOpacity={1} onPress={onClose}>
                <TouchableOpacity activeOpacity={1} style={styles.pickerContent as any}>
                    <View style={styles.pickerHeader as any}>
                        <TouchableOpacity onPress={onClose}><Text style={styles.cancelText as any}>取消</Text></TouchableOpacity>
                        <Text style={styles.pickerTitle as any}>设置开奖时间</Text>
                        <TouchableOpacity onPress={() => onConfirm(`${selDate} ${selHour}:${selMin}:00`)}>
                            <Text style={styles.confirmText as any}>确定</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.pickerBody as any}>
                        <FlatList
                            data={dates}
                            keyExtractor={i => i}
                            style={{ flex: 2 }}
                            renderItem={({ item }) => (
                                <TouchableOpacity
                                    style={[styles.pickerItem as any, selDate === item && styles.pickerItemActive]}
                                    onPress={() => setSelDate(item)}
                                >
                                    <Text style={[styles.pickerItemText as any, selDate === item && styles.pickerItemTextActive]}>{item}</Text>
                                </TouchableOpacity>
                            )}
                        />
                        <FlatList
                            data={hours}
                            keyExtractor={i => i}
                            style={{ flex: 1 }}
                            renderItem={({ item }) => (
                                <TouchableOpacity
                                    style={[styles.pickerItem as any, selHour === item && styles.pickerItemActive]}
                                    onPress={() => setSelHour(item)}
                                >
                                    <Text style={[styles.pickerItemText as any, selHour === item && styles.pickerItemTextActive]}>{item}时</Text>
                                </TouchableOpacity>
                            )}
                        />
                        <FlatList
                            data={mins}
                            keyExtractor={i => i}
                            style={{ flex: 1 }}
                            renderItem={({ item }) => (
                                <TouchableOpacity
                                    style={[styles.pickerItem as any, selMin === item && styles.pickerItemActive]}
                                    onPress={() => setSelMin(item)}
                                >
                                    <Text style={[styles.pickerItemText as any, selMin === item && styles.pickerItemTextActive]}>{item}分</Text>
                                </TouchableOpacity>
                            )}
                        />
                    </View>
                </TouchableOpacity>
            </TouchableOpacity>
        </Modal>
    );
};

const CreateScreen = () => {
    const router = useRouter();
    const insets = useSafeAreaInsets();

    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [password, setPassword] = useState('');
    const [mode, setMode] = useState(0); // 0: 进房即参加, 1: 审核后参加
    const [luckTime, setLuckTime] = useState('');
    const [goodsList, setGoodsList] = useState<any[]>([]);
    const [checked, setChecked] = useState(true);
    const [showPicker, setShowPicker] = useState(false);

    useEffect(() => {
        const subscription = event.on(event.keys.STORE_CHOOSE, (goods: any[]) => {
            setGoodsList(prev => {
                // 过滤掉已经存在的，避免重复添加
                const existingIds = prev.map(g => g.id);
                const uniqueNewGoods = goods.filter(g => !existingIds.includes(g.id));
                return [...prev, ...uniqueNewGoods];
            });
        });
        return () => subscription.remove();
    }, []);

    const handleSubmit = async () => {
        if (!name || !description || !luckTime) {
            Alert.alert('提示', '请完善表单');
            return;
        }

        const selectedTime = new Date(luckTime.replace(/-/g, '/'));
        if (selectedTime <= new Date()) {
            Alert.alert('提示', '开奖时间必须在当前时间之后');
            return;
        }

        if (goodsList.length === 0) {
            Alert.alert('提示', '请完善赠品');
            return;
        }
        if (!checked) {
            Alert.alert('提示', '请阅读并同意协议');
            return;
        }

        Alert.alert('确定', '确定要创建房间吗？', [
            { text: '取消', style: 'cancel' },
            {
                text: '确定',
                onPress: async () => {
                    const params: any = {
                        description,
                        inventoryIds: goodsList.map(g => g.id),
                        luckTime,
                        name,
                        password,
                    };
                    if (password) {
                        params.participateMode = mode;
                    }

                    try {
                        const res: any = await createRoom(params);
                        if (res && res.success) {
                            Alert.alert('成功', '创建成功');
                            router.back();
                        } else {
                            Alert.alert('创建失败', res?.msg || '操作失败');
                        }
                    } catch (error) {
                        Alert.alert('错误', '发生未知错误');
                    }
                }
            }
        ]);
    };

    const handleAddGoods = () => {
        router.push('/dimension/store_choose');
    };

    const handleRemoveGoods = (index: number) => {
        const newList = [...goodsList];
        newList.splice(index, 1);
        setGoodsList(newList);
    };

    return (
        <View style={styles.container}>
            <ImageBackground
                source={{ uri: Images.common.commonBg }}
                style={styles.background}
                resizeMode="cover"
            >
                <View style={[styles.header, { paddingTop: insets.top }]}>
                    <TouchableOpacity style={styles.backBtn} onPress={() => router.back()}>
                        <Ionicons name="chevron-back" size={24} color="#fff" />
                    </TouchableOpacity>
                    <Text style={styles.title}>创建房间</Text>
                    <View style={styles.placeholder} />
                </View>

                <ScrollView contentContainerStyle={styles.scrollContent}>
                    <View style={styles.tipsBar}>
                        <Ionicons name="information-circle" size={16} color="#fff" />
                        <Text style={styles.tipsText}>房间名称及房间介绍不得带有宣传与本平台无关的内容</Text>
                    </View>

                    <View style={styles.formContainer}>
                        <View style={styles.formItem}>
                            <Text style={styles.label}>房间名：</Text>
                            <TextInput
                                style={styles.input}
                                placeholder="输入房间名称，最多15个汉字"
                                placeholderTextColor="#777"
                                maxLength={15}
                                value={name}
                                onChangeText={setName}
                            />
                        </View>

                        <View style={styles.formItem}>
                            <Text style={styles.label}>活动介绍：</Text>
                            <TextInput
                                style={styles.input}
                                placeholder="输入活动介绍，最多15个汉字"
                                placeholderTextColor="#777"
                                maxLength={15}
                                value={description}
                                onChangeText={setDescription}
                            />
                        </View>

                        <View style={styles.formItem}>
                            <Text style={styles.label}>进房口令：</Text>
                            <TextInput
                                style={styles.input}
                                placeholder="(可选)用户输入口令才能进房间"
                                placeholderTextColor="#777"
                                maxLength={15}
                                value={password}
                                onChangeText={setPassword}
                            />
                        </View>

                        {!!password && (
                            <View style={styles.formItem}>
                                <Text style={styles.label}>参加模式：</Text>
                                <View style={styles.radioGroup}>
                                    <TouchableOpacity style={styles.radioItem} onPress={() => setMode(0)}>
                                        <Ionicons name={mode === 0 ? "radio-button-on" : "radio-button-off"} size={20} color={mode === 0 ? "#F8D668" : "#fff"} />
                                        <Text style={styles.radioText}>进房即参加</Text>
                                    </TouchableOpacity>
                                    <TouchableOpacity style={styles.radioItem} onPress={() => setMode(1)}>
                                        <Ionicons name={mode === 1 ? "radio-button-on" : "radio-button-off"} size={20} color={mode === 1 ? "#F8D668" : "#fff"} />
                                        <Text style={styles.radioText}>审核后参加</Text>
                                    </TouchableOpacity>
                                </View>
                            </View>
                        )}

                        <TouchableOpacity
                            style={styles.formItem as any}
                            onPress={() => setShowPicker(true)}
                        >
                            <Text style={styles.label}>开奖时间：</Text>
                            <Text style={[styles.inputValue, !luckTime && styles.placeholderText]}>
                                {luckTime || '设置开奖时间(一个月内)'}
                            </Text>
                        </TouchableOpacity>

                        <View style={styles.goodsSection as any}>
                            <Text style={styles.label}>赠品：</Text>
                            <View style={styles.goodsList as any}>
                                {goodsList.map((item, index) => (
                                    <View key={item.id} style={styles.goodsItem as any}>
                                        <Image source={{ uri: item.spu.cover }} style={styles.goodsImg} />
                                        <TouchableOpacity
                                            style={styles.removeBtn as any}
                                            onPress={() => handleRemoveGoods(index)}
                                        >
                                            <Ionicons name="close-circle" size={20} color="#ff4d4f" />
                                        </TouchableOpacity>
                                    </View>
                                ))}
                                <TouchableOpacity style={styles.addBtn as any} onPress={handleAddGoods}>
                                    <Ionicons name="add" size={40} color="rgba(255,255,255,0.5)" />
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                </ScrollView>

                <DateTimePickerModal
                    visible={showPicker}
                    onClose={() => setShowPicker(false)}
                    onConfirm={(val: string) => {
                        setLuckTime(val);
                        setShowPicker(false);
                    }}
                />

                <View style={[styles.footer as any, { paddingBottom: Math.max(insets.bottom, 20) }]}>
                    <View style={styles.agreementRow as any}>
                        <Text style={styles.agreementText}>阅读并同意</Text>
                        <TouchableOpacity><Text style={styles.agreementLink}>《福利房使用协议》</Text></TouchableOpacity>
                        <Switch
                            value={checked}
                            onValueChange={setChecked}
                            trackColor={{ false: "#767577", true: "#81b0ff" }}
                            thumbColor={checked ? "#f5dd4b" : "#f4f3f4"}
                            style={styles.switch}
                        />
                    </View>
                    <TouchableOpacity style={styles.submitBtn as any} onPress={handleSubmit}>
                        <ImageBackground
                            source={{ uri: Images.common.butBgL }}
                            style={styles.submitBtnBg as any}
                            resizeMode="stretch"
                        >
                            <Text style={styles.submitBtnText}>确认创建</Text>
                        </ImageBackground>
                    </TouchableOpacity>
                </View>

            </ImageBackground>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    background: {
        flex: 1,
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 15,
        height: 90,
    },
    backBtn: {
        width: 40,
        height: 40,
        justifyContent: 'center',
    },
    title: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#fff',
    },
    placeholder: {
        width: 40,
    },
    scrollContent: {
        paddingBottom: 200,
    },
    tipsBar: {
        backgroundColor: '#209AE5',
        flexDirection: 'row',
        alignItems: 'center',
        padding: 10,
        paddingHorizontal: 15,
    },
    tipsText: {
        color: '#fff',
        fontSize: 12,
        marginLeft: 8,
    },
    formContainer: {
        backgroundColor: 'rgba(255, 255, 255, 0.1)',
        margin: 15,
        padding: 15,
        borderRadius: 8,
    },
    formItem: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 15,
        borderBottomWidth: 1,
        borderBottomColor: 'rgba(255,255,255,0.1)',
    },
    label: {
        width: 80,
        fontSize: 14,
        color: '#fff',
    },
    input: {
        flex: 1,
        fontSize: 14,
        color: '#fff',
        padding: 0,
    },
    inputValue: {
        flex: 1,
        fontSize: 14,
        color: '#fff',
    },
    placeholderText: {
        color: '#777',
    },
    radioGroup: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-around',
    },
    radioItem: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    radioText: {
        color: '#fff',
        fontSize: 12,
        marginLeft: 5,
    },
    goodsSection: {
        paddingVertical: 15,
    },
    goodsList: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 10,
    },
    goodsItem: {
        width: 80,
        height: 80,
        marginRight: 10,
        marginBottom: 10,
        backgroundColor: 'rgba(255,255,255,0.1)',
        borderRadius: 8,
        padding: 5,
        position: 'relative',
    },
    goodsImg: {
        width: '100%',
        height: '100%',
        borderRadius: 4,
    },
    removeBtn: {
        position: 'absolute',
        top: -8,
        right: -8,
    },
    addBtn: {
        width: 80,
        height: 80,
        backgroundColor: 'rgba(255,255,255,0.1)',
        borderRadius: 8,
        justifyContent: 'center',
        alignItems: 'center',
    },
    footer: {
        position: 'absolute',
        bottom: 0,
        left: 0,
        right: 0,
        alignItems: 'center',
        paddingTop: 10,
        backgroundColor: 'rgba(0,0,0,0.5)',
    },
    agreementRow: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 10,
    },
    agreementText: {
        color: '#fff',
        fontSize: 12,
    },
    agreementLink: {
        color: '#50DAFF',
        fontSize: 12,
    },
    switch: {
        transform: [{ scaleX: 0.8 }, { scaleY: 0.8 }],
        marginLeft: 5,
    },
    submitBtn: {
        width: 200,
        height: 60,
    },
    submitBtnBg: {
        width: '100%',
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
    },
    submitBtnText: {
        fontSize: 16,
        fontWeight: '800',
        color: '#fff',
    },
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.6)',
        justifyContent: 'flex-end',
    },
    pickerContent: {
        backgroundColor: '#fff',
        borderTopLeftRadius: 20,
        borderTopRightRadius: 20,
        height: 350,
    },
    pickerHeader: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 15,
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
    },
    pickerTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333',
    },
    cancelText: {
        color: '#999',
        fontSize: 14,
    },
    confirmText: {
        color: '#209AE5',
        fontSize: 14,
        fontWeight: 'bold',
    },
    pickerBody: {
        flex: 1,
        flexDirection: 'row',
    },
    pickerItem: {
        height: 44,
        justifyContent: 'center',
        alignItems: 'center',
    },
    pickerItemActive: {
        backgroundColor: '#f5f5f5',
    },
    pickerItemText: {
        fontSize: 14,
        color: '#666',
    },
    pickerItemTextActive: {
        color: '#209AE5',
        fontWeight: 'bold',
    },
});

export default CreateScreen;
