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

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../../../../auth_provider.dart';
import '../../../../models/air_collection_data.dart';
import '../../../../services/air_sampling_service.dart';

class AirManualCollectionWidget extends StatefulWidget {
  final String stationCode;
  final AirCollectionData data;
  final double initialTemp;
  final Future<void> Function() onSubmit;
  final bool isLoading;

  const AirManualCollectionWidget({
    super.key,
    required this.stationCode,
    required this.data,
    required this.initialTemp,
    required this.onSubmit,
    required this.isLoading,
  });

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

class _AirManualCollectionWidgetState extends State<AirManualCollectionWidget> {
  final _formKey = GlobalKey<FormState>();
  bool _isPickingImage = false;

  // General Controllers
  final _collectionDateController = TextEditingController();
  final _collectionTimeController = TextEditingController();
  final _finalTempController = TextEditingController();
  final _remarkController = TextEditingController();
  final _optionalRemark1Controller = TextEditingController();
  final _optionalRemark2Controller = TextEditingController();
  final _optionalRemark3Controller = TextEditingController();
  final _optionalRemark4Controller = TextEditingController();

  // PM10 Controllers
  final _pm10FlowRateController = TextEditingController();
  final _pm10FlowRateResultController = TextEditingController();
  final _pm10TimeController = TextEditingController();
  final _pm10TimeResultController = TextEditingController();
  final _pm10PressureController = TextEditingController();
  final _pm10PressureResultController = TextEditingController();
  final _pm10TavgController = TextEditingController();
  final _pm10QstdController = TextEditingController();
  final _pm10VstdController = TextEditingController();

  // PM2.5 Controllers
  final _pm25FlowRateController = TextEditingController();
  final _pm25FlowRateResultController = TextEditingController();
  final _pm25TimeController = TextEditingController();
  final _pm25TimeResultController = TextEditingController();
  final _pm25PressureController = TextEditingController();
  final _pm25PressureResultController = TextEditingController();
  final _pm25TavgController = TextEditingController();
  final _pm25QstdController = TextEditingController();
  final _pm25VstdController = TextEditingController();

  @override
  void initState() {
    super.initState();
    final now = DateTime.now();
    widget.data.collectionDate ??= DateFormat('yyyy-MM-dd').format(now);
    widget.data.collectionTime ??= DateFormat('HH:mm').format(now);

    _collectionDateController.text = widget.data.collectionDate!;
    _collectionTimeController.text = widget.data.collectionTime!;

    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final currentUser = authProvider.profileData;
    if (currentUser != null) {
      widget.data.collectionUserId = currentUser['user_id'];
      widget.data.collectionUserName = currentUser['first_name'];
    }
  }

