import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';

import '../controllers/history_controller.dart';

class HistoryView extends GetView<HistoryController> {
  const HistoryView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text(
          'Riwayat Data',
          style: GoogleFonts.poppins(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        centerTitle: true,
        backgroundColor: Colors.green,
        elevation: 0,
        automaticallyImplyLeading: true,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: Obx(() {
        if (controller.historyData.isEmpty) {
          return _buildNoDataView();
        }
        return Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // FILTER GABUNGAN
              TextField(
                controller: controller.filterController,
                decoration: InputDecoration(
                  hintText: 'Cari farm atau tanaman...',
                  prefixIcon: const Icon(Icons.search),
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12)),
                  contentPadding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                ),
                onChanged: (val) => controller.applyFilter(),
              ),
              const SizedBox(height: 16),
              Expanded(child: _buildHistorySection()),
            ],
          ),
        );
      }),
    );
  }

  Widget _buildNoDataView() {
    return Center(
      child: Text(
        "No data available",
        style: GoogleFonts.poppins(
          fontSize: 16,
          fontWeight: FontWeight.bold,
          color: Colors.grey,
        ),
      ),
    );
  }

  Widget _buildHistorySection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              "Tabel Data Riwayat",
              style: GoogleFonts.poppins(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
            FittedBox(
              child: ElevatedButton.icon(
                onPressed: controller.selectedRows.isNotEmpty
                    ? controller.exportToPDF
                    : null,
                icon: const Icon(Icons.picture_as_pdf,
                    size: 18, color: Colors.white),
                label: Text(
                  "Unduh",
                  style: GoogleFonts.poppins(
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.green,
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        Flexible(
          child: Container(
            decoration: _boxDecoration(),
            padding: const EdgeInsets.all(12),
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: ConstrainedBox(
                constraints: const BoxConstraints(minWidth: 1000),
                child: SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  child: DataTable(
                    columnSpacing: 16.0,
                    border: TableBorder.all(color: Colors.black26),
                    headingRowColor: MaterialStateColor.resolveWith(
                      (states) => const Color(0xFFC8E6C9),
                    ),
                    columns: _buildTableColumns(),
                    rows: controller.paginatedData.map(_buildDataRow).toList(),
                  ),
                ),
              ),
            ),
          ),
        ),
        const SizedBox(height: 16),
        _buildPaginationControls(),
      ],
    );
  }

  BoxDecoration _boxDecoration() {
    return BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(16),
      boxShadow: [
        BoxShadow(
          color: Colors.grey.withOpacity(0.15),
          blurRadius: 10,
          offset: const Offset(0, 4),
        ),
      ],
    );
  }

  List<DataColumn> _buildTableColumns() {
    return [
      DataColumn(
        label: Checkbox(
          value: controller.isAllSelected.value,
          onChanged: (val) => controller.toggleSelectAll(val ?? false),
        ),
      ),
      _tableColumn("Datetime"),
      _tableColumn("Farm"),
      _tableColumn("Tanaman"),
      _tableColumn("Location"),
      _tableColumn("Soil M (%)"),
      _tableColumn("N (ppm)"),
      _tableColumn("P (ppm)"),
      _tableColumn("K (ppm)"),
    ];
  }

  DataColumn _tableColumn(String label) {
    return DataColumn(
      label: Text(
        label,
        style: GoogleFonts.poppins(
          fontSize: 13,
          fontWeight: FontWeight.w600,
          color: Colors.black87,
        ),
      ),
    );
  }

  DataRow _buildDataRow(Map<String, dynamic> data) {
    final isSelected = controller.selectedRows.contains(data);
    return DataRow(
      cells: [
        DataCell(Checkbox(
          value: isSelected,
          onChanged: (val) => controller.toggleRowSelection(data),
        )),
        DataCell(_wrapText(controller.formatTimestamp(data["timestamp"]))),
        DataCell(_wrapText(data["farm"] ?? "-")),
        DataCell(_wrapText(controller.getTanamanByFarm(data["farm"]))),
        DataCell(_wrapText(data["location"] ?? "-")),
        DataCell(_wrapText("${data["soil_moisture"] ?? "-"}")),
        DataCell(_wrapText("${data["nitrogen"] ?? "-"}")),
        DataCell(_wrapText("${data["phosphorus"] ?? "-"}")),
        DataCell(_wrapText("${data["potassium"] ?? "-"}")),
      ],
    );
  }

  Widget _wrapText(String text) {
    return Text(
      text,
      overflow: TextOverflow.ellipsis,
      maxLines: 2,
      softWrap: true,
      style: GoogleFonts.poppins(fontSize: 10),
    );
  }

  Widget _buildPaginationControls() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        IconButton(
          onPressed:
              controller.currentPage.value > 0 ? controller.previousPage : null,
          icon: const Icon(Icons.arrow_back_ios),
          color: const Color(0xFF4E944F),
          iconSize: 28,
        ),
        const SizedBox(width: 16),
        Text(
          "Page ${controller.currentPage.value + 1}",
          style: GoogleFonts.poppins(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: const Color(0xFF4E944F),
          ),
        ),
        const SizedBox(width: 16),
        IconButton(
          onPressed:
              ((controller.currentPage.value + 1) * controller.itemsPerPage) <
                      controller.historyData.length
                  ? controller.nextPage
                  : null,
          icon: const Icon(Icons.arrow_forward_ios),
          color: const Color(0xFF4E944F),
          iconSize: 28,
        ),
      ],
    );
  }

  ButtonStyle _buttonStyle() {
    return ElevatedButton.styleFrom(
      backgroundColor: Colors.green,
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
      ),
    );
  }
}
