// lib/screens/river/investigative/manual_sampling/river_inves_in_situ_step_1_sampling_info.dart

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:intl/intl.dart';
import 'package:simple_barcode_scanner/simple_barcode_scanner.dart';

import '../../../../auth_provider.dart';
import '../../../../models/river_inves_manual_sampling_data.dart';
import '../../../../services/river_investigative_sampling_service.dart';

class RiverInvesStep1SamplingInfo extends StatefulWidget {
  final RiverInvesManualSamplingData data;
  final VoidCallback onNext;

  const RiverInvesStep1SamplingInfo({
    super.key,
    required this.data,
    required this.onNext,
  });

  @override
  State<RiverInvesStep1SamplingInfo> createState() =>
      _RiverInvesStep1SamplingInfoState();
}

class _RiverInvesStep1SamplingInfoState extends State<RiverInvesStep1SamplingInfo> {
  final _formKey = GlobalKey<FormState>();
  bool _isLoadingLocation = false;

  // New flag to track if user manually typed the location
  bool _isManualLocationEntry = false;

  late final TextEditingController _firstSamplerController;
  late final TextEditingController _dateController;
  late final TextEditingController _timeController;
  late final TextEditingController _barcodeController;
  late final TextEditingController _stationLatController;
  late final TextEditingController _stationLonController;
  late final TextEditingController _currentLatController;
  late final TextEditingController _currentLonController;

  // --- NEW: Controllers for New Location ---
  late final TextEditingController _newStateController;
  late final TextEditingController _newBasinController;
  late final TextEditingController _newRiverController;
  late final TextEditingController _newStationCodeController;

  List<String> _statesList = [];
  List<Map<String, dynamic>> _manualStationsForState = [];
  List<Map<String, dynamic>> _triennialStationsForState = [];
  final List<String> _stationTypes = [
    'Existing Manual Station',
    'Existing Triennial Station',
    'New Location'
  ];

  @override
  void initState() {
    super.initState();
    _initializeControllers();
    _initializeForm();
  }

  @override
  void dispose() {
    _firstSamplerController.dispose();
    _dateController.dispose();
    _timeController.dispose();
    _barcodeController.dispose();
    _stationLatController.dispose();
    _stationLonController.dispose();
    _currentLatController.dispose();
    _currentLonController.dispose();
    _newStateController.dispose();
    _newBasinController.dispose();
    _newRiverController.dispose();
    _newStationCodeController.dispose();
    super.dispose();
  }

  void _initializeControllers() {
    _firstSamplerController = TextEditingController();
    _dateController = TextEditingController();
    _timeController = TextEditingController();
    _barcodeController = TextEditingController(text: widget.data.sampleIdCode);
    _stationLatController = TextEditingController(text: widget.data.stationLatitude);
    _stationLonController = TextEditingController(text: widget.data.stationLongitude);
    _currentLatController = TextEditingController(text: widget.data.currentLatitude);
    _currentLonController = TextEditingController(text: widget.data.currentLongitude);
    // New Location controllers
    _newStateController = TextEditingController(text: widget.data.newStateName);
    _newBasinController = TextEditingController(text: widget.data.newBasinName);
    _newRiverController = TextEditingController(text: widget.data.newRiverName);
    _newStationCodeController = TextEditingController(text: widget.data.newStationCode);
  }

  void _initializeForm() {
    final auth = Provider.of<AuthProvider>(context, listen: false);

    widget.data.firstSamplerName = auth.profileData?['first_name'] ?? 'Current User';
    widget.data.firstSamplerUserId = auth.profileData?['user_id'];
    _firstSamplerController.text = widget.data.firstSamplerName!;

    final now = DateTime.now();
    if (widget.data.samplingDate == null || widget.data.samplingDate!.isEmpty) {
      widget.data.samplingDate = DateFormat('yyyy-MM-dd').format(now);
      widget.data.samplingTime = DateFormat('HH:mm:ss').format(now);
    }
    _dateController.text = widget.data.samplingDate!;
    _timeController.text = widget.data.samplingTime!;

    // Populate states list logic (same as before)
    final allManualStations = auth.riverManualStations ?? [];
    if (allManualStations.isNotEmpty) {
      final states = allManualStations
          .map((s) => s['state_name'] as String?)
          .whereType<String>()
          .toSet()
          .toList();
      states.sort();
      setState(() {
        _statesList = states;
      });
    } else {
      final allTriennialStations = auth.riverTriennialStations ?? [];
      if (allTriennialStations.isNotEmpty) {
        final states = allTriennialStations
            .map((s) => s['state_name'] as String?)
            .whereType<String>()
            .toSet()
            .toList();
        states.sort();
        setState(() { _statesList = states; });
      } else {
        final generalStates = auth.states ?? [];
        final states = generalStates
            .map((s) => s['state_name'] as String?)
            .whereType<String>()
            .toSet()
            .toList();
        states.sort();
        setState(() { _statesList = states; });
      }
    }

    _loadStationsForSelectedState();
    _calculateDistance();
  }