  @override
  void dispose() {
    // Dispose all controllers
    _collectionDateController.dispose();
    _collectionTimeController.dispose();
    _finalTempController.dispose();
    _remarkController.dispose();
    _optionalRemark1Controller.dispose();
    _optionalRemark2Controller.dispose();
    _optionalRemark3Controller.dispose();
    _optionalRemark4Controller.dispose();
    _pm10FlowRateController.dispose();
    _pm10FlowRateResultController.dispose();
    _pm10TimeController.dispose();
    _pm10TimeResultController.dispose();
    _pm10PressureController.dispose();
    _pm10PressureResultController.dispose();
    _pm10TavgController.dispose();
    _pm10QstdController.dispose();
    _pm10VstdController.dispose();
    _pm25FlowRateController.dispose();
    _pm25FlowRateResultController.dispose();
    _pm25TimeController.dispose();
    _pm25TimeResultController.dispose();
    _pm25PressureController.dispose();
    _pm25PressureResultController.dispose();
    _pm25TavgController.dispose();
    _pm25QstdController.dispose();
    _pm25VstdController.dispose();
    super.dispose();
  }

  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(() => controller.text = picked.format(context));
    }
  }

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

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

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

  void _calculateVstd(int type) {
    setState(() {
      try {
        // Get the correct controllers for either PM10 or PM2.5
        final flowRateCtrl = type == 1 ? _pm10FlowRateController : _pm25FlowRateController;
        final pressureCtrl = type == 1 ? _pm10PressureController : _pm25PressureController;
        final timeResultCtrl = type == 1 ? _pm10TimeResultController : _pm25TimeResultController;
        final pressureResultCtrl = type == 1 ? _pm10PressureResultController : _pm25PressureResultController;
        final tAvgCtrl = type == 1 ? _pm10TavgController : _pm25TavgController;
        final qStdCtrl = type == 1 ? _pm10QstdController : _pm25QstdController;
        final vstdCtrl = type == 1 ? _pm10VstdController : _pm25VstdController;

        if (flowRateCtrl.text.isEmpty ||
            pressureCtrl.text.isEmpty ||
            _finalTempController.text.isEmpty ||
            timeResultCtrl.text.isEmpty) {
          tAvgCtrl.text = "";
          qStdCtrl.text = "";
          vstdCtrl.text = "0.000";
          return;
        }

        const double hpaToinHg = 0.0295;
        const double inHgToMmHg = 25.4;

        double totalTime_min = double.parse(timeResultCtrl.text);
        double qa_cfm_actual = double.parse(flowRateCtrl.text);

        double pressureHpa = double.parse(pressureCtrl.text);
        double pressureInHg = pressureHpa * hpaToinHg;
        double p_actual_mmHg = pressureInHg * inHgToMmHg;
        pressureResultCtrl.text = pressureInHg.toStringAsFixed(2);

        double t_avg_celsius = (widget.initialTemp + double.parse(_finalTempController.text)) / 2.0;
        tAvgCtrl.text = t_avg_celsius.toStringAsFixed(2);

        double q_std_numerator = qa_cfm_actual * pressureInHg * 298;
        double q_std_denominator = (760 * (273 + t_avg_celsius));
        double q_std = (q_std_denominator == 0) ? 0 : q_std_numerator / q_std_denominator;
        qStdCtrl.text = q_std.toStringAsFixed(5);

        double v_std = q_std * totalTime_min;

        if (type == 1) {
          _pm10VstdController.text = v_std.toStringAsFixed(3);
          widget.data.pm10Vstd = v_std;
        } else {
          _pm25VstdController.text = v_std.toStringAsFixed(3);
          widget.data.pm25Vstd = v_std;
        }

      } catch (e) {
        (type == 1 ? _pm10VstdController : _pm25VstdController).text = "Error";
      }
    });
  }

  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 ||
          widget.data.imageChart == null ||
          widget.data.imageFilterPaper == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('Please attach all required photos before proceeding.'),
            backgroundColor: Colors.red,
          ),
        );
        return;
      }

      widget.data.pm10FlowrateResult = _pm10FlowRateResultController.text;
      widget.data.pm10TotalTimeResult = _pm10TimeResultController.text;
      widget.data.pm10PressureResult = _pm10PressureResultController.text;
      widget.data.pm25FlowrateResult = _pm25FlowRateResultController.text;
      widget.data.pm25TotalTimeResult = _pm25TimeResultController.text;
      widget.data.pm25PressureResult = _pm25PressureResultController.text;

      widget.data.optionalRemark1 = _optionalRemark1Controller.text;
      widget.data.optionalRemark2 = _optionalRemark2Controller.text;
      widget.data.optionalRemark3 = _optionalRemark3Controller.text;
      widget.data.optionalRemark4 = _optionalRemark4Controller.text;

      widget.onSubmit();
    }
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
      child: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Center(
              child: Text('Collection Data',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            ),
            const Divider(height: 30),

            TextFormField(controller: _collectionDateController, readOnly: true, decoration: const InputDecoration(labelText: 'Collection Date', border: OutlineInputBorder(), suffixIcon: Icon(Icons.calendar_today)), onTap: () => _selectDate(context, _collectionDateController), onSaved: (v) => widget.data.collectionDate = v, validator: (v) => v!.isEmpty ? 'Date is required' : null),
            const SizedBox(height: 16),
            TextFormField(controller: _collectionTimeController, readOnly: true, decoration: const InputDecoration(labelText: 'Collection Time', border: OutlineInputBorder(), suffixIcon: Icon(Icons.access_time)), onTap: () => _selectTime(context, _collectionTimeController), onSaved: (v) => widget.data.collectionTime = 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: ['Clear', 'Cloudy', 'Raining'].map((v) => DropdownMenuItem(value: v, child: Text(v))).toList(),
              onChanged: (v) => setState(() => widget.data.weather = v),
              validator: (v) => v == null ? 'Required' : null,
              onSaved: (v) => widget.data.weather = v,
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _finalTempController,
              decoration: const InputDecoration(labelText: 'Final Temperature (°C)', border: OutlineInputBorder()),
              keyboardType: const TextInputType.numberWithOptions(decimal: true),
              validator: (v) => v!.isEmpty ? 'Required' : null,
              onSaved: (v) => widget.data.temperature = double.tryParse(v!),
            ),
            const SizedBox(height: 16),
            DropdownButtonFormField<String>(
              decoration: const InputDecoration(labelText: 'Power Failure Status', border: OutlineInputBorder()),
              value: widget.data.powerFailure,
              items: ['Yes', 'No'].map((v) => DropdownMenuItem(value: v, child: Text(v))).toList(),
              onChanged: (v) => setState(() => widget.data.powerFailure = v),
              validator: (v) => v == null ? 'Required' : null,
              onSaved: (v) => widget.data.powerFailure = v,
            ),
            const Padding(padding: EdgeInsets.symmetric(vertical: 20), child: Text("PM10 Data", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16))),
            _buildResultRow(_pm10FlowRateController, "Flow Rate (cfm)", _pm10FlowRateResultController, "Result (m³/min)", (v) => setState(() => _pm10FlowRateResultController.text = ((double.tryParse(v) ?? 0) * 0.0283).toStringAsFixed(4)), (v) => widget.data.pm10Flowrate = double.tryParse(v!)),
            _buildResultRow(_pm10TimeController, "Total Time (hours)", _pm10TimeResultController, "Result (mins)", (v) => setState(() => _pm10TimeResultController.text = ((double.tryParse(v) ?? 0) * 60).toStringAsFixed(2)), (v) => widget.data.pm10TotalTime = v),
            _buildResultRow(_pm10PressureController, "Pressure (hPa)", _pm10PressureResultController, "Result (inHg)", (v) => _calculateVstd(1), (v) => widget.data.pm10Pressure = double.tryParse(v!)),

            const SizedBox(height: 8),
            TextFormField(
              controller: _pm10TavgController,
              readOnly: true,
              decoration: const InputDecoration(
                  labelText: 'Ambient Temperature [Tavg=(T1+T2)/2] (°C)',
                  border: OutlineInputBorder(),
                  filled: true,
                  fillColor: Colors.black12),
            ),
            const SizedBox(height: 8),
            TextFormField(
              controller: _pm10QstdController,
              readOnly: true,
              decoration: const InputDecoration(
                  labelText: 'Flowrate (Standard Air), QSTD (m³/min)',
                  border: OutlineInputBorder(),
                  filled: true,
                  fillColor: Colors.black12),
            ),
            const SizedBox(height: 8),

            TextFormField(controller: _pm10VstdController, readOnly: true, decoration: const InputDecoration(labelText: 'VSTD PM10 (m³)', border: OutlineInputBorder(), filled: true, fillColor: Colors.black12)),

            const Padding(padding: EdgeInsets.symmetric(vertical: 20), child: Text("PM2.5 Data", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16))),
            _buildResultRow(_pm25FlowRateController, "Flow Rate (cfm)", _pm25FlowRateResultController, "Result (m³/min)", (v) => setState(() => _pm25FlowRateResultController.text = ((double.tryParse(v) ?? 0) * 0.0283).toStringAsFixed(4)), (v) => widget.data.pm25Flowrate = double.tryParse(v!)),
            _buildResultRow(_pm25TimeController, "Total Time (hours)", _pm25TimeResultController, "Result (mins)", (v) => setState(() => _pm25TimeResultController.text = ((double.tryParse(v) ?? 0) * 60).toStringAsFixed(2)), (v) => widget.data.pm25TotalTime = v),
            _buildResultRow(_pm25PressureController, "Pressure (hPa)", _pm25PressureResultController, "Result (inHg)", (v) => _calculateVstd(2), (v) => widget.data.pm25Pressure = double.tryParse(v!)),

            const SizedBox(height: 8),
            TextFormField(
              controller: _pm25TavgController,
              readOnly: true,
              decoration: const InputDecoration(
                  labelText: 'Ambient Temperature [Tavg=(T1+T2)/2] (°C)',
                  border: OutlineInputBorder(),
                  filled: true,
                  fillColor: Colors.black12),
            ),
            const SizedBox(height: 8),
            TextFormField(
              controller: _pm25QstdController,
              readOnly: true,
              decoration: const InputDecoration(
                  labelText: 'Flowrate (Standard Air), QSTD (m³/min)',
                  border: OutlineInputBorder(),
                  filled: true,
                  fillColor: Colors.black12),
            ),
            const SizedBox(height: 8),

            TextFormField(controller: _pm25VstdController, readOnly: true, decoration: const InputDecoration(labelText: 'VSTD PM2.5 (m³)', border: OutlineInputBorder(), filled: true, fillColor: Colors.black12)),

            const SizedBox(height: 16),
            TextFormField(
              controller: _remarkController,
              decoration: const InputDecoration(labelText: 'Remark (Optional)', border: OutlineInputBorder()),
              maxLines: 3,
              onSaved: (v) => widget.data.remarks = v,
            ),

            const SizedBox(height: 24),
            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),
            _buildImagePicker('Chart', 'chart', widget.data.imageChart, (file) => widget.data.imageChart = file, isRequired: true),
            _buildImagePicker('Filter Paper', 'filter_paper', widget.data.imageFilterPaper, (file) => widget.data.imageFilterPaper = 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(
                  backgroundColor: Colors.green,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
                child: widget.isLoading
                    ? const CircularProgressIndicator(color: Colors.white)
                    : const Text('Submit Collection Data', style: TextStyle(color: Colors.white)),
              ),
            ),
          ],
        ),
      ),
    );
  }

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

  Widget _buildResultRow(TextEditingController inputCtrl, String inputLabel, TextEditingController resultCtrl, String resultLabel, Function(String) onChanged, Function(String?) onSaved) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Row(
        children: [
          Expanded(
            child: TextFormField(
              controller: inputCtrl,
              decoration: InputDecoration(labelText: inputLabel, border: const OutlineInputBorder()),
              keyboardType: const TextInputType.numberWithOptions(decimal: true),
              onChanged: onChanged,
              onSaved: onSaved,
              validator: (v) => v!.isEmpty ? 'Required' : null,
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: TextFormField(
              controller: resultCtrl,
              readOnly: true,
              decoration: InputDecoration(labelText: resultLabel, border: const OutlineInputBorder(), filled: true, fillColor: Colors.black12),
            ),
          ),
        ],
      ),
    );
  }
}