// lib/screens/marine/investigative/manual_sampling/marine_inves_manual_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/marine_inves_manual_sampling_data.dart';
import '../../../../services/marine_investigative_sampling_service.dart';

class MarineInvesManualStep1SamplingInfo extends StatefulWidget {
  final MarineInvesManualSamplingData data;
  final VoidCallback onNext;

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

  @override
  State<MarineInvesManualStep1SamplingInfo> createState() => _MarineInvesManualStep1SamplingInfoState();
}

class _MarineInvesManualStep1SamplingInfoState extends State<MarineInvesManualStep1SamplingInfo> {
  final _formKey = GlobalKey<FormState>();
  bool _isLoadingLocation = 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;

  // Controllers for 'New Location'
  late final TextEditingController _newStationNameController;
  late final TextEditingController _newStationCodeController;

  // State for Station Selection
  String _stationType = 'Existing Manual Station';
  final List<String> _stationTypeOptions = ['Existing Manual Station', 'Existing Tarball Station', 'New Location'];

  // Lists for Dropdowns
  List<String> _manualStatesList = [];
  List<String> _categoriesForManualState = [];
  List<Map<String, dynamic>> _stationsForManualCategory = [];

  List<String> _tarballStatesList = [];
  List<Map<String, dynamic>> _stationsForTarballState = [];

  final List<String> _samplingTypes = ['Investigative'];