  void _loadStationsForSelectedState() {
    if (widget.data.selectedStateName == null) return;

    final auth = Provider.of<AuthProvider>(context, listen: false);
    final allManualStations = auth.riverManualStations ?? [];
    final allTriennialStations = auth.riverTriennialStations ?? [];

    setState(() {
      _manualStationsForState = allManualStations
          .where((s) => s['state_name'] == widget.data.selectedStateName)
          .toList()
        ..sort((a, b) => (a['sampling_station_code'] ?? '')
            .compareTo(b['sampling_station_code'] ?? ''));

      _triennialStationsForState = allTriennialStations
          .where((s) => s['state_name'] == widget.data.selectedStateName)
          .toList()
        ..sort((a, b) => (a['triennial_station_code'] ?? '')
            .compareTo(b['triennial_station_code'] ?? ''));
    });
  }

  Future<void> _getCurrentLocation() async {
    setState(() => _isLoadingLocation = true);
    final service = Provider.of<RiverInvestigativeSamplingService>(context, listen: false);

    try {
      final position = await service.getCurrentLocation();
      if (mounted) {
        setState(() {
          // Reset manual entry flag because we successfully used GPS
          _isManualLocationEntry = false;

          widget.data.currentLatitude = position.latitude.toString();
          widget.data.currentLongitude = position.longitude.toString();
          _currentLatController.text = widget.data.currentLatitude!;
          _currentLonController.text = widget.data.currentLongitude!;

          // If 'New Location', update station lat/lon as well
          if (widget.data.stationTypeSelection == 'New Location') {
            widget.data.stationLatitude = position.latitude.toString();
            widget.data.stationLongitude = position.longitude.toString();
            _stationLatController.text = widget.data.stationLatitude!;
            _stationLonController.text = widget.data.stationLongitude!;
          }

          _calculateDistance();
        });
      }
    } catch (e) {
      if(mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Failed to get location: $e')));
      }
    } finally {
      if (mounted) {
        setState(() => _isLoadingLocation = false);
      }
    }
  }

  void _calculateDistance() {
    final lat1Str = widget.data.stationLatitude;
    final lon1Str = widget.data.stationLongitude;
    final lat2Str = widget.data.currentLatitude;
    final lon2Str = widget.data.currentLongitude;

    if (lat1Str != null && lon1Str != null && lat2Str != null && lon2Str != null) {
      final service = Provider.of<RiverInvestigativeSamplingService>(context, listen: false);
      final lat1 = double.tryParse(lat1Str);
      final lon1 = double.tryParse(lon1Str);
      final lat2 = double.tryParse(lat2Str);
      final lon2 = double.tryParse(lon2Str);

      if (lat1 != null && lon1 != null && lat2 != null && lon2 != null) {
        final distance = service.calculateDistance(lat1, lon1, lat2, lon2);
        setState(() {
          widget.data.distanceDifferenceInKm = distance;
        });
      } else {
        setState(() { widget.data.distanceDifferenceInKm = null; });
      }
    } else {
      setState(() { widget.data.distanceDifferenceInKm = null; });
    }
  }

