import React, { useState, useEffect } from 'react';
import { View, TextInput, StyleSheet, Text, TouchableOpacity } from 'react-native';
import * as SQLite from 'expo-sqlite';
import { Picker } from '@react-native-picker/picker';
import DateTimePicker from '@react-native-community/datetimepicker';

export default function TransactionAdd({ onTransactionAdded }) {
  const [description, setDescription] = useState('');
  const [amount, setAmount] = useState('');
  const [category, setCategory] = useState(''); // Default category
  const [transactionType, setTransactionType] = useState('expense'); // Default to expense
  const [date, setDate] = useState(new Date());
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [datePlaceholder, setDatePlaceholder] = useState('');

  useEffect(() => {
    async function setupDatabase() {
      const db = await SQLite.openDatabaseAsync('moneyAppDB');
      // await db.execAsync('DROP TABLE IF EXISTS transactions'); // Elimina la tabella esistente
      await db.execAsync(`
        CREATE TABLE IF NOT EXISTS transactions (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          description TEXT NOT NULL,
          amount REAL NOT NULL,
          category TEXT NOT NULL,
          date TEXT NOT NULL,
          type TEXT NOT NULL
        )
      `);
    }
    setupDatabase();

    const currentDate = new Date();
    const formattedDate = `${currentDate.getDate().toString().padStart(2, '0')}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${currentDate.getFullYear()}`;
    setDatePlaceholder(formattedDate);
  }, []);

  const addTransaction = async () => {
    if (description.trim() === '' || amount.trim() === '') {
      alert('Descrizione e/o Importo mancanti');
      return;
    }

    // Validate amount format
    const amountRegex = /^\d+(\.\d{1,2})?$/;
    if (!amountRegex.test(amount)) {
      alert('Formato importo non valido. Usa il formato 0.00');
      return;
    }

    // Get selected date in DD-MM-YYYY format
    const formattedDate = `${date.getDate().toString().padStart(2, '0')}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getFullYear()}`;

    try {
      const db = await SQLite.openDatabaseAsync('moneyAppDB');
      await db.runAsync(
        'INSERT INTO transactions (description, amount, category, date, type) VALUES (?, ?, ?, ?, ?)',
        [description, parseFloat(amount), category, formattedDate, transactionType]
      );
      alert('Transazione aggiunta con successo.');
      setDescription('');
      setAmount('');
      setCategory(''); // Reset to default category
      setTransactionType('expense'); // Reset to default type
      if (onTransactionAdded) {
        onTransactionAdded();
      }
    } catch (error) {
      console.error('Error adding transaction:', error);
      alert('Errore. Inserisci correttamente i dati.');
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.testo}>Descrizione:</Text>
      <TextInput
        style={styles.input}
        value={description}
        onChangeText={setDescription}
      />
      <Text style={styles.testo}>Importo:</Text>
      <TextInput
        style={styles.input}
        value={amount}
        onChangeText={setAmount}
        keyboardType="numeric"
      />
      <Text style={styles.testo}>Categoria:</Text>

      <View style={{borderColor: 'gray', borderWidth: 1, marginBottom: 20}}>
        <Picker
          selectedValue={category}
          style={styles.picker}
          onValueChange={(itemValue) => setCategory(itemValue)}
        >
          <Picker.Item label="Spesa" value="spesa" />
          <Picker.Item label="Svago" value="svago" />
          <Picker.Item label="Trasporti" value="trasporti" />
          <Picker.Item label="Cibo" value="cibo" />
          <Picker.Item label="Varie" value="varie" />
        </Picker>
      </View>

      <Text style={styles.testo}>Data:</Text>
      <TextInput
        style={styles.input}
        value={datePlaceholder}
        onFocus={() => setShowDatePicker(true)}
      />
      {showDatePicker && (
        <DateTimePicker
          value={date}
          mode="date"
          display="default"
          onChange={(event, selectedDate) => {
            const currentDate = selectedDate || date;
            setShowDatePicker(false);
            setDate(currentDate);
            const formattedDate = `${currentDate.getDate().toString().padStart(2, '0')}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${currentDate.getFullYear()}`;
            setDatePlaceholder(formattedDate);
          }}
        />
      )}

      <View style={{marginTop: 10}}>
        <Text style={styles.testo}>Tipo di Transazione:</Text>
      </View>
      <View style={styles.buttonContainer}>
        <TouchableOpacity
          style={[styles.button, transactionType === 'income' && styles.selectedButton]}
          onPress={() => setTransactionType('income')}
        >
          <Text style={styles.buttonText}>Entrata (+)</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.button, transactionType === 'expense' && styles.selectedButton]}
          onPress={() => setTransactionType('expense')}
        >
          <Text style={styles.buttonText}>Uscita (-)</Text>
        </TouchableOpacity>
      </View>

      <TouchableOpacity style={styles.addButton} onPress={addTransaction}>
        <Text style={styles.addButtonText}>Aggiungi</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  input: {
    color: '#fff',
    height: 50,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 15,
    fontSize: 16
  },
  picker: {
    color: '#fff',
    borderColor: 'gray',
    borderWidth: 2,
  },
  testo: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '700',
    paddingBottom: 10,
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 20,
  },
  button: {
    flex: 1,
    padding: 15,
    backgroundColor: '#3c3c3c',
    borderRadius: 5,
    alignItems: 'center',
    marginHorizontal: 3,
  },
  selectedButton: {
    backgroundColor: '#f57242',
  },
  buttonText: {
    color: '#fff',
    fontSize: 16,
  },
  addButton: {
    backgroundColor: '#fff',
    padding: 15, // Aumenta l'altezza del pulsante
    borderRadius: 5,
    alignItems: 'center',
  },
  addButtonText: {
    color: '#000',
    fontSize: 16,
  },
});
