import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import '../controllers/home_controller.dart';
import '../../../widgets/history_card.dart'; // asumsi kamu punya card khusus di widgets
import 'package:intl/intl.dart'; // buat format tanggal
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fl_chart/fl_chart.dart';

class HomeView extends StatelessWidget {
  const HomeView({super.key});

  @override
  Widget build(BuildContext context) {
    final HomeController controller = Get.put(HomeController());
    double screenWidth = MediaQuery.of(context).size.width;

    String todayDate = DateFormat('d MMMM yyyy', 'id_ID').format(DateTime.now());

    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(screenWidth * 0.05),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // USERNAME DAN NOTIF
                Row(
                  children: [
                    Expanded(
                      child: Obx(() => Text(
                            controller.username.value,
                            style: GoogleFonts.poppins(
                              fontSize: 24,
                              fontWeight: FontWeight.bold,
                            ),
                          )),
                    ),
                    IconButton(
  icon: const Icon(Icons.notifications),
  onPressed: controller.keNotifikasi, // <-- GANTI ini!
),

                  ],
                ),
                const SizedBox(height: 4),
                // TANGGAL SEKARANG
                Text(
                  todayDate,
                  style: GoogleFonts.poppins(
                    fontSize: 14,
                    color: Colors.grey,
                  ),
                ),
                const SizedBox(height: 20),

                // STATUS KONEKSI
                Text(
                  "Status Koneksi",
                  style: GoogleFonts.poppins(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 10),
                Container(
  padding: const EdgeInsets.all(16),
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(16),
    border: Border.all(color: Colors.grey.shade200),
  ),
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: [
      Expanded(
        child: _buildConnectionStatus(
          icon: Icons.wifi,
          title: 'Internet',
          status: controller.internetStatus,
          onlineText: 'Connected',
          offlineText: 'Disconnected',
        ),
      ),
      const VerticalDivider(
        thickness: 1,
        color: Colors.grey,
      ),
      Expanded(
        child: _buildConnectionStatus(
          icon: Icons.device_hub,
          title: 'Koneksi Alat',
          status: controller.koneksiAlat,
          onlineText: 'Connect',
          offlineText: 'Disconnect',
        ),
      ),
    ],
  ),
),

const SizedBox(height: 20),

// GRAFIK DATA
Text(
  "Grafik Data",
  style: GoogleFonts.poppins(
    fontSize: 18,
    fontWeight: FontWeight.bold,
  ),
),
const SizedBox(height: 10),
// LEGEND
Padding(
  padding: const EdgeInsets.only(bottom: 8),
  child: Center(
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildLegendDot(Colors.blue, 'Nitrogen (N)'),
            const SizedBox(width: 32),
            _buildLegendDot(Colors.green, 'Kalium (K)'),
          ],
        ),
        const SizedBox(height: 8),
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildLegendDot(Colors.orange, 'Phosphorus (P)'),
            const SizedBox(width: 32),
            _buildLegendDot(Colors.lightBlue.shade200, 'Soil Moisture'),
          ],
        ),
      ],
    ),
  ),
),
const SizedBox(height: 8),
Obx(() {
  if (controller.chartData.isEmpty) {
    return const Center(child: CircularProgressIndicator());
  }

  List<FlSpot> nitrogenSpots = [];
  List<FlSpot> phosphorusSpots = [];
  List<FlSpot> potassiumSpots = [];
  List<FlSpot> soilMoistureSpots = [];

  for (int i = 0; i < controller.chartData.length; i++) {
    nitrogenSpots.add(FlSpot(i.toDouble(), controller.chartData[i]['nitrogen']));
    phosphorusSpots.add(FlSpot(i.toDouble(), controller.chartData[i]['phosphorus']));
    potassiumSpots.add(FlSpot(i.toDouble(), controller.chartData[i]['potassium']));
    soilMoistureSpots.add(FlSpot(i.toDouble(), controller.chartData[i]['soil_moisture']));
  }

  return SizedBox(
    height: 250,
    child: Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      child: LineChart(
        LineChartData(
          minY: 0, 
          gridData: FlGridData(show: true, drawVerticalLine: true),
          titlesData: FlTitlesData(
            leftTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                reservedSize: 30,
                interval: 20, 
                getTitlesWidget: (value, meta) {
                  return Text(
                    value.toInt().toString(),
                    style: const TextStyle(fontSize: 10),
                    textAlign: TextAlign.right,
                  );
                },
              ),
            ),
            bottomTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                interval: 1,
                getTitlesWidget: (value, meta) {
                  if (value.toInt() >= 0 && value.toInt() < controller.chartData.length) {
                    var timestamp = controller.chartData[value.toInt()]['timestamp'];
                    if (timestamp != null) {
                      String hour = timestamp.hour.toString().padLeft(2, '0');
                      String minute = timestamp.minute.toString().padLeft(2, '0');
                      return Text(
                        "$hour:$minute",
                        style: const TextStyle(fontSize: 10),
                      );
                    } else {
                      return const Text("?", style: TextStyle(fontSize: 10));
                    }
                  }
                  return const Text("");
                },
              ),
            ),
            topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
            rightTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
          ),
          borderData: FlBorderData(
            show: true,
            border: const Border(
              left: BorderSide(color: Colors.black),
              bottom: BorderSide(color: Colors.black),
            ),
          ),
          lineBarsData: [
            LineChartBarData(
              spots: nitrogenSpots,
              isCurved: true,
              color: Colors.blue,
              barWidth: 2,
              dotData: FlDotData(show: false),
              belowBarData: BarAreaData(show: true, color: Colors.blue.withOpacity(0.15)),
            ),
            LineChartBarData(
              spots: phosphorusSpots,
              isCurved: true,
              color: Colors.orange,
              barWidth: 2,
              dotData: FlDotData(show: false),
              belowBarData: BarAreaData(show: true, color: Colors.orange.withOpacity(0.15)),
            ),
            LineChartBarData(
              spots: potassiumSpots,
              isCurved: true,
              color: Colors.green,
              barWidth: 2,
              dotData: FlDotData(show: false),
              belowBarData: BarAreaData(show: true, color: Colors.green.withOpacity(0.15)),
            ),
            LineChartBarData(
              spots: soilMoistureSpots,
              isCurved: true,
              color: Colors.lightBlue,
              barWidth: 2,
              dotData: FlDotData(show: false),
              belowBarData: BarAreaData(show: true, color: Colors.lightBlue.shade100.withOpacity(0.5)),
            ),
          ],
        ),
      ),
    ),
  );
}),



                const SizedBox(height: 20),

                // RIWAYAT
                Row(
                  children: [
                    Text(
                      "Riwayat",
                      style: GoogleFonts.poppins(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const Spacer(),
                    GestureDetector(
                      onTap: controller.keRiwayat,

                      child: Text(
                        "Selengkapnya",
                        style: GoogleFonts.poppins(
                          fontSize: 14,
                          color: Colors.green,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                // GUNAKAN HISTORY CARD
Obx(() {
  final limitedHistory = controller.historyList.take(3).toList(); // <= sudah bener ambil 3
  return Column(
    children: limitedHistory.map((doc) {
      return HistoryCard(
        title: doc['title'] ?? 'Cek kondisi tanah',
        farmName: doc['farm'] ?? 'No Farm Name',
        timestamp: formatTimestamp(doc['timestamp']),
        onTap: () {
          showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
                title: Row(
                  children: [
                    const Icon(Icons.history, color: Colors.green),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        doc['title'] ?? 'Detail Riwayat',
                        style: GoogleFonts.poppins(fontWeight: FontWeight.bold),
                      ),
                    ),
                  ],
                ),
                content: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          const Icon(Icons.eco, color: Colors.green, size: 18),
                          const SizedBox(width: 6),
                          Text('Kebun:', style: GoogleFonts.poppins(fontWeight: FontWeight.w600)),
                          const SizedBox(width: 4),
                          Expanded(child: Text(doc['farm'] ?? '-', style: GoogleFonts.poppins())),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Row(
                        children: [
                          const Icon(Icons.access_time, color: Colors.blue, size: 18),
                          const SizedBox(width: 6),
                          Text('Waktu:', style: GoogleFonts.poppins(fontWeight: FontWeight.w600)),
                          const SizedBox(width: 4),
                          Expanded(child: Text(formatTimestamp(doc['timestamp']), style: GoogleFonts.poppins())),
                        ],
                      ),
                      const Divider(height: 20, thickness: 1),
                      Text('Data Sensor', style: GoogleFonts.poppins(fontWeight: FontWeight.bold, color: Colors.green)),
                      const SizedBox(height: 8),
                      ..._buildDynamicSensorRows(doc),
                      const Divider(height: 20, thickness: 1),
                      if (doc['latitude'] != null && doc['longitude'] != null)
                        Row(
                          children: [
                            const Icon(Icons.location_on, color: Colors.orange, size: 18),
                            const SizedBox(width: 6),
                            Text('Lokasi:', style: GoogleFonts.poppins(fontWeight: FontWeight.w600)),
                            const SizedBox(width: 4),
                            Expanded(child: Text('${doc['latitude']}, ${doc['longitude']}', style: GoogleFonts.poppins())),
                          ],
                        ),
                    ],
                  ),
                ),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(),
                    child: const Text('Tutup'),
                  ),
                ],
              );
            },
          );
        },
      );
    }).toList(),
  );
}),



              ],
            ),
          ),
        ),
      ),
    );
  }

 Widget _buildConnectionStatus({
  required IconData icon,
  required String title,
  required RxBool status,
  required String onlineText,
  required String offlineText,
}) {
  return Obx(() => Row(
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
      Container(
        padding: const EdgeInsets.all(6),
        decoration: BoxDecoration(
          color: status.value ? Colors.green : Colors.red,
          shape: BoxShape.circle,
        ),
        child: Icon(icon, color: Colors.white, size: 16),
      ),
      const SizedBox(width: 12),
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: GoogleFonts.poppins(
              fontSize: 14,
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(
            status.value ? onlineText : offlineText,
            style: GoogleFonts.poppins(
              fontSize: 12,
              color: Colors.grey[700],
            ),
          ),
        ],
      ),
    ],
  ));
}



  String formatTimestamp(Timestamp timestamp) {
    DateTime date = timestamp.toDate();
    return "${date.day} ${_getMonthName(date.month)} ${date.year} ${date.hour.toString().padLeft(2, '0')}.${date.minute.toString().padLeft(2, '0')}";
  }

  String _getMonthName(int month) {
    const months = [
      "Januari", "Februari", "Maret", "April", "Mei", "Juni",
      "Juli", "Agustus", "September", "Oktober", "November", "Desember"
    ];
    return months[month - 1];
  }

  Widget _buildDetailRow(String label, String value, IconData icon, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        children: [
          Icon(icon, color: color, size: 18),
          const SizedBox(width: 6),
          Text('$label:', style: GoogleFonts.poppins(fontWeight: FontWeight.w600)),
          const SizedBox(width: 4),
          Expanded(child: Text(value, style: GoogleFonts.poppins())),
        ],
      ),
    );
  }

  List<Widget> _buildDynamicSensorRows(Map<String, dynamic> doc) {
    // Field yang tidak perlu ditampilkan sebagai sensor
    const exclude = {'title', 'farm', 'timestamp', 'location', 'latitude', 'longitude'};
    // Map field ke label dan icon
    final Map<String, Map<String, dynamic>> sensorMeta = {
      'nitrogen': {'label': 'Nitrogen', 'icon': Icons.science, 'color': Colors.red},
      'phosphorus': {'label': 'Phosphorus', 'icon': Icons.science, 'color': Colors.blue},
      'potassium': {'label': 'Kalium', 'icon': Icons.science, 'color': Colors.green},
      'soilMoisture': {'label': 'Soil Moisture', 'icon': Icons.water_drop, 'color': Colors.brown, 'suffix': ' %'},
      'ec': {'label': 'EC', 'icon': Icons.bolt, 'color': Colors.deepPurple},
      'suhu': {'label': 'Suhu', 'icon': Icons.thermostat, 'color': Colors.orange, 'suffix': ' °C'},
      'kelembaban': {'label': 'Kelembaban', 'icon': Icons.water, 'color': Colors.blueGrey, 'suffix': ' %'},
    };
    List<Widget> rows = [];
    for (final entry in doc.entries) {
      final key = entry.key;
      if (exclude.contains(key)) continue;
      final meta = sensorMeta[key];
      final label = meta != null ? meta['label'] : key;
      final icon = meta != null ? meta['icon'] as IconData : Icons.data_object;
      final color = meta != null ? meta['color'] as Color : Colors.grey;
      final suffix = meta != null && meta['suffix'] != null ? meta['suffix'] as String : '';
      rows.add(_buildDetailRow(label, entry.value.toString() + suffix, icon, color));
    }
    if (rows.isEmpty) {
      rows.add(Text('Tidak ada data sensor.', style: GoogleFonts.poppins(color: Colors.grey)));
    }
    return rows;
  }

  Widget _buildLegendDot(Color color, String label) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 12,
          height: 12,
          decoration: BoxDecoration(
            color: color,
            shape: BoxShape.circle,
          ),
        ),
        const SizedBox(width: 4),
        Text(label, style: GoogleFonts.poppins(fontSize: 12)),
      ],
    );
  }
}
