import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart'; // Ensure this is imported

class DatabaseHelper {
  static final _databaseName = "eanapo.db";
  static final _databaseVersion = 1;

  static final tableData = 'eanapo_data';
  static final tableImage = 'eanapo_image';

  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
  static Database? _database;

  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  Future<Database> _initDatabase() async {
    final directory = await getApplicationDocumentsDirectory();
    final path = join(directory.path, _databaseName);
    return await openDatabase(
      path,
      version: _databaseVersion,
      onCreate: _onCreate,
    );
  }

  Future<void> _onCreate(Database db, int version) async {
    await db.execute('''
      CREATE TABLE $tableData (
        id INTEGER PRIMARY KEY,
        title TEXT NOT NULL,
        content TEXT NOT NULL,
        date_time TEXT NOT NULL
      )
    ''');
    await db.execute('''
      CREATE TABLE $tableImage (
        id INTEGER PRIMARY KEY,
        title TEXT NOT NULL,
        path TEXT NOT NULL,
        date_time TEXT NOT NULL
      )
    ''');
  }

  Future<List<Map<String, dynamic>>> getLastDataByDate(String date) async {
    final db = await database;
    return await db.query(
      tableData,
      where: 'date_time LIKE ?',
      whereArgs: ['$date%'],
      orderBy: 'date_time DESC',
      limit: 1,
    );
  }

  Future<List<Map<String, dynamic>>> getImagesByDate(String date) async {
    final db = await database;
    return await db.query(
      tableImage,
      where: 'date_time LIKE ?',
      whereArgs: ['$date%'],
    );
  }

  Future<void> insertData(String title, String content, String dateTime) async {
    final db = await database;
    await db.insert(
      tableData,
      {'title': title, 'content': content, 'date_time': dateTime},
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  Future<void> insertImage(String title, String path, String dateTime) async {
    final db = await database;
    await db.insert(
      tableImage,
      {'title': title, 'path': path, 'date_time': dateTime},
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  Future<void> deleteDataByTitle(String title) async {
    final db = await database;
    await db.delete(
      'eanapo_data', // Make sure to replace with your actual data table name
      where: 'title = ?',
      whereArgs: [title],
    );
  }

  Future<void> deleteImagesByTitle(String title) async {
    final db = await database;
    await db.delete(
      'eanapo_image', // Make sure to replace with your actual images table name
      where: 'title = ?',
      whereArgs: [title],
    );
  }

  // Method to delete all records from the data table
  Future<void> deleteAllData() async {
    final db = await database;
    await db.delete(tableData);
  }

  // Method to delete all records from the image table
  Future<void> deleteAllImages() async {
    final db = await database;
    await db.delete(tableImage);
  }

  Future<String?> getMostRecentTitle() async {
    final db = await database;

    try {
      // Query the most recent entry from both tables
      final dataResult = await db.query(
        'eanapo_data',
        columns: [
          'title',
          'timestamp_column'
        ], // Replace with your timestamp column
        orderBy: 'timestamp_column DESC',
        limit: 1,
      );

      final imageResult = await db.query(
        'eanapo_image',
        columns: [
          'title',
          'timestamp_column'
        ], // Replace with your timestamp column
        orderBy: 'timestamp_column DESC',
        limit: 1,
      );

      // Extract the most recent title from each result
      final dataTitle = dataResult.isNotEmpty ? dataResult.first : null;
      final imageTitle = imageResult.isNotEmpty ? imageResult.first : null;

      // If both results are empty, return null
      if (dataTitle == null && imageTitle == null) {
        return null;
      }

      // If one of the results is null, return the other
      if (dataTitle == null) {
        return imageTitle?['title'] as String?;
      }
      if (imageTitle == null) {
        return dataTitle['title'] as String?;
      }

      // Extract titles and timestamps
      final dataTitleStr = dataTitle['title'] as String?;
      final imageTitleStr = imageTitle['title'] as String?;
      final dataTimestamp = dataTitle['timestamp_column'] as String?;
      final imageTimestamp = imageTitle['timestamp_column'] as String?;

      // Convert timestamps to DateTime objects
      final dataDateTime = DateTime.parse(dataTimestamp!);
      final imageDateTime = DateTime.parse(imageTimestamp!);

      // Return the title of the entry with the most recent timestamp
      return dataDateTime.isAfter(imageDateTime) ? dataTitleStr : imageTitleStr;
    } catch (e) {
      // print('Error retrieving most recent title: $e');
      return null;
    }
  }
}
