import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class DatabaseHelper {
  static final DatabaseHelper _instance = DatabaseHelper._internal();
  factory DatabaseHelper() => _instance;
  static Database? _database;

  DatabaseHelper._internal();

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

  Future<Database> _initDatabase() async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, 'history.db');

    return await openDatabase(
      path,
      version: 5, // Naikkan versi agar onUpgrade dijalankan
      onCreate: (db, version) async {
        print("📌 onCreate: Membuat database...");
        await db.execute('''
          CREATE TABLE IF NOT EXISTS history (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp TEXT NOT NULL,
            lampu INTEGER NOT NULL,
            kipas INTEGER NOT NULL,
            event TEXT NOT NULL
          )
        ''');

        await db.execute('''
          CREATE TABLE notifications (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp TEXT NOT NULL,
            event TEXT NOT NULL
          )
        ''');

        await db.execute('''
          CREATE TABLE angkakematian (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            tanggal TEXT NOT NULL,
            angka INTEGER NOT NULL,
            kloter INTEGER NOT NULL
          )
        ''');
      },
       onUpgrade: (db, oldVersion, newVersion) async {
        print("📌 onUpgrade: Upgrade database dari versi $oldVersion ke $newVersion...");
        if (oldVersion < 5) {
          await db.execute('DROP TABLE IF EXISTS notifications');
          await db.execute('''
            CREATE TABLE IF NOT EXISTS notifications (
              id INTEGER PRIMARY KEY AUTOINCREMENT,
              timestamp TEXT NOT NULL,
              event TEXT NOT NULL
            )
          ''');
        }
        if (oldVersion < 5) {
          await db.execute('DROP TABLE IF EXISTS angkakematian');
          await db.execute('''
            CREATE TABLE IF NOT EXISTS angkakematian (
              id INTEGER PRIMARY KEY AUTOINCREMENT,
              tanggal TEXT NOT NULL,
              angka INTEGER NOT NULL,
              kloter INTEGER NOT NULL
            )
          ''');
          print("✅ Tabel angkakematian berhasil dibuat di upgrade.");
        }
        if (oldVersion < 5) {
          await db.execute('''
            ALTER TABLE angkakematian ADD COLUMN kloter INTEGER;
          ''');
        }
      },
    );
  }

  Future<void> insertAngkaKematian(Map<String, dynamic> data) async {
    final db = await database;
    try {
      await db.insert('angkakematian', data);
      print("✅ Data angka kematian berhasil disimpan: $data");
    } catch (e) {
      print("❌ Gagal menyimpan angka kematian: $e");
    }
  }

  Future<List<Map<String, dynamic>>> getAngkaKematian() async {
    final db = await database;
    return await db.query('angkakematian', orderBy: 'id DESC');
  }

  // 🔹 DEBUG: Cek apakah tabel notifications sudah ada
  Future<void> checkTables() async {
    final db = await database;
    List<Map<String, dynamic>> tables = await db.rawQuery(
        "SELECT name FROM sqlite_master WHERE type='table' AND name='notifications'");
    if (tables.isEmpty) {
      print("⚠️ Tabel notifications belum ada. Membuat tabel...");
      await db.execute('''
        CREATE TABLE IF NOT EXISTS notifications (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          timestamp TEXT NOT NULL,
          event TEXT NOT NULL
        )
      ''');
      print("✅ Tabel notifications berhasil dibuat.");
    } else {
      print("✅ Tabel notifications sudah ada.");
      
      // Debug: tampilkan jumlah record
      List<Map<String, dynamic>> count = await db.rawQuery("SELECT COUNT(*) as count FROM notifications");
      print("📊 Jumlah record di tabel notifications: ${count.first['count']}");
      
      // Debug: tampilkan beberapa record terakhir
      List<Map<String, dynamic>> lastRecords = await db.query(
        'notifications',
        orderBy: 'id DESC',
        limit: 5
      );
      if (lastRecords.isNotEmpty) {
        print("📊 5 record terakhir: $lastRecords");
      } else {
        print("📊 Belum ada record di tabel notifications");
      }
    }
  }

  // 🔹 INSERT DATA KE HISTORY
  Future<void> insertHistory(Map<String, dynamic> data) async {
    final db = await database;
    try {
      await db.insert('history', data);
      print("✅ Data history berhasil disimpan: $data");
    } catch (e) {
      print("❌ Gagal menyimpan history: $e");
    }
  }

  // 🔹 GET DATA HISTORY
  Future<List<Map<String, dynamic>>> getHistory() async {
    final db = await database;
    return await db.query('history', orderBy: 'id DESC');
  }

  // 🔹 INSERT DATA KE NOTIFICATIONS (Format sudah sesuai tabel)
  Future<void> insertNotification(String event) async {
    final db = await database;
    String timestamp = DateTime.now().toIso8601String();
    try {
      // Periksa apakah tabel notifications ada
      List<Map<String, dynamic>> tables = await db.rawQuery(
          "SELECT name FROM sqlite_master WHERE type='table' AND name='notifications'");
      
      if (tables.isEmpty) {
        print("⚠️ Tabel notifications belum ada saat menyimpan notifikasi. Membuat tabel...");
        await db.execute('''
          CREATE TABLE IF NOT EXISTS notifications (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp TEXT NOT NULL,
            event TEXT NOT NULL
          )
        ''');
      }
      
      int id = await db.insert('notifications', {
        'timestamp': timestamp,
        'event': event,
      });
      print("✅ Notifikasi berhasil disimpan dengan ID: $id, Event: $event");
    } catch (e) {
      print("❌ Gagal menyimpan notifikasi: $e");
    }
  }

  // 🔹 GET DATA NOTIFICATIONS
  Future<List<Map<String, dynamic>>> getNotifications() async {
    final db = await database;
    try {
      // Periksa apakah tabel notifications ada
      List<Map<String, dynamic>> tables = await db.rawQuery(
          "SELECT name FROM sqlite_master WHERE type='table' AND name='notifications'");
      
      if (tables.isEmpty) {
        print("⚠️ Tabel notifications belum ada. Membuat tabel...");
        await db.execute('''
          CREATE TABLE IF NOT EXISTS notifications (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            timestamp TEXT NOT NULL,
            event TEXT NOT NULL
          )
        ''');
        print("✅ Tabel notifications berhasil dibuat.");
        return [];
      }
      
      List<Map<String, dynamic>> result = await db.query(
        'notifications',
        orderBy: 'id DESC',
      );
      print("✅ Data notifikasi yang diambil: ${result.length} item");
      
      // Debug: tampilkan beberapa data notifikasi terakhir
      if (result.isNotEmpty) {
        print("📊 Data notifikasi terakhir: ${result.first}");
      }
      
      return result;
    } catch (e) {
      print("❌ Error saat mengambil data notifikasi: $e");
      return [];
    }
  }

  // 🔹 DELETE ALL NOTIFICATIONS
  Future<void> clearNotifications() async {
    final db = await database;
    await db.delete('notifications');
    print("✅ Semua notifikasi berhasil dihapus");
  }

  // 🔹 Hapus database (Gunakan ini jika ingin reset database manual)
  Future<void> resetDatabase() async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, 'history.db');
    await deleteDatabase(path);
    print("✅ Database berhasil dihapus.");
  }

  Future<void> deleteAngkaKematian(String tanggal, String kloter) async {
    final db = await database;
    await db.delete(
      'angkakematian',
      where: 'tanggal = ? AND kloter = ?',
      whereArgs: [tanggal, kloter],
    );
    print("✅ Data angka kematian dengan tanggal $tanggal dan kloter $kloter berhasil dihapus.");
  }

  Future<void> deleteAngkaKematianByKloter(String kloter) async {
    final db = await database;
    await db.delete('angkakematian', where: 'kloter = ?', whereArgs: [kloter]);
  }
}
