// lib/screens/river/manual/river_manual_image_request.dart

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

import '../../../auth_provider.dart';
import '../../../services/api_service.dart';


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

  @override
  Widget build(BuildContext context) {
    return const RiverImageRequestScreen();
  }
}


class RiverImageRequestScreen extends StatefulWidget {
  const RiverImageRequestScreen({super.key});

  @override
  State<RiverImageRequestScreen> createState() => _RiverImageRequestScreenState();
}

class _RiverImageRequestScreenState extends State<RiverImageRequestScreen> {
  final _formKey = GlobalKey<FormState>();
  final _dateController = TextEditingController();

  // --- START: MODIFICATION ---
  String? _selectedSamplingType = 'In-Situ Sampling'; // Default to one
  final List<String> _samplingTypes = ['In-Situ Sampling', 'Triennial Sampling', 'Investigative Sampling'];
  // --- END: MODIFICATION ---

  String? _selectedStateName;
  String? _selectedBasinName;
  Map<String, dynamic>? _selectedStation;
  DateTime? _selectedDate;

  List<String> _statesList = [];
  List<String> _basinsForState = [];
  List<Map<String, dynamic>> _stationsForBasin = [];

  bool _isLoading = false;
  List<String> _imageUrls = [];
  final Set<String> _selectedImageUrls = {};

