import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import '../controllers/mode_controller.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';

class ModeView extends StatefulWidget {
  const ModeView({Key? key}) : super(key: key);

  @override
  State<ModeView> createState() => _ModeViewState();
}

class _ModeViewState extends State<ModeView> {
  late final ModeController controller;

  @override
  void initState() {
    super.initState();
    controller = Get.put(ModeController());
    controller.getCurrentLocation();
  }

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final pos = controller.currentPosition.value;
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text(
          'Mode Kontrol Alat',
          style: GoogleFonts.poppins(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        centerTitle: true, // ✅ Biar teks rata tengah
        backgroundColor: Colors.green, // ✅ Background hijau
        elevation: 0,
        automaticallyImplyLeading: true, // ✅ Biar ada tombol back
        iconTheme: const IconThemeData(
          color: Colors.white, // ✅ Warna icon back putih
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Pilih Mode', style: GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.w500)),
            const SizedBox(height: 8),
            GestureDetector(
              onTap: () => _showModelChoiceBottomSheet(context, controller),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey.shade300),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Obx(() => Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('Mode ${controller.mode.value}', style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
                    const Icon(Icons.arrow_forward_ios, size: 16),
                  ],
                )),
              ),
            ),
            const SizedBox(height: 24),

           Obx(() => controller.mode.value == 'Auto'
    ? Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Nilai Sensor', style: GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.w500)),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildSensorBox('P', 'Phospor', controller.phosphorus.value),
              _buildSensorBox('N', 'Nitrogen', controller.nitrogen.value),
              _buildSensorBox('K', 'Kalium', controller.potassium.value),
            ],
          ),
          const SizedBox(height: 24),
          _buildSoilMoisture(controller.soilMoisture.value),
          const SizedBox(height: 24),
        ],
      )
    : const SizedBox()),


            // ❗ Kalau mode Manual, tampilkan inputan
