import { router } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { useState } from 'react';
import { KeyboardAvoidingView, Platform, ScrollView, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { getDB } from '../db';

export default function AddAssetScreen() {
    const insets = useSafeAreaInsets();
    const [name, setName] = useState('');
    const [type, setType] = useState('stock');
    const [value, setValue] = useState('');
    const [quantity, setQuantity] = useState('');

    const handleSave = async () => {
        if (!name || !value) {
            alert('Please fill in name and value');
            return;
        }

        try {
            const db = getDB();
            await db.runAsync(
                'INSERT INTO assets (name, type, value, quantity, purchase_date) VALUES (?, ?, ?, ?, ?)',
                [name, type, parseFloat(value), quantity ? parseFloat(quantity) : null, new Date().toISOString()]
            );
            router.back();
        } catch (error) {
            console.error(error);
            alert('Failed to save asset');
        }
    };

    return (
        <View className="flex-1 bg-gray-100 dark:bg-gray-900">
            <StatusBar style={Platform.OS === 'ios' ? 'light' : 'auto'} />

            <View className="bg-purple-600 pt-4 pb-6 px-6 rounded-b-3xl shadow-lg">
                <Text className="text-white text-2xl font-bold mt-8 text-center">New Asset</Text>
            </View>

            <KeyboardAvoidingView
                behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                className="flex-1"
            >
                <ScrollView className="flex-1 px-6 pt-6">

                    {/* Type Selector */}
                    <ScrollView horizontal showsHorizontalScrollIndicator={false} className="flex-row space-x-2 mb-6">
                        {['stock', 'crypto', 'real_estate', 'fund', 'other'].map((t) => (
                            <TouchableOpacity
                                key={t}
                                onPress={() => setType(t)}
                                className={`px-4 py-2 rounded-full border ${type === t ? 'bg-purple-600 border-purple-600' : 'bg-white border-gray-200 dark:bg-gray-800 dark:border-gray-700'}`}
                            >
                                <Text className={`capitalize ${type === t ? 'text-white' : 'text-gray-900 dark:text-gray-300'}`}>{t.replace('_', ' ')}</Text>
                            </TouchableOpacity>
                        ))}
                    </ScrollView>

                    {/* Value Input */}
                    <View className="bg-white dark:bg-gray-800 rounded-2xl p-6 mb-4 shadow-sm">
                        <Text className="text-gray-500 text-sm mb-2">Current Value</Text>
                        <View className="flex-row items-center">
                            <Text className="text-3xl font-bold text-gray-900 dark:text-white mr-2">€</Text>
                            <TextInput
                                className="flex-1 text-4xl font-bold text-gray-900 dark:text-white"
                                placeholder="0.00"
                                keyboardType="numeric"
                                value={value}
                                onChangeText={setValue}
                                placeholderTextColor="#9CA3AF"
                            />
                        </View>
                    </View>

                    {/* Details Form */}
                    <View className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-sm space-y-4">
                        <View>
                            <Text className="text-gray-500 text-sm mb-2">Asset Name</Text>
                            <TextInput
                                className="w-full bg-gray-50 dark:bg-gray-700 p-4 rounded-xl text-gray-900 dark:text-white"
                                placeholder="e.g. Apple Stock, Bitcoin"
                                value={name}
                                onChangeText={setName}
                                placeholderTextColor="#9CA3AF"
                            />
                        </View>

                        <View className="mt-4">
                            <Text className="text-gray-500 text-sm mb-2">Quantity (Optional)</Text>
                            <TextInput
                                className="w-full bg-gray-50 dark:bg-gray-700 p-4 rounded-xl text-gray-900 dark:text-white"
                                placeholder="0"
                                keyboardType="numeric"
                                value={quantity}
                                onChangeText={setQuantity}
                                placeholderTextColor="#9CA3AF"
                            />
                        </View>
                    </View>

                </ScrollView>

                <View className="p-6 bg-white dark:bg-gray-900 border-t border-gray-100 dark:border-gray-800" style={{ paddingBottom: Math.max(insets.bottom, 24) }}>
                    <TouchableOpacity
                        className="w-full bg-purple-600 py-4 rounded-2xl shadow-lg active:bg-purple-700"
                        onPress={handleSave}
                    >
                        <Text className="text-white text-center font-bold text-lg">Save Asset</Text>
                    </TouchableOpacity>
                </View>
            </KeyboardAvoidingView>
        </View>
    );
}
