import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:printing/printing.dart';
import 'package:flutter/material.dart';

class HistoryController extends GetxController {
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  var historyData = <Map<String, dynamic>>[].obs;
  var kebunList = <Map<String, dynamic>>[].obs;

  // Pagination states
  var currentPage = 0.obs;
  final int itemsPerPage = 10;

  final filterController = TextEditingController();
  var filteredData = <Map<String, dynamic>>[].obs;
  var selectedRows = <Map<String, dynamic>>[].obs;
  var isAllSelected = false.obs;

  List<Map<String, dynamic>> get paginatedData {
    final start = currentPage.value * itemsPerPage;
    final end = start + itemsPerPage;
    return filteredData.sublist(
      start,
      end > filteredData.length ? filteredData.length : end,
    );
  }

  @override
  void onInit() {
    super.onInit();
    fetchHistoryData();
    fetchKebunList();
    ever(historyData, (_) => applyFilter());
    filterController.addListener(applyFilter);
  }

  @override
  void onClose() {
    filterController.dispose();
    super.onClose();
  }

  Future<void> fetchHistoryData() async {
    try {
      final snapshot = await _firestore
          .collection('history_data')
          .orderBy('timestamp', descending: true)
          .get();

      historyData.value = snapshot.docs.map((doc) {
        final data = doc.data();
        return {
          'timestamp': data['timestamp'],
          'farm': data['farm'],
          'tanaman': data['tanaman'],
          'location': data['location'],
          'soil_moisture': data['soilMoisture'],
          'nitrogen': data['nitrogen'],
          'phosphorus': data['phosphorus'],
          'potassium': data['potassium'],
        };
      }).toList();
    } catch (e) {
      Get.snackbar("Error", "Failed to fetch history data: $e");
    }
  }

  Future<void> fetchKebunList() async {
    try {
      final snapshot = await _firestore.collection('kebun').get();
      kebunList.value = snapshot.docs.map((doc) {
        final data = doc.data();
        return {
          'id': doc.id,
          'nama_kebun': data['nama_kebun'],
          'tanaman': data['tanaman'],
        };
      }).toList();
    } catch (e) {
      Get.snackbar("Error", "Failed to fetch kebun data: $e");
    }
  }

  String getTanamanByFarm(String? farm) {
    if (farm == null) return '-';
    final kebun = kebunList.firstWhereOrNull((k) => k['nama_kebun'] == farm);
    return kebun?['tanaman'] ?? '-';
  }

  void nextPage() {
    if ((currentPage.value + 1) * itemsPerPage < historyData.length) {
      currentPage.value++;
    }
  }

  void previousPage() {
    if (currentPage.value > 0) {
      currentPage.value--;
    }
  }

  String formatTimestamp(Timestamp? timestamp) {
    if (timestamp == null) return "-";
    try {
      final date = timestamp.toDate();
      return DateFormat('dd MMM yyyy HH:mm').format(date);
    } catch (e) {
      return "-";
    }
  }

  void applyFilter() {
    final query = filterController.text.toLowerCase();
    if (query.isEmpty) {
      filteredData.assignAll(historyData);
    } else {
      filteredData.assignAll(historyData.where((item) {
        final farm = (item['farm'] ?? '').toString().toLowerCase();
        final tanaman = (item['tanaman'] ?? '').toString().toLowerCase();
        return farm.contains(query) || tanaman.contains(query);
      }));
    }
    // Reset selection on filter change
    selectedRows.clear();
    isAllSelected.value = false;
    update();
  }

  void toggleRowSelection(Map<String, dynamic> row) {
    if (selectedRows.contains(row)) {
      selectedRows.remove(row);
    } else {
      selectedRows.add(row);
    }
    isAllSelected.value = selectedRows.length == paginatedData.length && paginatedData.isNotEmpty;
    update();
  }

  void toggleSelectAll(bool select) {
    if (select) {
      selectedRows.assignAll(paginatedData);
    } else {
      selectedRows.clear();
    }
    isAllSelected.value = select;
    update();
  }

  Future<void> exportToPDF() async {
    // Hanya ekspor data yang dichecklist
    final dataToExport = selectedRows;
    final pdf = pw.Document();

    pdf.addPage(
      pw.MultiPage(
        pageFormat: PdfPageFormat.a4,
        build: (pw.Context context) {
          return [
            pw.Text('Riwayat Data', style: pw.TextStyle(fontSize: 24)),
            pw.SizedBox(height: 20),
            pw.Table.fromTextArray(
              headers: [
                'Datetime',
                'Farm',
                'Tanaman',
                'Location',
                'Soil Moisture (%)',
                'Nitrogen',
                'Phosphorus',
                'Potassium',
              ],
              data: dataToExport.map((data) {
                return [
                  formatTimestamp(data['timestamp']),
                  data['farm'] ?? '-',
                  getTanamanByFarm(data['farm']),
                  data['location'] ?? '-',
                  data['soil_moisture']?.toString() ?? '-',
                  data['nitrogen']?.toString() ?? '-',
                  data['phosphorus']?.toString() ?? '-',
                  data['potassium']?.toString() ?? '-',
                ];
              }).toList(),
              cellStyle: const pw.TextStyle(fontSize: 10),
              headerStyle: pw.TextStyle(
                  fontSize: 12, fontWeight: pw.FontWeight.bold),
              headerDecoration:
                  const pw.BoxDecoration(color: PdfColors.green100),
              border: pw.TableBorder.all(),
            ),
          ];
        },
      ),
    );

    await Printing.layoutPdf(
        onLayout: (PdfPageFormat format) async => pdf.save());
  }
}