  @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();
    _newStationNameController.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);

    _newStationNameController = TextEditingController(text: widget.data.newStationName);
    _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!;

    _dateController.text = widget.data.samplingDate!;
    _timeController.text = widget.data.samplingTime!;

    if (widget.data.samplingType == null) {
      widget.data.samplingType = 'Investigative';
    }

    _stationType = widget.data.stationTypeSelection ?? 'Existing Manual Station';

    // Load Manual Station Data
    final allManualStations = auth.manualStations ?? [];
    if (allManualStations.isNotEmpty) {
      _manualStatesList = allManualStations.map((s) => s['state_name'] as String?).whereType<String>().toSet().toList()..sort();
      if (widget.data.selectedManualStateName != null) {
        _categoriesForManualState = allManualStations
            .where((s) => s['state_name'] == widget.data.selectedManualStateName)
            .map((s) => s['category_name'] as String?)
            .whereType<String>()
            .toSet().toList()..sort();
      }
      if (widget.data.selectedManualCategoryName != null) {
        _stationsForManualCategory = allManualStations
            .where((s) => s['state_name'] == widget.data.selectedManualStateName && s['category_name'] == widget.data.selectedManualCategoryName)
            .toList()..sort((a, b) => (a['man_station_code'] ?? '').compareTo(b['man_station_code'] ?? ''));
      }
    }

    // Load Tarball Station Data
    final allTarballStations = auth.tarballStations ?? [];
    if (allTarballStations.isNotEmpty) {
      _tarballStatesList = allTarballStations.map((s) => s['state_name'] as String?).whereType<String>().toSet().toList()..sort();
      if (widget.data.selectedTarballStateName != null) {
        _stationsForTarballState = allTarballStations
            .where((s) => s['state_name'] == widget.data.selectedTarballStateName)
            .toList()..sort((a, b) => (a['tbl_station_code'] ?? '').compareTo(b['tbl_station_code'] ?? ''));
      }
    }
  }

  void _handleStationTypeChange(String? value) {
    if (value == null) return;
    setState(() {
      _stationType = value;
      widget.data.stationTypeSelection = value;

      widget.data.selectedManualStateName = null;
      widget.data.selectedManualCategoryName = null;
      widget.data.selectedStation = null;

      widget.data.selectedTarballStateName = null;
      widget.data.selectedTarballStation = null;

      widget.data.newStationName = null;
      widget.data.newStationCode = null;
      _newStationNameController.clear();
      _newStationCodeController.clear();

      widget.data.stationLatitude = null;
      widget.data.stationLongitude = null;
      _stationLatController.clear();
      _stationLonController.clear();

      widget.data.distanceDifferenceInKm = null;
    });
  }

  Future<void> _getCurrentLocation() async {
    setState(() => _isLoadingLocation = true);
    final service = Provider.of<MarineInvestigativeSamplingService>(context, listen: false);
    try {
      final position = await service.getCurrentLocation();
      // FIX: Check if mounted after async location call to prevent framework crash
      if (!mounted) return;

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

        if (_stationType == 'New Location') {
          widget.data.stationLatitude = widget.data.currentLatitude;
          widget.data.stationLongitude = widget.data.currentLongitude;
          _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<MarineInvestigativeSamplingService>(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()),
    );
    // FIX: Ensure widget is still mounted before updating state after returning from navigation
    if (result is String && result != '-1' && mounted) {
      setState(() {
        widget.data.sampleIdCode = result;
        _barcodeController.text = result;
      });
    }
  }

  Future<void> _findAndShowNearbyStations() async {
    if (widget.data.currentLatitude == null || widget.data.currentLatitude!.isEmpty) {
      await _getCurrentLocation();
      // FIX: Standard async mount check
      if (!mounted || widget.data.currentLatitude == null || widget.data.currentLatitude!.isEmpty) {
        return;
      }
    }

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

    final currentLat = double.parse(widget.data.currentLatitude!);
    final currentLon = double.parse(widget.data.currentLongitude!);
    final allStations = auth.manualStations ?? [];
    final List<Map<String, dynamic>> nearbyStations = [];

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

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

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

    // FIX: Verify mount before showing dialog
    if (!mounted) return;

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

    // FIX: Verify mount after dialog closes
    if (selectedStation != null && mounted) {
      _updateFormWithSelectedStation(selectedStation);
    }
  }

  void _updateFormWithSelectedStation(Map<String, dynamic> station) {
    final allStations = Provider.of<AuthProvider>(context, listen: false).manualStations ?? [];
    setState(() {
      widget.data.selectedManualStateName = station['state_name'];

      final categories = allStations
          .where((s) => s['state_name'] == widget.data.selectedManualStateName)
          .map((s) => s['category_name'] as String?)
          .whereType<String>()
          .toSet()
          .toList();
      categories.sort();
      _categoriesForManualState = categories;

      widget.data.selectedManualCategoryName = station['category_name'];

      _stationsForManualCategory = allStations
          .where((s) =>
      s['state_name'] == widget.data.selectedManualStateName &&
          s['category_name'] == widget.data.selectedManualCategoryName)
          .toList()
        ..sort((a, b) => (a['man_station_code'] ?? '').compareTo(b['man_station_code'] ?? ''));

      widget.data.selectedStation = station;
      widget.data.stationLatitude = station['man_latitude']?.toString();
      widget.data.stationLongitude = station['man_longitude']?.toString();
      _stationLatController.text = widget.data.stationLatitude ?? '';
      _stationLonController.text = widget.data.stationLongitude ?? '';

      _calculateDistance();
    });
  }

  void _goToNextStep() {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();

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

      if (distanceInMeters > 50 && widget.data.stationLatitude != null && widget.data.stationLongitude != null) {
        _showDistanceRemarkDialog();
      } else {
        widget.data.distanceDifferenceRemarks = null;
        widget.onNext();
      }
    }
  }

  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 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: () {
                // FIX: Guard setState and navigation within dialog actions
                if (dialogFormKey.currentState!.validate() && mounted) {
                  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'] ?? ''));

    return Form(
      key: _formKey,
      child: ListView(
        padding: const EdgeInsets.all(24.0),
        children: [
          Text("Sampling Information", style: Theme.of(context).textTheme.headlineSmall),
          const SizedBox(height: 24),
          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),
          DropdownButtonFormField<String>(
            value: widget.data.samplingType,
            items: _samplingTypes.map((type) => DropdownMenuItem(value: type, child: Text(type))).toList(),
            onChanged: (value) => setState(() => widget.data.samplingType = value),
            decoration: const InputDecoration(labelText: 'Sampling Type *'),
            validator: (value) => value == null ? 'Please select a type' : null,
          ),
          const SizedBox(height: 24),

          Text("Station Selection", style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 16),
          DropdownButtonFormField<String>(
            value: _stationType,
            items: _stationTypeOptions.map((type) => DropdownMenuItem(value: type, child: Text(type))).toList(),
            onChanged: _handleStationTypeChange,
            decoration: const InputDecoration(labelText: 'Station Source *'),
            validator: (value) => value == null ? 'Please select a station source' : null,
          ),
          const SizedBox(height: 16),

          if (_stationType == 'Existing Manual Station')
            _buildManualStationSelectors(auth.manualStations ?? []),

          if (_stationType == 'Existing Tarball Station')
            _buildTarballStationSelectors(auth.tarballStations ?? []),

          if (_stationType == 'New Location')
            _buildNewLocationFields(),

          const SizedBox(height: 24),
          Text("Location Verification", style: Theme.of(context).textTheme.titleLarge),
          const SizedBox(height: 16),
          TextFormField(controller: _currentLatController, readOnly: true, decoration: const InputDecoration(labelText: 'Current Latitude')),
          const SizedBox(height: 16),
          TextFormField(controller: _currentLonController, readOnly: true, decoration: const InputDecoration(labelText: 'Current Longitude')),
          if (widget.data.distanceDifferenceInKm != null)
            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(_stationType == 'New Location' ? "Get & Use Current Location" : "Get Current Location"),
            style: OutlinedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 12)),
          ),
          const SizedBox(height: 16),

          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: 32),
          ElevatedButton(
            onPressed: _goToNextStep,
            style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16)),
            child: const Text('Next'),
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  Widget _buildManualStationSelectors(List<Map<String, dynamic>> allStations) {
    return Column(
      children: [
        DropdownSearch<String>(
          items: _manualStatesList,
          selectedItem: widget.data.selectedManualStateName,
          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.selectedManualStateName = state;
              widget.data.selectedManualCategoryName = null;
              widget.data.selectedStation = null;
              _stationLatController.clear();
              _stationLonController.clear();
              widget.data.distanceDifferenceInKm = null;
              if (state != null) {
                _categoriesForManualState = allStations
                    .where((s) => s['state_name'] == state)
                    .map((s) => s['category_name'] as String?)
                    .whereType<String>()
                    .toSet().toList()..sort();
              } else {
                _categoriesForManualState = <String>[];
              }
              _stationsForManualCategory = [];
            });
          },
          validator: (val) => val == null ? "State is required" : null,
        ),
        const SizedBox(height: 16),
        DropdownSearch<String>(
          items: _categoriesForManualState,
          selectedItem: widget.data.selectedManualCategoryName,
          enabled: widget.data.selectedManualStateName != null,
          popupProps: const PopupProps.menu(showSearchBox: true, searchFieldProps: TextFieldProps(decoration: InputDecoration(hintText: "Search Category..."))),
          dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "Select Category *")),
          onChanged: (category) {
            setState(() {
              widget.data.selectedManualCategoryName = category;
              widget.data.selectedStation = null;
              _stationLatController.clear();
              _stationLonController.clear();
              widget.data.distanceDifferenceInKm = null;
              if (category != null) {
                _stationsForManualCategory = allStations
                    .where((s) => s['state_name'] == widget.data.selectedManualStateName && s['category_name'] == category)
                    .toList()..sort((a, b) => (a['man_station_code'] ?? '').compareTo(b['man_station_code'] ?? ''));
              } else {
                _stationsForManualCategory = [];
              }
            });
          },
          validator: (val) => widget.data.selectedManualStateName != null && val == null ? "Category is required" : null,
        ),
        const SizedBox(height: 16),
        DropdownSearch<Map<String, dynamic>>(
          items: _stationsForManualCategory,
          selectedItem: widget.data.selectedStation,
          enabled: widget.data.selectedManualCategoryName != null,
          itemAsString: (station) => "${station['man_station_code']} - ${station['man_station_name']}",
          popupProps: const PopupProps.menu(showSearchBox: true, searchFieldProps: TextFieldProps(decoration: InputDecoration(hintText: "Search Station..."))),
          dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "Select Station *")),
          onChanged: (station) => setState(() {
            widget.data.selectedStation = station;
            widget.data.stationLatitude = station?['man_latitude']?.toString();
            widget.data.stationLongitude = station?['man_longitude']?.toString();
            _stationLatController.text = widget.data.stationLatitude ?? '';
            _stationLonController.text = widget.data.stationLongitude ?? '';
            _calculateDistance();
          }),
          validator: (val) => widget.data.selectedManualCategoryName != null && val == null ? "Station is required" : null,
        ),
        const SizedBox(height: 16),
        TextFormField(controller: _stationLatController, readOnly: true, decoration: const InputDecoration(labelText: 'Station Latitude')),
        const SizedBox(height: 16),
        TextFormField(controller: _stationLonController, readOnly: true, decoration: const InputDecoration(labelText: 'Station Longitude')),
        const SizedBox(height: 16),
        ElevatedButton.icon(
          icon: const Icon(Icons.explore_outlined),
          label: const Text("NEARBY STATION"),
          onPressed: _isLoadingLocation ? null : _findAndShowNearbyStations,
          style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 12)),
        ),
      ],
    );
  }

  Widget _buildTarballStationSelectors(List<Map<String, dynamic>> allStations) {
    return Column(
      children: [
        DropdownSearch<String>(
          items: _tarballStatesList,
          selectedItem: widget.data.selectedTarballStateName,
          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.selectedTarballStateName = state;
              widget.data.selectedTarballStation = null;
              _stationLatController.clear();
              _stationLonController.clear();
              widget.data.distanceDifferenceInKm = null;
              if (state != null) {
                _stationsForTarballState = allStations
                    .where((s) => s['state_name'] == state)
                    .toList()..sort((a, b) => (a['tbl_station_code'] ?? '').compareTo(b['tbl_station_code'] ?? ''));
              } else {
                _stationsForTarballState = <Map<String, dynamic>>[];
              }
            });
          },
          validator: (val) => val == null ? "State is required" : null,
        ),
        const SizedBox(height: 16),
        DropdownSearch<Map<String, dynamic>>(
          items: _stationsForTarballState,
          selectedItem: widget.data.selectedTarballStation,
          enabled: widget.data.selectedTarballStateName != null,
          itemAsString: (station) => "${station['tbl_station_code']} - ${station['tbl_station_name']}",
          popupProps: const PopupProps.menu(showSearchBox: true, searchFieldProps: TextFieldProps(decoration: InputDecoration(hintText: "Search Station..."))),
          dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "Select Station *")),
          onChanged: (station) => setState(() {
            widget.data.selectedTarballStation = station;
            widget.data.stationLatitude = station?['tbl_latitude']?.toString();
            widget.data.stationLongitude = station?['tbl_longitude']?.toString();
            _stationLatController.text = widget.data.stationLatitude ?? '';
            _stationLonController.text = widget.data.stationLongitude ?? '';
            _calculateDistance();
          }),
          validator: (val) => widget.data.selectedTarballStateName != null && val == null ? "Station is required" : null,
        ),
        const SizedBox(height: 16),
        TextFormField(controller: _stationLatController, readOnly: true, decoration: const InputDecoration(labelText: 'Station Latitude')),
        const SizedBox(height: 16),
        TextFormField(controller: _stationLonController, readOnly: true, decoration: const InputDecoration(labelText: 'Station Longitude')),
      ],
    );
  }

  Widget _buildNewLocationFields() {
    return Column(
      children: [
        TextFormField(
          controller: _newStationNameController,
          decoration: const InputDecoration(labelText: 'New Station Name *'),
          validator: (val) => val == null || val.isEmpty ? "Station Name is required" : null,
          onSaved: (val) => widget.data.newStationName = val,
          onChanged: (val) => widget.data.newStationName = val,
        ),
        const SizedBox(height: 16),
        TextFormField(
          controller: _newStationCodeController,
          decoration: const InputDecoration(labelText: 'New Station Code *', hintText: "e.g., INV-001"),
          validator: (val) => val == null || val.isEmpty ? "Station Code is required" : null,
          onSaved: (val) => widget.data.newStationCode = val,
          onChanged: (val) => widget.data.newStationCode = val,
        ),
        const SizedBox(height: 16),
        TextFormField(
          controller: _stationLatController,
          decoration: const InputDecoration(labelText: 'Station Latitude *', hintText: "Enter manually or use 'Get Location'"),
          keyboardType: const TextInputType.numberWithOptions(decimal: true),
          validator: (val) {
            if (val == null || val.isEmpty) return "Latitude is required";
            final lat = double.tryParse(val);
            if (lat == null || lat < -90 || lat > 90) return "Enter a valid latitude (-90 to 90)";
            return null;
          },
          onSaved: (val) => widget.data.stationLatitude = val,
          onChanged: (val) {
            widget.data.stationLatitude = val;
            _calculateDistance();
          },
        ),
        const SizedBox(height: 16),
        TextFormField(
          controller: _stationLonController,
          decoration: const InputDecoration(labelText: 'Station Longitude *', hintText: "Enter manually or use 'Get Location'"),
          keyboardType: const TextInputType.numberWithOptions(decimal: true),
          validator: (val) {
            if (val == null || val.isEmpty) return "Longitude is required";
            final lon = double.tryParse(val);
            if (lon == null || lon < -180 || lon > 180) return "Enter a valid longitude (-180 to 180)";
            return null;
          },
          onSaved: (val) => widget.data.stationLongitude = val,
          onChanged: (val) {
            widget.data.stationLongitude = val;
            _calculateDistance();
          },
        ),
      ],
    );
  }
}

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 Stations (within 5km)'),
      content: SizedBox(
        width: double.maxFinite,
        child: nearbyStations.isEmpty
            ? const Center(child: Text('No stations found within 5km of your current location.'))
            : 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(
              margin: const EdgeInsets.symmetric(vertical: 4.0),
              child: ListTile(
                title: Text("${station['man_station_code'] ?? 'N/A'}"),
                subtitle: Text("${station['man_station_name'] ?? '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'),
        ),
      ],
    );
  }
}