// lib/screens/air/manual/widgets/air_manual_installation.dart

import 'package:flutter/material.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import 'package:dropdown_search/dropdown_search.dart';
import 'package:intl/intl.dart';
import '../../../../auth_provider.dart';
import '../../../../models/air_installation_data.dart';
import '../../../../services/air_sampling_service.dart';
// --- ADDED: Import ApiService for dependency injection ---
import '../../../../services/api_service.dart';
// --- REMOVED: Import of local_storage_service.dart as it is no longer used for logging ---
import '../../../../services/telegram_service.dart'; // Import TelegramService

class AirManualInstallationWidget extends StatefulWidget {
  final AirInstallationData data;
  final Future<void> Function() onSubmit;
  final bool isLoading;

  const AirManualInstallationWidget({
    super.key,
    required this.data,
    required this.onSubmit,
    required this.isLoading,
  });

  @override
  _AirManualInstallationWidgetState createState() =>
      _AirManualInstallationWidgetState();
}

class _AirManualInstallationWidgetState extends State<AirManualInstallationWidget> {
  final _formKey = GlobalKey<FormState>();

  bool _isDataInitialized = false;
  bool _isPickingImage = false;

  List<Map<String, dynamic>> _allClients = [];
  List<Map<String, dynamic>> _allStations = [];

  String? _selectedRegion;
  String? _selectedState;
  Map<String, dynamic>? _selectedLocation;
  Map<String, dynamic>? _selectedClient;

  List<String> _statesForSelectedRegion = [];
  List<Map<String, dynamic>> _locationsForSelectedState = [];

  final TextEditingController _samplingDateController = TextEditingController();
  final TextEditingController _installationDateController = TextEditingController();
  final TextEditingController _installationTimeController = TextEditingController();
  final TextEditingController _tempController = TextEditingController();
  final TextEditingController _pm10Controller = TextEditingController();
  final TextEditingController _pm25Controller = TextEditingController();
  final TextEditingController _remarkController = TextEditingController();

  final TextEditingController _optionalRemark1Controller = TextEditingController();
  final TextEditingController _optionalRemark2Controller = TextEditingController();
  final TextEditingController _optionalRemark3Controller = TextEditingController();
  final TextEditingController _optionalRemark4Controller = TextEditingController();


  static const List<String> _regions = ["NORTHERN", "CENTRAL", "SOUTHERN", "EAST COAST", "EAST MALAYSIA"];
  static const List<String> _weatherOptions = ['Clear', 'Cloudy', 'Raining'];

  static const Map<String, List<String>> _regionToStatesMap = {
    "NORTHERN": ["Perlis", "Kedah", "Penang", "Perak"],
    "CENTRAL": ["Selangor", "Kuala Lumpur", "Putrajaya", "Negeri Sembilan"],
    "SOUTHERN": ["Malacca", "Johor"],
    "EAST COAST": ["Kelantan", "Terengganu", "Pahang"],
    "EAST MALAYSIA": ["Sabah", "Sarawak", "Labuan"],
  };


  @override
  void initState() {
    super.initState();
    _samplingDateController.text = widget.data.samplingDate ?? '';
    _installationDateController.text = widget.data.installationDate ?? '';
    _installationTimeController.text = widget.data.installationTime ?? '';
    _tempController.text = widget.data.temp ?? '';
    _pm10Controller.text = widget.data.pm10FilterId ?? '';
    _pm25Controller.text = widget.data.pm25FilterId ?? '';
    _remarkController.text = widget.data.remark ?? '';
    _optionalRemark1Controller.text = widget.data.optionalRemark1 ?? '';
    _optionalRemark2Controller.text = widget.data.optionalRemark2 ?? '';
    _optionalRemark3Controller.text = widget.data.optionalRemark3 ?? '';
    _optionalRemark4Controller.text = widget.data.optionalRemark4 ?? '';
  }

  void _initializeData(AuthProvider authProvider) {
    final currentUser = authProvider.profileData;
    final clients = authProvider.airClients;
    final stations = authProvider.airManualStations;

    if (currentUser != null) {
      widget.data.installationUserId = currentUser['user_id'];
      widget.data.installationUserName = currentUser['first_name'];
    }

    if (clients != null && clients.isNotEmpty) {
      _allClients = clients;
      final defaultClient = _allClients.firstWhere(
            (c) => c['client_name'] == 'Jabatan Alam Sekitar',
        orElse: () => _allClients.first,
      );
      _selectedClient = defaultClient;
      widget.data.clientId = defaultClient['client_id'];
    }

    if (stations != null) {
      _allStations = stations;
    }
  }

