import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, Modal, TouchableOpacity, TextInput, KeyboardAvoidingView, Platform, ScrollView } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { theme } from '../styles/theme';

interface TrackMealModalProps {
    visible: boolean;
    onClose: () => void;
    onSave: (meal: { type: string; name: string; calories: number }) => void;
    onResetData?: () => void;
}

const MEAL_TYPES = ['Breakfast', 'Lunch', 'Dinner', 'Snack'];

export function TrackMealModal({ visible, onClose, onSave, onResetData }: TrackMealModalProps) {
    const [selectedType, setSelectedType] = useState('Breakfast');
    const [foodName, setFoodName] = useState('');
    const [calories, setCalories] = useState('');

    useEffect(() => {
        if (visible) {
            setFoodName('');
            setCalories('');
            setSelectedType('Breakfast');
        }
    }, [visible]);

    const handleReset = () => {
        setFoodName('');
        setCalories('');
        setSelectedType('Breakfast');
        if (onResetData) {
            onResetData();
        }
    };

    const handleSave = () => {
        if (!foodName || !calories) return;

        onSave({
            type: selectedType,
            name: foodName,
            calories: parseInt(calories, 10)
        });

        // Reset form
        setFoodName('');
        setCalories('');
        setSelectedType('Breakfast');
    };

    return (
        <Modal
            visible={visible}
            transparent
            animationType="slide"
            onRequestClose={onClose}
        >
            <KeyboardAvoidingView
                behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                style={styles.modalContainer}
            >
                <View style={styles.contentContainer}>
                    <View style={styles.header}>
                        <TouchableOpacity onPress={onClose} style={styles.closeButton}>
                            <Ionicons name="close" size={24} color={theme.colors.gray500} />
                        </TouchableOpacity>
                        <Text style={styles.title}>Track Meal</Text>
                        <TouchableOpacity onPress={handleReset}>
                            <Text style={styles.resetText}>Reset</Text>
                        </TouchableOpacity>
                    </View>

                    <ScrollView showsVerticalScrollIndicator={false}>
                        {/* Meal Type Selection */}
                        <Text style={styles.label}>Meal Type</Text>
                        <View style={styles.typeContainer}>
                            {MEAL_TYPES.map((type) => (
                                <TouchableOpacity
                                    key={type}
                                    onPress={() => setSelectedType(type)}
                                    style={[
                                        styles.typeButton,
                                        selectedType === type && styles.typeButtonActive
                                    ]}
                                >
                                    <Text style={[
                                        styles.typeText,
                                        selectedType === type && styles.typeTextActive
                                    ]}>{type}</Text>
                                </TouchableOpacity>
                            ))}
                        </View>

                        {/* Food Name Input */}
                        <Text style={styles.label}>Food Name</Text>
                        <TextInput
                            style={styles.input}
                            placeholder="e.g., Oatmeal with Berries"
                            value={foodName}
                            onChangeText={setFoodName}
                            placeholderTextColor={theme.colors.gray400}
                        />

                        {/* Calories Input */}
                        <Text style={styles.label}>Calories</Text>
                        <View style={styles.caloriesInputContainer}>
                            <TextInput
                                style={[styles.input, styles.caloriesInput]}
                                placeholder="0"
                                value={calories}
                                onChangeText={setCalories}
                                keyboardType="number-pad"
                                placeholderTextColor={theme.colors.gray400}
                            />
                            <Text style={styles.caloriesUnit}>kcal</Text>
                        </View>

                        {/* Save Button */}
                        <TouchableOpacity onPress={handleSave} style={styles.saveButtonContainer}>
                            <LinearGradient
                                colors={theme.gradients.primary}
                                style={styles.saveButton}
                                start={{ x: 0, y: 0 }}
                                end={{ x: 1, y: 0 }}
                            >
                                <Text style={styles.saveButtonText}>Save Meal</Text>
                            </LinearGradient>
                        </TouchableOpacity>
                    </ScrollView>
                </View>
            </KeyboardAvoidingView>
        </Modal>
    );
}

const styles = StyleSheet.create({
    modalContainer: {
        flex: 1,
        justifyContent: 'flex-end',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
    },
    contentContainer: {
        backgroundColor: '#fff',
        borderTopLeftRadius: 32,
        borderTopRightRadius: 32,
        padding: 24,
        minHeight: '60%',
        ...theme.shadows.strong,
    },
    header: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 24,
    },
    title: {
        fontSize: 24,
        fontWeight: '700',
        color: theme.colors.gray900,
    },
    closeButton: {
        padding: 4,
    },
    resetText: {
        fontSize: 16,
        color: theme.colors.primary,
        fontWeight: '600',
    },
    label: {
        fontSize: 16,
        fontWeight: '600',
        color: theme.colors.gray700,
        marginBottom: 12,
        marginTop: 8,
    },
    typeContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        gap: 8,
        marginBottom: 24,
    },
    typeButton: {
        paddingHorizontal: 16,
        paddingVertical: 8,
        borderRadius: 20,
        backgroundColor: theme.colors.gray100,
        borderWidth: 1,
        borderColor: theme.colors.gray200,
    },
    typeButtonActive: {
        backgroundColor: theme.colors.primaryLight,
        borderColor: theme.colors.primary,
    },
    typeText: {
        fontSize: 14,
        fontWeight: '500',
        color: theme.colors.gray600,
    },
    typeTextActive: {
        color: '#fff',
        fontWeight: '600',
    },
    input: {
        backgroundColor: theme.colors.gray50,
        borderWidth: 1,
        borderColor: theme.colors.gray200,
        borderRadius: 16,
        padding: 16,
        fontSize: 16,
        color: theme.colors.gray900,
        marginBottom: 24,
    },
    caloriesInputContainer: {
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 32,
    },
    caloriesInput: {
        flex: 1,
        marginBottom: 0,
        marginRight: 12,
    },
    caloriesUnit: {
        fontSize: 16,
        fontWeight: '600',
        color: theme.colors.gray500,
    },
    saveButtonContainer: {
        marginTop: 'auto',
        marginBottom: 24,
    },
    saveButton: {
        paddingVertical: 16,
        borderRadius: 20,
        alignItems: 'center',
    },
    saveButtonText: {
        color: '#fff',
        fontSize: 18,
        fontWeight: '700',
    },
});
