// lib/screens/river/investigative/river_investigative_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 RiverInvestigativeImageRequest extends StatelessWidget {
  const RiverInvestigativeImageRequest({super.key});

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

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

  @override
  State<RiverInvestigativeImageRequestScreen> createState() =>
      _RiverInvestigativeImageRequestScreenState();
}

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

  final String _selectedSamplingType = 'Investigative Sampling';

  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 = {};

  // --- MODIFICATION: Added flag to track initialization ---
  bool _filtersInitialized = false;

  @override
  void initState() {
    super.initState();
    // We NO LONGER initialize filters here, as data isn't ready.
  }

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

  /// Gets the correct list of stations from AuthProvider.
  List<Map<String, dynamic>> _getStationsForType(AuthProvider auth) {
    return auth.riverManualStations ?? [];
  }

  /// Gets the key for the station's unique ID (for API calls).
  String _getStationIdKey() {
    return 'station_id';
  }

  /// Gets the key for the station's human-readable code.
  String _getStationCodeKey() {
    return 'sampling_station_code';
  }

  /// Gets the key for the station's name (river name).
  String _getStationNameKey() {
    return 'sampling_river';
  }

  /// Gets the key for the station's basin.
  String _getStationBasinKey() {
    return 'sampling_basin';
  }

  // --- MODIFICATION: This is now called by the build method ---
  void _initializeStationFilters() {
    final auth = Provider.of<AuthProvider>(context, listen: false);
    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;
        _selectedStateName = null;
        _selectedBasinName = null;
        _selectedStation = null;
        _basinsForState = [];
        _stationsForBasin = [];
      });
    } else {
      setState(() {
        _statesList = [];
        _selectedStateName = null;
        _selectedBasinName = null;
        _selectedStation = null;
        _basinsForState = [];
        _stationsForBasin = [];
      });
    }
    // Set flag to prevent re-initialization
    _filtersInitialized = true;
  }

  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();
      });

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

      final stationIdKey = _getStationIdKey();
      final stationId = _selectedStation![stationIdKey];

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

      try {
        final result = await apiService.river.getRiverSamplingImages(
          stationId: stationId,
          samplingDate: _selectedDate!,
          samplingType: _selectedSamplingType, // "Investigative Sampling"
        );

        if (mounted && result['success'] == true) {
          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 {
      final stationCode = _selectedStation?[_getStationCodeKey()] ?? 'N/A';
      final stationName = _selectedStation?[_getStationNameKey()] ?? 'N/A';
      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) {
    // --- MODIFICATION: Wrap with Consumer ---
    return Consumer<AuthProvider>(
      builder: (context, auth, child) {

        // --- 1. Show loading screen if data isn't ready ---
        if (auth.isBackgroundLoading) {
          return Scaffold(
            appBar: AppBar(title: const Text("River Investigative Image Request")),
            body: const Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircularProgressIndicator(),
                  SizedBox(height: 16),
                  Text("Loading station data..."),
                ],
              ),
            ),
          );
        }

        // --- 2. Initialize filters ONLY when data is ready ---
        if (!auth.isBackgroundLoading && !_filtersInitialized) {
          // Data is loaded, but our local lists are empty. Initialize them.
          // Schedule this for after the build pass to avoid errors.
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (mounted) {
              _initializeStationFilters();
            }
          });
        }

        // --- 3. Build the actual UI ---
        return Scaffold(
          appBar: AppBar(title: const Text("River Investigative 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),

                TextFormField(
                  initialValue: _selectedSamplingType, // "Investigative Sampling"
                  readOnly: true,
                  decoration: InputDecoration(
                    labelText: 'Sampling Type *',
                    border: const OutlineInputBorder(),
                    filled: true,
                    fillColor: Theme.of(context).inputDecorationTheme.fillColor?.withOpacity(0.5), // Make it look disabled
                  ),
                ),
                const SizedBox(height: 16),

                // State Dropdown
                DropdownSearch<String>(
                  items: _statesList, // This list will be populated
                  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);
                      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>[];
                      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);
                      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] ?? '')))
                          : [];
                    });
                  },
                  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,
                  itemAsString: (station) {
                    final code = station[_getStationCodeKey()] ?? 'N/A';
                    final name = station[_getStationNameKey()] ?? 'N/A';
                    return "$code - $name";
                  },
                  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),
                    ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}