Obx(() => controller.mode.value == 'Manual'
    ? Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
           Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            elevation: 4,
            color: Colors.green.shade100, // Light green background
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: Row(
                children: [
                  Icon(
                    Icons.warning, // Warning icon
                    color: Colors.yellow.shade700, // Icon color
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      'Masukkan semua nilai yang akan disimpan berdasarkan nilai yang sudah tercantum di alat secara manual.',
                      style: GoogleFonts.poppins(
                        fontSize: 12,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 4),
            child: Column(
              children: [
                Row(
                  children: [
                    Expanded(
                      child: _buildLabeledInput(
                        label: 'Nilai N',
                        hint: 'Masukkan Nilai N',
                        controller: controller.manualNitrogenController,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: _buildLabeledInput(
                        label: 'Nilai P',
                        hint: 'Masukkan Nilai P',
                        controller: controller.manualPhosphorusController,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                Row(
                  children: [
                    Expanded(
                      child: _buildLabeledInput(
                        label: 'Nilai K',
                        hint: 'Masukkan Nilai K',
                        controller: controller.manualPotassiumController,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: _buildLabeledInput(
                        label: 'Soil Moisture',
                        hint: 'Masukkan Soil Moisture',
                        controller: controller.manualSoilMoistureController,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          const SizedBox(height: 24),
        ],
      )
    : const SizedBox()),



            Text(
  'Kebun',
  style: GoogleFonts.poppins(
    fontSize: 14,
    fontWeight: FontWeight.w500,
  ),
),
const SizedBox(height: 8),
Obx(() => DropdownButtonFormField<String>(
      value: controller.selectedKebun.value.isNotEmpty
          ? controller.selectedKebun.value
          : null,
      items: controller.kebunList
          .map((kebun) => DropdownMenuItem(
                value: kebun,
                child: Text(
                  kebun,
                  style: GoogleFonts.poppins(fontSize: 14),
                ),
              ))
          .toList(),
      onChanged: (value) {
        controller.selectedKebun.value = value!;
        controller.farmController.text = value;
      },
      icon: const Icon(Icons.arrow_drop_down_rounded), // custom icon
      dropdownColor: Colors.white, // warna background dropdown
      decoration: InputDecoration(
        filled: true,
        fillColor: Colors.white, // background form field
        contentPadding: const EdgeInsets.symmetric(
          vertical: 14,
          horizontal: 12,
        ),
        hintText: 'Pilih Nama Kebun',
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Colors.grey),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: const BorderSide(color: Colors.grey),
        ),
      ),
    )),

            const SizedBox(height: 16),
            Text('Lokasi', style: GoogleFonts.poppins(fontSize: 14, fontWeight: FontWeight.w500)),
            const SizedBox(height: 8),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: controller.locationController,
                    readOnly: true,
                    decoration: InputDecoration(
                      hintText: 'Koordinat lokasi',
                      hintStyle: GoogleFonts.poppins(),
                      border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                    ),
                  ),
                ),
                const SizedBox(width: 8),
                ElevatedButton.icon(
                  onPressed: () async {
                    await controller.getCurrentLocation();
                    setState(() {}); // agar widget rebuild dan posisi terbaru tampil
                  },
                  icon: const Icon(Icons.my_location),
                  label: const Text('Lokasi Terkini'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.green,
                    foregroundColor: Colors.white,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            pos == null
                ? Center(child: Padding(
                    padding: EdgeInsets.symmetric(vertical: 24),
                    child: CircularProgressIndicator(),
                  ))
                : MyGoogleMapWidget(position: pos),
            const SizedBox(height: 32),
            SizedBox(
              width: screenWidth,
              child: ElevatedButton(
                onPressed: controller.saveModeData,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.green,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                ),
                child: Text('Simpan', style: GoogleFonts.poppins(color: Colors.white, fontWeight: FontWeight.w600)),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSensorBox(String label, String title, double value) {
    Color boxColor;
    Color textColor;
    switch (label) {
      case 'N':
        boxColor = Colors.red;
        textColor = Colors.red;
        break;
      case 'P':
        boxColor = Colors.blue;
        textColor = Colors.blue;
        break;
      case 'K':
        boxColor = Colors.green;
        textColor = Colors.green;
        break;
      default:
        boxColor = const Color(0xFFA5D6A7);
        textColor = Colors.black;
    }
    return Column(
      children: [
        Container(
          width: 60,
          height: 60,
          decoration: BoxDecoration(
            color: boxColor,
            borderRadius: BorderRadius.circular(12),
          ),
          child: Center(
            child: Text(label, style: GoogleFonts.poppins(fontWeight: FontWeight.bold, fontSize: 18, color: Colors.white)),
          ),
        ),
        const SizedBox(height: 8),
        Text(
          title,
          style: GoogleFonts.poppins(fontSize: 12, fontWeight: FontWeight.w500, color: textColor),
        ),
        const SizedBox(height: 4),
        RichText(
          text: TextSpan(
            children: [
              TextSpan(
                text: '${value.toStringAsFixed(0)}',
                style: GoogleFonts.poppins(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black),
              ),
              TextSpan(
                text: ' ppm',
                style: GoogleFonts.poppins(fontSize: 12, color: Colors.black),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildLabeledInput({
    required String label,
    required String hint,
    required TextEditingController controller,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: GoogleFonts.poppins(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: Colors.black,
          ),
        ),
        const SizedBox(height: 4),
        TextField(
          controller: controller,
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            hintText: hint,
            hintStyle: GoogleFonts.poppins(fontSize: 12),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
          ),
        ),
      ],
    );
  }


Widget _buildSoilMoisture(double value) {
  return Container(
    padding: const EdgeInsets.all(16),
    decoration: BoxDecoration(
      color: const Color(0xFFB3E5FC), // Biru muda
      borderRadius: BorderRadius.circular(12),
    ),
    child: Row(
      children: [
        const Icon(Icons.water_drop_outlined, color: Colors.blue),
        const SizedBox(width: 8),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Soil Moisture',
              style: GoogleFonts.poppins(fontSize: 12, fontWeight: FontWeight.w500),
            ),
            RichText(
              text: TextSpan(
                children: [
                  TextSpan(
                    text: '${value.toStringAsFixed(0)}', // Nilai data besar
                    style: GoogleFonts.poppins(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black),
                  ),
                  TextSpan(
                    text: ' %', // Satuan kecil
                    style: GoogleFonts.poppins(fontSize: 12, color: Colors.black),
                  ),
                ],
              ),
            ),
          ],
        ),
      ],
    ),
  );
}


  Widget _buildManualInputField(String hint, TextEditingController controller) {
    return TextField(
      controller: controller,
      keyboardType: TextInputType.number,
      decoration: InputDecoration(
        hintText: hint,
        hintStyle: GoogleFonts.poppins(),
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
      ),
    );
  }

  void _showModelChoiceBottomSheet(BuildContext context, ModeController controller) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
      ),
      builder: (context) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const SizedBox(height: 16),
            ListTile(
              title: const Text('Auto'),
              onTap: () {
                controller.setMode('Auto');
                Get.back();
              },
            ),
            ListTile(
              title: const Text('Manual'),
              onTap: () {
                controller.setMode('Manual');
                Get.back();
              },
            ),
            const SizedBox(height: 16),
          ],
        );
      },
    );
  }
}

class MyGoogleMapWidget extends StatefulWidget {
  final Position position;
  const MyGoogleMapWidget({Key? key, required this.position}) : super(key: key);

  @override
  State<MyGoogleMapWidget> createState() => _MyGoogleMapWidgetState();
}

class _MyGoogleMapWidgetState extends State<MyGoogleMapWidget> {
  late GoogleMapController _mapController;
  double _currentZoom = 16;
  MapType _mapType = MapType.normal;

  void _onMapCreated(GoogleMapController controller) {
    _mapController = controller;
  }

  void _zoomIn() {
    setState(() {
      _currentZoom += 1;
      _mapController.animateCamera(CameraUpdate.zoomTo(_currentZoom));
    });
  }

  void _zoomOut() {
    setState(() {
      _currentZoom -= 1;
      _mapController.animateCamera(CameraUpdate.zoomTo(_currentZoom));
    });
  }

  void _toggleMapType() {
    setState(() {
      _mapType = _mapType == MapType.normal ? MapType.satellite : MapType.normal;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 6,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      margin: const EdgeInsets.symmetric(vertical: 8),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(16),
        child: SizedBox(
          height: 220,
          child: Stack(
            children: [
              GoogleMap(
                onMapCreated: _onMapCreated,
                initialCameraPosition: CameraPosition(
                  target: LatLng(widget.position.latitude, widget.position.longitude),
                  zoom: _currentZoom,
                ),
                markers: {
                  Marker(
                    markerId: const MarkerId('current'),
                    position: LatLng(widget.position.latitude, widget.position.longitude),
                    infoWindow: const InfoWindow(title: 'Lokasi Terkini'),
                    icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueAzure),
                  ),
                },
                myLocationEnabled: true,
                myLocationButtonEnabled: false,
                zoomControlsEnabled: false,
                mapType: _mapType,
                compassEnabled: true,
                tiltGesturesEnabled: true,
                trafficEnabled: false,
              ),
              Positioned(
                bottom: 16,
                right: 16,
                child: Column(
                  children: [
                    FloatingActionButton(
                      heroTag: 'zoom_in',
                      mini: true,
                      backgroundColor: Colors.white,
                      onPressed: _zoomIn,
                      child: const Icon(Icons.add, color: Colors.black),
                    ),
                    const SizedBox(height: 8),
                    FloatingActionButton(
                      heroTag: 'zoom_out',
                      mini: true,
                      backgroundColor: Colors.white,
                      onPressed: _zoomOut,
                      child: const Icon(Icons.remove, color: Colors.black),
                    ),
                    const SizedBox(height: 8),
                    FloatingActionButton(
                      heroTag: 'map_type',
                      mini: true,
                      backgroundColor: Colors.white,
                      onPressed: _toggleMapType,
                      child: Icon(_mapType == MapType.normal ? Icons.satellite : Icons.map, color: Colors.black),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