  @override
  void initState() {
    super.initState();
    // Use addPostFrameCallback to ensure provider is ready
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if(mounted) {
        _initializeStationFilters();
      }
    });
  }

  @override
  void dispose() {
    _dateController.dispose();
    super.dispose();
  }

  // --- START: ADDED HELPER FUNCTIONS (from marine_image_request pattern) ---

  /// Gets the correct list of stations from AuthProvider based on sampling type.
  List<Map<String, dynamic>> _getStationsForType(AuthProvider auth) {
    switch (_selectedSamplingType) {
      case 'In-Situ Sampling':
        return auth.riverManualStations ?? [];
      case 'Triennial Sampling':
        return auth.riverTriennialStations ?? [];
    // --- START: MODIFICATION ---
      case 'Investigative Sampling':
      // Assumes riverInvestigativeStations is loaded in AuthProvider
        return auth.riverInvestigativeStations ?? [];
    // --- END: MODIFICATION ---
      default:
        return [];
    }
  }

  /// Gets the key for the station's unique ID (for API calls).
  String _getStationIdKey() {
    // Both In-Situ and Triennial stations use 'station_id' in the DB
    // Assuming Investigative stations list also uses 'station_id'
    return 'station_id';
  }

  /// Gets the key for the station's human-readable code.
  String _getStationCodeKey() {
    // Both In-Situ and Triennial station maps use 'sampling_station_code'
    // Assuming Investigative stations list also uses 'sampling_station_code'
    return 'sampling_station_code';
  }

  /// Gets the key for the station's name (river name).
  String _getStationNameKey() {
    // Both In-Situ and Triennial station maps use 'sampling_river'
    // Assuming Investigative stations list also uses 'sampling_river'
    return 'sampling_river';
  }

  /// Gets the key for the station's basin.
  String _getStationBasinKey() {
    // Both In-Situ and Triennial station maps use 'sampling_basin'
    // Assuming Investigative stations list also uses 'sampling_basin'
    return 'sampling_basin';
  }

  // --- END: ADDED HELPER FUNCTIONS ---

  void _initializeStationFilters() {
    final auth = Provider.of<AuthProvider>(context, listen: false);
    // --- MODIFIED: Use helper to get dynamic station list ---
    final allStations = _getStationsForType(auth);

    if (allStations.isNotEmpty) {
      final states = allStations.map((s) => s['state_name'] as String?).whereType<String>().toSet().toList();
      states.sort();
      setState(() {
        _statesList = states;
        // Reset dependent fields on change
        _selectedStateName = null;
        _selectedBasinName = null;
        _selectedStation = null;
        _basinsForState = [];
        _stationsForBasin = [];
      });
    } else {
      // Handle empty list
      setState(() {
        _statesList = [];
        _selectedStateName = null;
        _selectedBasinName = null;
        _selectedStation = null;
        _basinsForState = [];
        _stationsForBasin = [];
      });
    }
  }

  Future<void> _selectDate() async {
    final picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate ?? DateTime.now(),
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
    );

    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
        _dateController.text = DateFormat('yyyy-MM-dd').format(_selectedDate!);
      });
    }
  }

  Future<void> _searchImages() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
        _imageUrls = [];
        _selectedImageUrls.clear();
      });

      // --- MODIFIED: Validate all required fields ---
      if (_selectedStation == null || _selectedDate == null || _selectedSamplingType == null) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Error: Type, Station and date are required.'), backgroundColor: Colors.red),
          );
          setState(() => _isLoading = false);
        }
        return;
      }

      // --- MODIFIED: Use dynamic keys ---
      final stationIdKey = _getStationIdKey();
      final stationId = _selectedStation![stationIdKey];
      // --- END: MODIFIED ---

      final apiService = Provider.of<ApiService>(context, listen: false);

      try {
        final result = await apiService.river.getRiverSamplingImages(
          stationId: stationId,
          samplingDate: _selectedDate!,
          samplingType: _selectedSamplingType!, // <-- Pass dynamic type
        );

        if (mounted && result['success'] == true) {
          // The backend returns a direct list of full URLs, which is great.
          // No need for frontend key-matching like in the marine file.
          final List<String> fetchedUrls = List<String>.from(result['data'] ?? []);

          setState(() {
            _imageUrls = fetchedUrls.toSet().toList(); // Use toSet to remove duplicates
          });

          debugPrint("[Image Request] Successfully received and processed ${_imageUrls.length} image URLs.");

        } else if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(result['message'] ?? 'Failed to fetch images.')),
          );
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('An error occurred: $e')));
        }
      } finally {
        if (mounted) {
          setState(() => _isLoading = false);
        }
      }
    }
  }

  Future<void> _showEmailDialog() async {
    final emailController = TextEditingController();
    final dialogFormKey = GlobalKey<FormState>();

    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setDialogState) {
            bool isSending = false;

            return AlertDialog(
              title: const Text('Send Images via Email'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  if (isSending)
                    const Padding(
                      padding: EdgeInsets.all(16.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [CircularProgressIndicator(), SizedBox(width: 24), Text("Sending...")],
                      ),
                    )
                  else
                    Form(
                      key: dialogFormKey,
                      child: TextFormField(
                        controller: emailController,
                        keyboardType: TextInputType.emailAddress,
                        decoration: const InputDecoration(labelText: 'Recipient Email Address', hintText: 'user@example.com'),
                        validator: (value) {
                          if (value == null || value.isEmpty || !RegExp(r'\S+@\S+\.\S+').hasMatch(value)) {
                            return 'Please enter a valid email address.';
                          }
                          return null;
                        },
                      ),
                    ),
                ],
              ),
              actions: <Widget>[
                TextButton(
                  onPressed: isSending ? null : () => Navigator.of(context).pop(),
                  child: const Text('Cancel'),
                ),
                FilledButton(
                  onPressed: isSending ? null : () async {
                    if (dialogFormKey.currentState!.validate()) {
                      setDialogState(() => isSending = true);
                      await _sendEmailRequestToServer(emailController.text);
                      if (mounted) Navigator.of(context).pop();
                    }
                  },
                  child: const Text('Send'),
                ),
              ],
            );
          },
        );
      },
    );
  }

  Future<void> _sendEmailRequestToServer(String toEmail) async {
    final apiService = Provider.of<ApiService>(context, listen: false);

    try {
      // --- MODIFIED: Use dynamic keys ---
      final stationCode = _selectedStation?[_getStationCodeKey()] ?? 'N/A';
      final stationName = _selectedStation?[_getStationNameKey()] ?? 'N/A';
      // --- END: MODIFIED ---
      final fullStationIdentifier = '$stationCode - $stationName';

      final result = await apiService.river.sendImageRequestEmail(
        recipientEmail: toEmail,
        imageUrls: _selectedImageUrls.toList(),
        stationName: fullStationIdentifier,
        samplingDate: _dateController.text,
      );

      if (mounted) {
        if (result['success'] == true) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Success! Email is being sent by the server.'), backgroundColor: Colors.green),
          );
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Error: ${result['message']}'), backgroundColor: Colors.red),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('An error occurred: $e'), backgroundColor: Colors.red),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("River Image Request")),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(24.0),
          children: [
            Text("Image Search Filters", style: Theme.of(context).textTheme.headlineSmall),
            const SizedBox(height: 24),

            // --- START: MODIFIED ---
            // Sampling Type Dropdown
            DropdownButtonFormField<String>(
              value: _selectedSamplingType,
              items: _samplingTypes.map((type) => DropdownMenuItem(value: type, child: Text(type))).toList(),
              onChanged: (value) => setState(() {
                _selectedSamplingType = value;
                // Re-initialize filters when type changes
                _initializeStationFilters();
              }),
              decoration: const InputDecoration(labelText: 'Sampling Type *', border: OutlineInputBorder()),
              validator: (value) => value == null ? 'Please select a type' : null,
            ),
            // --- END: MODIFIED ---
            const SizedBox(height: 16),

            // State Dropdown
            DropdownSearch<String>(
              items: _statesList,
              selectedItem: _selectedStateName,
              popupProps: const PopupProps.menu(showSearchBox: true, searchFieldProps: TextFieldProps(decoration: InputDecoration(hintText: "Search State..."))),
              dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "Select State *", border: OutlineInputBorder())),
              onChanged: (state) {
                setState(() {
                  _selectedStateName = state;
                  _selectedBasinName = null;
                  _selectedStation = null;
                  final auth = Provider.of<AuthProvider>(context, listen: false);
                  // --- MODIFIED: Use dynamic helpers ---
                  final allStations = _getStationsForType(auth);
                  final basinKey = _getStationBasinKey();
                  final basins = state != null ? allStations.where((s) => s['state_name'] == state).map((s) => s[basinKey] as String?).whereType<String>().toSet().toList() : <String>[];
                  // --- END: MODIFIED ---
                  basins.sort();
                  _basinsForState = basins;
                  _stationsForBasin = [];
                });
              },
              validator: (val) => val == null ? "State is required" : null,
            ),
            const SizedBox(height: 16),

            // Basin Dropdown
            DropdownSearch<String>(
              items: _basinsForState,
              selectedItem: _selectedBasinName,
              enabled: _selectedStateName != null,
              popupProps: const PopupProps.menu(showSearchBox: true, searchFieldProps: TextFieldProps(decoration: InputDecoration(hintText: "Search Basin..."))),
              dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "Select Basin *", border: OutlineInputBorder())),
              onChanged: (basin) {
                setState(() {
                  _selectedBasinName = basin;
                  _selectedStation = null;
                  final auth = Provider.of<AuthProvider>(context, listen: false);
                  // --- MODIFIED: Use dynamic helpers ---
                  final allStations = _getStationsForType(auth);
                  final basinKey = _getStationBasinKey();
                  final stationCodeKey = _getStationCodeKey();
                  _stationsForBasin = basin != null ? (allStations.where((s) => s['state_name'] == _selectedStateName && s[basinKey] == basin).toList()..sort((a, b) => (a[stationCodeKey] ?? '').compareTo(b[stationCodeKey] ?? ''))) : [];
                  // --- END: MODIFIED ---
                });
              },
              validator: (val) => _selectedStateName != null && val == null ? "Basin is required" : null,
            ),
            const SizedBox(height: 16),

            // Station Dropdown
            DropdownSearch<Map<String, dynamic>>(
              items: _stationsForBasin,
              selectedItem: _selectedStation,
              enabled: _selectedBasinName != null,
              // --- MODIFIED: Use dynamic helpers ---
              itemAsString: (station) {
                final code = station[_getStationCodeKey()] ?? 'N/A';
                final name = station[_getStationNameKey()] ?? 'N/A';
                return "$code - $name";
              },
              // --- END: MODIFIED ---
              popupProps: const PopupProps.menu(showSearchBox: true, searchFieldProps: TextFieldProps(decoration: InputDecoration(hintText: "Search Station..."))),
              dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "Select Station *", border: OutlineInputBorder())),
              onChanged: (station) => setState(() => _selectedStation = station),
              validator: (val) => _selectedBasinName != null && val == null ? "Station is required" : null,
            ),
            const SizedBox(height: 16),

            // Date Picker
            TextFormField(
              controller: _dateController,
              readOnly: true,
              decoration: InputDecoration(
                labelText: 'Select Date *',
                hintText: 'Tap to pick a date',
                border: const OutlineInputBorder(),
                suffixIcon: IconButton(icon: const Icon(Icons.calendar_today), onPressed: _selectDate),
              ),
              onTap: _selectDate,
              validator: (val) => val == null || val.isEmpty ? "Date is required" : null,
            ),
            const SizedBox(height: 32),

            // Search Button
            ElevatedButton.icon(
              icon: const Icon(Icons.search),
              label: const Text('Search Images'),
              onPressed: _isLoading ? null : _searchImages,
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                textStyle: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
            const SizedBox(height: 24),
            const Divider(thickness: 1),
            const SizedBox(height: 16),
            Text("Results", style: Theme.of(context).textTheme.headlineSmall),
            const SizedBox(height: 16),
            _buildResults(),

            // Send Email Button
            if (_selectedImageUrls.isNotEmpty) ...[
              const SizedBox(height: 24),
              ElevatedButton.icon(
                icon: const Icon(Icons.email_outlined),
                label: Text('Send (${_selectedImageUrls.length}) Selected Image(s)'),
                onPressed: _showEmailDialog,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).colorScheme.secondary,
                  foregroundColor: Theme.of(context).colorScheme.onSecondary,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildResults() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }
    if (_imageUrls.isEmpty) {
      return const Center(
        child: Text('No images found. Please adjust your filters and search again.', textAlign: TextAlign.center),
      );
    }
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
        crossAxisSpacing: 8,
        mainAxisSpacing: 8,
        childAspectRatio: 1.0,
      ),
      itemCount: _imageUrls.length,
      itemBuilder: (context, index) {
        final imageUrl = _imageUrls[index];
        final isSelected = _selectedImageUrls.contains(imageUrl);

        return GestureDetector(
          onTap: () {
            setState(() {
              if (isSelected) {
                _selectedImageUrls.remove(imageUrl);
              } else {
                _selectedImageUrls.add(imageUrl);
              }
            });
          },
          child: Card(
            clipBehavior: Clip.antiAlias,
            elevation: 2.0,
            child: GridTile(
              child: Stack(
                fit: StackFit.expand,
                children: [
                  Image.network(
                    imageUrl,
                    fit: BoxFit.cover,
                    loadingBuilder: (context, child, loadingProgress) {
                      if (loadingProgress == null) return child;
                      return const Center(child: CircularProgressIndicator(strokeWidth: 2));
                    },
                    errorBuilder: (context, error, stackTrace) {
                      return const Icon(Icons.broken_image, color: Colors.grey, size: 40);
                    },
                  ),
                  if (isSelected)
                    Container(
                      color: Colors.black.withOpacity(0.6),
                      child: const Icon(Icons.check_circle, color: Colors.white, size: 40),
                    ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}