  Future<void> _scanBarcode() async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => const SimpleBarcodeScannerPage()),
    );
    if (result is String && result != '-1' && mounted) {
      setState(() {
        widget.data.sampleIdCode = result;
        _barcodeController.text = result;
      });
    }
  }

  Future<void> _findAndShowNearbyStations() async {
    if (widget.data.stationTypeSelection != 'Existing Manual Station') {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Nearby station search only available for Manual Stations.')));
      return;
    }

    if (widget.data.currentLatitude == null || widget.data.currentLatitude!.isEmpty) {
      await _getCurrentLocation();
      if (!mounted || widget.data.currentLatitude == null || widget.data.currentLatitude!.isEmpty) {
        return;
      }
    }

    final service = Provider.of<RiverInvestigativeSamplingService>(context, listen: false);
    final auth = Provider.of<AuthProvider>(context, listen: false);

    final currentLat = double.tryParse(widget.data.currentLatitude ?? '');
    final currentLon = double.tryParse(widget.data.currentLongitude ?? '');

    if (currentLat == null || currentLon == null) return;

    final allStations = auth.riverManualStations ?? [];
    final List<Map<String, dynamic>> nearbyStations = [];

    for (var station in allStations) {
      final stationLat = station['sampling_lat'];
      final stationLon = station['sampling_long'];

      if (stationLat is num && stationLon is num) {
        final distance = service.calculateDistance(currentLat, currentLon, stationLat.toDouble(), stationLon.toDouble());
        if (distance <= 3.0) {
          nearbyStations.add({'station': station, 'distance': distance});
        }
      }
    }

    nearbyStations.sort((a, b) => a['distance'].compareTo(b['distance']));

    if (!mounted) return;

    final selectedStation = await showDialog<Map<String, dynamic>>(
      context: context,
      builder: (context) => _NearbyStationsDialog(nearbyStations: nearbyStations),
    );

    if (selectedStation != null) {
      _updateFormWithSelectedManualStation(selectedStation);
    }
  }

  void _updateFormWithSelectedManualStation(Map<String, dynamic> station) {
    final auth = Provider.of<AuthProvider>(context, listen: false);
    final allManualStations = auth.riverManualStations ?? [];
    setState(() {
      widget.data.stationTypeSelection = 'Existing Manual Station';
      widget.data.selectedStateName = station['state_name'];
      widget.data.selectedStation = station;
      widget.data.selectedTriennialStation = null;
      _clearNewLocationFields();

      widget.data.stationLatitude = station['sampling_lat']?.toString();
      widget.data.stationLongitude = station['sampling_long']?.toString();
      _stationLatController.text = widget.data.stationLatitude ?? '';
      _stationLonController.text = widget.data.stationLongitude ?? '';

      _manualStationsForState = allManualStations
          .where((s) => s['state_name'] == widget.data.selectedStateName)
          .toList()
        ..sort((a, b) => (a['sampling_station_code'] ?? '').compareTo(b['sampling_station_code'] ?? ''));

      _calculateDistance();
    });
  }

  void _updateFormWithSelectedTriennialStation(Map<String, dynamic> station) {
    final auth = Provider.of<AuthProvider>(context, listen: false);
    final allTriennialStations = auth.riverTriennialStations ?? [];
    setState(() {
      widget.data.stationTypeSelection = 'Existing Triennial Station';
      widget.data.selectedStateName = station['state_name'];
      widget.data.selectedTriennialStation = station;
      widget.data.selectedStation = null;
      _clearNewLocationFields();

      widget.data.stationLatitude = station['triennial_lat']?.toString();
      widget.data.stationLongitude = station['triennial_long']?.toString();
      _stationLatController.text = widget.data.stationLatitude ?? '';
      _stationLonController.text = widget.data.stationLongitude ?? '';

      _triennialStationsForState = allTriennialStations
          .where((s) => s['state_name'] == widget.data.selectedStateName)
          .toList()
        ..sort((a, b) => (a['triennial_station_code'] ?? '').compareTo(b['triennial_station_code'] ?? ''));

      _calculateDistance();
    });
  }

  void _clearStationSelections() {
    widget.data.selectedStation = null;
    widget.data.selectedTriennialStation = null;
    widget.data.stationLatitude = null;
    widget.data.stationLongitude = null;
    _stationLatController.clear();
    _stationLonController.clear();
    widget.data.distanceDifferenceInKm = null;
  }

  void _clearNewLocationFields() {
    widget.data.newStateName = null;
    widget.data.newBasinName = null;
    widget.data.newRiverName = null;
    widget.data.newStationCode = null;
    _newStateController.clear();
    _newBasinController.clear();
    _newRiverController.clear();
    _newStationCodeController.clear();
  }


  Future<void> _goToNextStep() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();

      if (widget.data.stationTypeSelection == 'New Location') {
        if (widget.data.stationLatitude == null || widget.data.stationLatitude!.isEmpty ||
            widget.data.stationLongitude == null || widget.data.stationLongitude!.isEmpty ) {
          ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('Please capture GPS coordinates for the new location.'), backgroundColor: Colors.red)
          );
          return;
        }
      }

      // NEW: Check if manually entered, ask for confirmation
      if (_isManualLocationEntry) {
        final confirmed = await _showLocationConfirmationDialog();
        if (confirmed != true) {
          return; // Stop if user cancels
        }
      }

      final distanceInMeters = (widget.data.distanceDifferenceInKm ?? 0) * 1000;

      if (widget.data.stationTypeSelection != 'New Location' && distanceInMeters > 50) {
        _showDistanceRemarkDialog();
      } else {
        widget.data.distanceDifferenceRemarks = null;
        widget.onNext();
      }
    }
  }

  // NEW: Dialog for manual location verification
  Future<bool?> _showLocationConfirmationDialog() {
    return showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Verify Coordinates'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('You have manually entered the location. Please confirm these coordinates are correct:'),
              const SizedBox(height: 12),
              Text('Latitude: ${widget.data.currentLatitude}', style: const TextStyle(fontWeight: FontWeight.bold)),
              Text('Longitude: ${widget.data.currentLongitude}', style: const TextStyle(fontWeight: FontWeight.bold)),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('Edit'),
            ),
            FilledButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: const Text('Confirm'),
            ),
          ],
        );
      },
    );
  }

  Future<void> _showDistanceRemarkDialog() async {
    final remarkController = TextEditingController(text: widget.data.distanceDifferenceRemarks);
    final dialogFormKey = GlobalKey<FormState>();

    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Distance Warning'),
          content: SingleChildScrollView(
            child: Form(
              key: dialogFormKey,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text('Your current location is more than 50m away from the selected station.'),
                  const SizedBox(height: 16),
                  TextFormField(
                    controller: remarkController,
                    decoration: const InputDecoration(
                      labelText: 'Remarks *',
                      hintText: 'Please provide a reason...',
                      border: OutlineInputBorder(),
                    ),
                    validator: (value) {
                      if (value == null || value.trim().isEmpty) {
                        return 'Remarks are required to continue.';
                      }
                      return null;
                    },
                    maxLines: 3,
                  ),
                ],
              ),
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('Cancel'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            FilledButton(
              child: const Text('Confirm'),
              onPressed: () {
                if (dialogFormKey.currentState!.validate()) {
                  setState(() {
                    widget.data.distanceDifferenceRemarks = remarkController.text;
                  });
                  Navigator.of(context).pop();
                  widget.onNext();
                }
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final auth = Provider.of<AuthProvider>(context, listen: false);
    final allUsers = auth.allUsers ?? [];

    final secondSamplersList = allUsers
        .where((user) => user['user_id'] != auth.profileData?['user_id'])
        .toList()
      ..sort((a, b) =>
          (a['first_name'] ?? '').compareTo(b['first_name'] ?? ''));

    bool isNewLocation = widget.data.stationTypeSelection == 'New Location';

    return Form(
      key: _formKey,
      child: ListView(
        padding: const EdgeInsets.all(24.0),
        children: [
          Text("Investigative Sampling Information",
              style: Theme.of(context).textTheme.headlineSmall),
          const SizedBox(height: 24),

          // --- Sampler and Time ---
          TextFormField(
              controller: _firstSamplerController,
              readOnly: true,
              decoration: const InputDecoration(labelText: '1st Sampler')),
          const SizedBox(height: 16),
          DropdownSearch<Map<String, dynamic>>(
            items: secondSamplersList,
            selectedItem: widget.data.secondSampler,
            itemAsString: (sampler) =>
            "${sampler['first_name']} ${sampler['last_name']}",
            onChanged: (sampler) => widget.data.secondSampler = sampler,
            popupProps: const PopupProps.menu(
                showSearchBox: true,
                searchFieldProps: TextFieldProps(
                    decoration: InputDecoration(hintText: "Search Sampler..."))),
            dropdownDecoratorProps: const DropDownDecoratorProps(
                dropdownSearchDecoration:
                InputDecoration(labelText: '2nd Sampler (Optional)')),
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                  child: TextFormField(
                      controller: _dateController,
                      readOnly: true,
                      decoration: const InputDecoration(labelText: 'Date'))),
              const SizedBox(width: 16),
              Expanded(
                  child: TextFormField(
                      controller: _timeController,
                      readOnly: true,
                      decoration: const InputDecoration(labelText: 'Time'))),
            ],
          ),
          const SizedBox(height: 16),

          // --- Sample ID ---
          TextFormField(
            controller: _barcodeController,
            decoration: InputDecoration(
              labelText: 'Sample ID Code *',
              suffixIcon: IconButton(
                icon: const Icon(Icons.qr_code_scanner),
                onPressed: _scanBarcode,
              ),
            ),
            validator: (val) =>
            val == null || val.isEmpty ? "Sample ID is required" : null,
            onSaved: (val) => widget.data.sampleIdCode = val,
            onChanged: (val) => widget.data.sampleIdCode = val,
          ),
          const SizedBox(height: 24),

          // --- Station Type Selection ---
          DropdownButtonFormField<String>(
            value: widget.data.stationTypeSelection,
            items: _stationTypes
                .map((type) => DropdownMenuItem(value: type, child: Text(type)))
                .toList(),
            onChanged: (value) {
              setState(() {
                widget.data.stationTypeSelection = value;
                _clearStationSelections();
                _clearNewLocationFields();
                if (value == 'New Location' && widget.data.currentLatitude != null) {
                  widget.data.stationLatitude = widget.data.currentLatitude;
                  widget.data.stationLongitude = widget.data.currentLongitude;
                  _stationLatController.text = widget.data.stationLatitude!;
                  _stationLonController.text = widget.data.stationLongitude!;
                }
                _calculateDistance();
              });
            },
            decoration: const InputDecoration(labelText: 'Station Type *'),
            validator: (value) => value == null ? 'Please select station type' : null,
          ),
          const SizedBox(height: 16),

          // --- Conditional Station/Location Inputs ---

          // == Existing Manual Station ==
          if (widget.data.stationTypeSelection == 'Existing Manual Station') ...[
            DropdownSearch<String>(
              items: _statesList,
              selectedItem: widget.data.selectedStateName,
              popupProps: const PopupProps.menu(
                  showSearchBox: true,
                  searchFieldProps: TextFieldProps(
                      decoration: InputDecoration(hintText: "Search State..."))),
              dropdownDecoratorProps: const DropDownDecoratorProps(
                  dropdownSearchDecoration:
                  InputDecoration(labelText: "Select State *")),
              onChanged: (state) {
                setState(() {
                  widget.data.selectedStateName = state;
                  _clearStationSelections();
                  _loadStationsForSelectedState();
                  _calculateDistance();
                });
              },
              validator: (val) => val == null ? "State is required" : null,
            ),
            const SizedBox(height: 16),
            DropdownSearch<Map<String, dynamic>>(
              items: _manualStationsForState,
              selectedItem: widget.data.selectedStation,
              enabled: widget.data.selectedStateName != null,
              itemAsString: (station) =>
              "${station['sampling_station_code']} | ${station['sampling_river']} | ${station['sampling_basin']}",
              popupProps: const PopupProps.menu(
                  showSearchBox: true,
                  searchFieldProps: TextFieldProps(
                      decoration:
                      InputDecoration(hintText: "Search Station..."))),
              dropdownDecoratorProps: const DropDownDecoratorProps(
                  dropdownSearchDecoration:
                  InputDecoration(labelText: "Select Manual Station *")),
              onChanged: (station) {
                if (station != null) {
                  _updateFormWithSelectedManualStation(station);
                }
              },
              validator: (val) => widget.data.selectedStateName != null && val == null
                  ? "Manual Station is required"
                  : null,
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              icon: const Icon(Icons.explore_outlined),
              label: const Text("NEARBY MANUAL STATION"),
              onPressed: _isLoadingLocation ? null : _findAndShowNearbyStations,
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 12),
              ),
            ),
          ],

          // == Existing Triennial Station ==
          if (widget.data.stationTypeSelection == 'Existing Triennial Station') ...[
            DropdownSearch<String>(
              items: _statesList,
              selectedItem: widget.data.selectedStateName,
              popupProps: const PopupProps.menu(showSearchBox: true, searchFieldProps: TextFieldProps(decoration: InputDecoration(hintText: "Search State..."))),
              dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "Select State *")),
              onChanged: (state) {
                setState(() {
                  widget.data.selectedStateName = state;
                  _clearStationSelections();
                  _loadStationsForSelectedState();
                  _calculateDistance();
                });
              },
              validator: (val) => val == null ? "State is required" : null,
            ),
            const SizedBox(height: 16),
            DropdownSearch<Map<String, dynamic>>(
              items: _triennialStationsForState,
              selectedItem: widget.data.selectedTriennialStation,
              enabled: widget.data.selectedStateName != null,
              itemAsString: (station) =>
              "${station['triennial_station_code']} | ${station['triennial_river']} | ${station['triennial_basin']}",
              popupProps: const PopupProps.menu(
                  showSearchBox: true,
                  searchFieldProps: TextFieldProps(
                      decoration:
                      InputDecoration(hintText: "Search Station..."))),
              dropdownDecoratorProps: const DropDownDecoratorProps(
                  dropdownSearchDecoration:
                  InputDecoration(labelText: "Select Triennial Station *")),
              onChanged: (station) {
                if (station != null) {
                  _updateFormWithSelectedTriennialStation(station);
                }
              },
              validator: (val) => widget.data.selectedStateName != null && val == null
                  ? "Triennial Station is required"
                  : null,
            ),
          ],

          // == New Location ==
          if (widget.data.stationTypeSelection == 'New Location') ...[
            DropdownSearch<String>(
              items: _statesList,
              selectedItem: widget.data.newStateName,
              popupProps: const PopupProps.menu(showSearchBox: true, searchFieldProps: TextFieldProps(decoration: InputDecoration(hintText: "Search State..."))),
              dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "Select State *")),
              onChanged: (state) {
                setState(() {
                  widget.data.newStateName = state;
                  widget.data.selectedStateName = state;
                });
              },
              validator: (val) => val == null ? "State is required" : null,
              onSaved: (val) => widget.data.newStateName = val,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _newBasinController,
              decoration: const InputDecoration(labelText: 'Basin Name *'),
              validator: (val) =>
              val == null || val.isEmpty ? "Basin name is required" : null,
              onSaved: (val) => widget.data.newBasinName = val,
              onChanged: (val) => widget.data.newBasinName = val,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _newRiverController,
              decoration: const InputDecoration(labelText: 'River Name *'),
              validator: (val) =>
              val == null || val.isEmpty ? "River name is required" : null,
              onSaved: (val) => widget.data.newRiverName = val,
              onChanged: (val) => widget.data.newRiverName = val,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _newStationCodeController,
              decoration: const InputDecoration(labelText: 'Station Code (Optional)'),
              onSaved: (val) => widget.data.newStationCode = val,
              onChanged: (val) => widget.data.newStationCode = val,
            ),
          ],
          const SizedBox(height: 16),

          // --- Station Coordinates ---
          TextFormField(
            controller: _stationLatController,
            readOnly: !isNewLocation,
            decoration: InputDecoration(
                labelText: 'Station Latitude ${isNewLocation ? "*" : ""}',
                hintText: isNewLocation ? 'Use GPS or enter manually' : null
            ),
            keyboardType: TextInputType.numberWithOptions(decimal: true),
            validator: (val) => isNewLocation && (val == null || val.isEmpty) ? "Latitude is required for new location" : null,
            onChanged: (val) {
              if (isNewLocation) {
                widget.data.stationLatitude = val;
                _calculateDistance();
              }
            },
            onSaved: (val) => widget.data.stationLatitude = val,
          ),
          const SizedBox(height: 16),
          TextFormField(
            controller: _stationLonController,
            readOnly: !isNewLocation,
            decoration: InputDecoration(
                labelText: 'Station Longitude ${isNewLocation ? "*" : ""}',
                hintText: isNewLocation ? 'Use GPS or enter manually' : null
            ),
            keyboardType: TextInputType.numberWithOptions(decimal: true),
            validator: (val) => isNewLocation && (val == null || val.isEmpty) ? "Longitude is required for new location" : null,
            onChanged: (val) {
              if (isNewLocation) {
                widget.data.stationLongitude = val;
                _calculateDistance();
              }
            },
            onSaved: (val) => widget.data.stationLongitude = val,
          ),

          const SizedBox(height: 24),

          // --- Location Verification ---
          Text("Location Verification",
              style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 16),

          // MODIFIED: Enabled manual entry for Current Latitude
          TextFormField(
            controller: _currentLatController,
            keyboardType: const TextInputType.numberWithOptions(decimal: true),
            decoration: const InputDecoration(
              labelText: 'Current Latitude *',
              hintText: 'e.g. 3.14159',
            ),
            validator: (val) => val == null || val.isEmpty ? "Latitude is required" : null,
            onChanged: (val) {
              _isManualLocationEntry = true;
              widget.data.currentLatitude = val;
              _calculateDistance();
            },
          ),
          const SizedBox(height: 16),

          // MODIFIED: Enabled manual entry for Current Longitude
          TextFormField(
            controller: _currentLonController,
            keyboardType: const TextInputType.numberWithOptions(decimal: true),
            decoration: const InputDecoration(
              labelText: 'Current Longitude *',
              hintText: 'e.g. 101.68685',
            ),
            validator: (val) => val == null || val.isEmpty ? "Longitude is required" : null,
            onChanged: (val) {
              _isManualLocationEntry = true;
              widget.data.currentLongitude = val;
              _calculateDistance();
            },
          ),

          if (widget.data.distanceDifferenceInKm != null && widget.data.stationTypeSelection != 'New Location')
            Padding(
              padding: const EdgeInsets.only(top: 16.0),
              child: Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: ((widget.data.distanceDifferenceInKm ?? 0) * 1000) > 50
                      ? Colors.red.withOpacity(0.1)
                      : Colors.green.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                      color: ((widget.data.distanceDifferenceInKm ?? 0) * 1000) > 50
                          ? Colors.red
                          : Colors.green),
                ),
                child: RichText(
                  textAlign: TextAlign.center,
                  text: TextSpan(
                    style: Theme.of(context).textTheme.bodyLarge,
                    children: <TextSpan>[
                      const TextSpan(text: 'Distance from Station: '),
                      TextSpan(
                        text:
                        '${(widget.data.distanceDifferenceInKm! * 1000).toStringAsFixed(0)} meters',
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: ((widget.data.distanceDifferenceInKm ?? 0) * 1000) > 50
                                ? Colors.red
                                : Colors.green),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          const SizedBox(height: 16),
          OutlinedButton.icon(
            onPressed: _isLoadingLocation ? null : _getCurrentLocation,
            icon: _isLoadingLocation
                ? const SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(strokeWidth: 2))
                : const Icon(Icons.location_searching),
            label: Text(isNewLocation ? "Get Current Location (GPS)" : "Get Current Location (GPS)"),
          ),
          const SizedBox(height: 32),

          // --- Navigation ---
          ElevatedButton(
            onPressed: _goToNextStep,
            style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16)),
            child: const Text('Next'),
          ),
        ],
      ),
    );
  }
}

class _NearbyStationsDialog extends StatelessWidget {
  final List<Map<String, dynamic>> nearbyStations;

  const _NearbyStationsDialog({required this.nearbyStations});

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Nearby Manual Stations (within 3km)'),
      content: SizedBox(
        width: double.maxFinite,
        child: nearbyStations.isEmpty
            ? const Center(child: Text('No stations found.'))
            : ListView.builder(
          shrinkWrap: true,
          itemCount: nearbyStations.length,
          itemBuilder: (context, index) {
            final item = nearbyStations[index];
            final station = item['station'] as Map<String, dynamic>;
            final distanceInMeters = (item['distance'] as double) * 1000;

            return Card(
              child: ListTile(
                title: Text("${station['sampling_station_code'] ?? 'N/A'}"),
                subtitle: Text("${station['sampling_river'] ?? 'N/A'}"),
                trailing: Text("${distanceInMeters.toStringAsFixed(0)} m"),
                onTap: () {
                  Navigator.of(context).pop(station);
                },
              ),
            );
          },
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('Cancel'),
        ),
      ],
    );
  }
}