  void _onRegionChanged(String? region) {
    if (region == null) return;
    final statesInRegion = _regionToStatesMap[region] ?? [];

    final availableStates = _allStations
        .where((s) => statesInRegion.contains(s['state_name']))
        .map((s) => s['state_name'] as String)
        .toSet()
        .toList();
    availableStates.sort();

    setState(() {
      _selectedRegion = region;
      _statesForSelectedRegion = availableStates;
      _selectedState = null;
      _locationsForSelectedState = [];
      _selectedLocation = null;
      widget.data.region = region;
    });
  }

  void _onStateChanged(String? stateName) {
    if (stateName == null) return;
    final filteredLocations = _allStations.where((s) => s['state_name'] == stateName).toList();
    setState(() {
      _selectedState = stateName;
      _locationsForSelectedState = filteredLocations;
      _selectedLocation = null;
      widget.data.stateID = stateName;
    });
  }

  Future<void> _selectDate(BuildContext context, TextEditingController controller) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );
    if (picked != null) {
      setState(() {
        controller.text = DateFormat('yyyy-MM-dd').format(picked);
      });
    }
  }

  Future<void> _selectTime(BuildContext context, TextEditingController controller) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );
    if (picked != null) {
      setState(() {
        final String hour = picked.hour.toString().padLeft(2, '0');
        final String minute = picked.minute.toString().padLeft(2, '0');
        controller.text = '$hour:$minute';
      });
    }
  }

  void _showOrientationDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("Incorrect Image Orientation"),
          content: const Text("Required photos must be taken in a horizontal (landscape) orientation."),
          actions: [
            TextButton(
              child: const Text("OK"),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
        );
      },
    );
  }

  void _setImage(Function(File?) setImageCallback, ImageSource source, String imageInfo, {required bool isRequired}) async {
    if (_isPickingImage) return;
    setState(() => _isPickingImage = true);

    if (widget.data.stationID == null || widget.data.stationID!.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Please select a station before attaching images.'),
          backgroundColor: Colors.orange,
        ),
      );
      setState(() => _isPickingImage = false);
      return;
    }

    final service = Provider.of<AirSamplingService>(context, listen: false);
    final stationCode = widget.data.stationID!;

    final File? imageFile = await service.pickAndProcessImage(
      source,
      stationCode: stationCode,
      imageInfo: imageInfo.toUpperCase(),
      processType: 'COLLECT',
      isRequired: isRequired,
    );

    if (imageFile == null && isRequired) {
      _showOrientationDialog();
    } else if (imageFile != null) {
      setState(() {
        setImageCallback(imageFile);
      });
    }
    setState(() => _isPickingImage = false);
  }

  Widget _buildImagePicker(String title, String imageInfo, File? imageFile, Function(File?) setImageCallback, {TextEditingController? remarkController, bool isRequired = false}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(title + (isRequired ? ' *' : ''), style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
          const SizedBox(height: 8),
          if (imageFile != null)
            Stack(
              alignment: Alignment.topRight,
              children: [
                ClipRRect(
                    borderRadius: BorderRadius.circular(8.0),
                    child: Image.file(imageFile, key: UniqueKey(), height: 150, width: double.infinity, fit: BoxFit.cover)),
                Container(
                  margin: const EdgeInsets.all(4),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.6),
                    shape: BoxShape.circle,
                  ),
                  child: IconButton(
                    visualDensity: VisualDensity.compact,
                    icon: const Icon(Icons.close, color: Colors.white, size: 20),
                    onPressed: () => setState(() => setImageCallback(null)),
                  ),
                ),
              ],
            )
          else
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton.icon(onPressed: _isPickingImage ? null : () => _setImage(setImageCallback, ImageSource.camera, imageInfo, isRequired: isRequired), icon: const Icon(Icons.camera_alt), label: const Text("Camera")),
                ElevatedButton.icon(onPressed: _isPickingImage ? null : () => _setImage(setImageCallback, ImageSource.gallery, imageInfo, isRequired: isRequired), icon: const Icon(Icons.photo_library), label: const Text("Gallery")),
              ],
            ),
          if (remarkController != null)
            Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: TextFormField(
                controller: remarkController,
                decoration: InputDecoration(
                  labelText: 'Remarks for $title',
                  hintText: 'Add an optional remark...',
                  border: const OutlineInputBorder(),
                ),
              ),
            ),
        ],
      ),
    );
  }

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

      if (widget.data.imageFront == null ||
          widget.data.imageBack == null ||
          widget.data.imageLeft == null ||
          widget.data.imageRight == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Please attach all required photos before proceeding.'),
            backgroundColor: Colors.red,
          ),
        );
        return;
      }

      widget.data.optionalRemark1 = _optionalRemark1Controller.text;
      widget.data.optionalRemark2 = _optionalRemark2Controller.text;
      widget.data.optionalRemark3 = _optionalRemark3Controller.text;
      widget.data.optionalRemark4 = _optionalRemark4Controller.text;
      widget.onSubmit();
    }
  }

  @override
  void dispose() {
    _samplingDateController.dispose();
    _installationDateController.dispose();
    _installationTimeController.dispose();
    _tempController.dispose();
    _pm10Controller.dispose();
    _pm25Controller.dispose();
    _remarkController.dispose();
    _optionalRemark1Controller.dispose();
    _optionalRemark2Controller.dispose();
    _optionalRemark3Controller.dispose();
    _optionalRemark4Controller.dispose();
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    final authProvider = Provider.of<AuthProvider>(context);

    final isProviderDataReady = authProvider.airClients != null &&
        authProvider.airManualStations != null;

    if (isProviderDataReady && !_isDataInitialized) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (mounted) {
          _initializeData(authProvider);
          setState(() {
            _isDataInitialized = true;
          });
        }
      });
    }

    if (!_isDataInitialized) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text("Loading master data..."),
          ],
        ),
      );
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Center(child: Text('Installation Details', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold))),
            const Divider(height: 30),

            DropdownSearch<Map<String, dynamic>>(
              items: _allClients,
              selectedItem: _selectedClient,
              itemAsString: (c) => c['client_name'],
              popupProps: const PopupProps.menu(showSearchBox: true, fit: FlexFit.loose),
              dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "Client", border: OutlineInputBorder())),
              onChanged: (value) => setState(() => _selectedClient = value),
              onSaved: (v) => widget.data.clientId = v?['client_id'],
              validator: (v) => v == null ? 'Client is required' : null,
            ),
            const SizedBox(height: 16),

            TextFormField(controller: _samplingDateController, readOnly: true, decoration: const InputDecoration(labelText: 'Sampling Date (Initiated)', border: OutlineInputBorder(), filled: true, fillColor: Colors.black12)),
            const SizedBox(height: 16),

            DropdownSearch<String>(
              items: _regions,
              selectedItem: _selectedRegion,
              popupProps: const PopupProps.menu(showSearchBox: true, fit: FlexFit.loose),
              dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "Region", border: OutlineInputBorder())),
              onChanged: _onRegionChanged,
              validator: (v) => v == null ? 'Region is required' : null,
            ),
            const SizedBox(height: 16),

            DropdownSearch<String>(
              items: _statesForSelectedRegion,
              selectedItem: _selectedState,
              enabled: _selectedRegion != null,
              popupProps: const PopupProps.menu(showSearchBox: true, fit: FlexFit.loose),
              dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "State", border: OutlineInputBorder())),
              onChanged: _onStateChanged,
              validator: (v) => _selectedRegion != null && v == null ? 'State is required' : null,
            ),
            const SizedBox(height: 16),

            DropdownSearch<Map<String, dynamic>>(
              items: _locationsForSelectedState,
              selectedItem: _selectedLocation,
              enabled: _selectedState != null,
              itemAsString: (s) => "${s['station_code']} - ${s['station_name']}",
              popupProps: const PopupProps.menu(showSearchBox: true, fit: FlexFit.loose),
              dropdownDecoratorProps: const DropDownDecoratorProps(dropdownSearchDecoration: InputDecoration(labelText: "Station ID / Location", border: OutlineInputBorder())),
              onChanged: (value) => setState(() {
                _selectedLocation = value;
                widget.data.stationID = value?['station_code'];
                widget.data.locationName = value?['station_name'];
              }),
              onSaved: (v) {
                widget.data.stationID = v?['station_code'];
                widget.data.locationName = v?['station_name'];
              },
              validator: (v) => _selectedState != null && v == null ? 'Location is required' : null,
            ),
            const SizedBox(height: 16),

            TextFormField(controller: _installationDateController, readOnly: true, decoration: const InputDecoration(labelText: 'Installation Date', border: OutlineInputBorder(), suffixIcon: Icon(Icons.calendar_today)), onTap: () => _selectDate(context, _installationDateController), onSaved: (v) => widget.data.installationDate = v, validator: (v) => v!.isEmpty ? 'Date is required' : null),
            const SizedBox(height: 16),
            TextFormField(controller: _installationTimeController, readOnly: true, decoration: const InputDecoration(labelText: 'Installation Time', border: OutlineInputBorder(), suffixIcon: Icon(Icons.access_time)), onTap: () => _selectTime(context, _installationTimeController), onSaved: (v) => widget.data.installationTime = v, validator: (v) => v!.isEmpty ? 'Time is required' : null),
            const SizedBox(height: 16),
            DropdownButtonFormField<String>(decoration: const InputDecoration(labelText: 'Weather', border: OutlineInputBorder()), value: widget.data.weather, items: _weatherOptions.map((v) => DropdownMenuItem(value: v, child: Text(v))).toList(), onChanged: (v) => setState(() => widget.data.weather = v), onSaved: (v) => widget.data.weather = v, validator: (v) => v == null ? 'Weather is required' : null),
            const SizedBox(height: 16),
            TextFormField(controller: _tempController, decoration: const InputDecoration(labelText: 'Temperature (°C)', border: OutlineInputBorder()), keyboardType: const TextInputType.numberWithOptions(decimal: true), validator: (v) => v!.isEmpty ? 'Temperature is required' : null, onSaved: (v) => widget.data.temp = v),
            SwitchListTile(title: const Text("Power Failure?"), value: widget.data.powerFailure, onChanged: (bool value) => setState(() => widget.data.powerFailure = value)),
            TextFormField(controller: _pm10Controller, enabled: !widget.data.powerFailure, decoration: const InputDecoration(labelText: 'PM10 Filter ID', border: OutlineInputBorder()), validator: (v) => !widget.data.powerFailure && v!.isEmpty ? 'Required' : null, onSaved: (v) => widget.data.pm10FilterId = v),
            const SizedBox(height: 16),
            TextFormField(controller: _pm25Controller, enabled: !widget.data.powerFailure, decoration: const InputDecoration(labelText: 'PM2.5 Filter ID', border: OutlineInputBorder()), validator: (v) => !widget.data.powerFailure && v!.isEmpty ? 'Required' : null, onSaved: (v) => widget.data.pm25FilterId = v),
            const SizedBox(height: 16),
            TextFormField(controller: _remarkController, decoration: const InputDecoration(labelText: 'Remark (Optional)', border: OutlineInputBorder()), maxLines: 3, onSaved: (v) => widget.data.remark = v),
            const SizedBox(height: 16),

            const Text("Required Photos", style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            _buildImagePicker('Site Picture (Front)', 'front', widget.data.imageFront, (file) => widget.data.imageFront = file, isRequired: true),
            _buildImagePicker('Site Picture (Back)', 'back', widget.data.imageBack, (file) => widget.data.imageBack = file, isRequired: true),
            _buildImagePicker('Site Picture (Left)', 'left', widget.data.imageLeft, (file) => widget.data.imageLeft = file, isRequired: true),
            _buildImagePicker('Site Picture (Right)', 'right', widget.data.imageRight, (file) => widget.data.imageRight = file, isRequired: true),

            const SizedBox(height: 24),
            const Text("Optional Photos", style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            _buildImagePicker('Optional Photo 1', 'optional_01', widget.data.optionalImage1, (file) => widget.data.optionalImage1 = file, remarkController: _optionalRemark1Controller),
            _buildImagePicker('Optional Photo 2', 'optional_02', widget.data.optionalImage2, (file) => widget.data.optionalImage2 = file, remarkController: _optionalRemark2Controller),
            _buildImagePicker('Optional Photo 3', 'optional_03', widget.data.optionalImage3, (file) => widget.data.optionalImage3 = file, remarkController: _optionalRemark3Controller),
            _buildImagePicker('Optional Photo 4', 'optional_04', widget.data.optionalImage4, (file) => widget.data.optionalImage4 = file, remarkController: _optionalRemark4Controller),


            const SizedBox(height: 30),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: widget.isLoading ? null : _onSubmitPressed,
                style: ElevatedButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 16), backgroundColor: Theme.of(context).primaryColor),
                child: widget.isLoading ? const CircularProgressIndicator(color: Colors.white) : const Text('Submit Installation', style: TextStyle(color: Colors.white)),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
