// lib/screens/marine/manual/tarball_sampling_step3_summary.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'package:environment_monitoring_app/auth_provider.dart';
import 'package:environment_monitoring_app/models/tarball_data.dart';
import 'package:environment_monitoring_app/services/marine_tarball_sampling_service.dart';
import 'package:environment_monitoring_app/screens/marine/manual/reports/npe_report_from_tarball.dart';


class TarballSamplingStep3Summary extends StatefulWidget {
  final TarballSamplingData data;
  const TarballSamplingStep3Summary({super.key, required this.data});

  @override
  State<TarballSamplingStep3Summary> createState() => _TarballSamplingStep3SummaryState();
}

class _TarballSamplingStep3SummaryState extends State<TarballSamplingStep3Summary> {
  bool _isLoading = false;

  Future<void> _submitForm() async {
    // Check if the classification indicates a tarball incident.
    // We assume 'None' has an ID of 1.
    final bool isIncident = widget.data.classificationId != 1;
    bool proceedWithSubmission = false;

    if (isIncident) {
      // Show a dialog to inform the user about the redirection to NPE report.
      final bool? userConfirmed = await showDialog<bool>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('Tarball Incident Detected'),
            content: const Text(
                'You have selected a tarball classification that indicates an incident. You will be redirected to the NPE report screen after submission.'),
            actions: <Widget>[
              TextButton(
                child: const Text('Cancel'),
                onPressed: () => Navigator.of(context).pop(false),
              ),
              FilledButton(
                child: const Text('Okay'),
                onPressed: () => Navigator.of(context).pop(true),
              ),
            ],
          );
        },
      );

      if (userConfirmed == true) {
        proceedWithSubmission = true;
      }
    } else {
      // For "None" classification, proceed without a dialog.
      proceedWithSubmission = true;
    }

    if (!proceedWithSubmission) {
      return; // User cancelled, so we stop here.
    }

    setState(() => _isLoading = true);

    final authProvider = Provider.of<AuthProvider>(context, listen: false);
    final appSettings = authProvider.appSettings;
    final tarballService = Provider.of<MarineTarballSamplingService>(context, listen: false);

    // Delegate the entire submission process to the dedicated service.
    final result = await tarballService.submitTarballSample(
      data: widget.data,
      appSettings: appSettings,
      context: context,
    );

    if (!mounted) return;

    setState(() => _isLoading = false);

    final message = result['message'] ?? 'An unknown error occurred.';
    final color = (result['success'] == true) ? Colors.green : Colors.red;

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: color, duration: const Duration(seconds: 4)),
    );

    // After a successful submission, decide where to navigate.
    if (result['success'] == true) {
      if (isIncident) {
        // Convert the tarball data to the format needed for the NPE report.
        final npeData = widget.data.toNpeReportData();
        // Navigate to the NPE report screen, passing the pre-filled data.
        Navigator.pushAndRemoveUntil(
          context,
          MaterialPageRoute(
            builder: (context) => NPEReportFromTarball(initialData: npeData),
          ),
              (route) => route.isFirst,
        );
      } else {
        // If not an incident, go back to the home screen as before.
        Navigator.of(context).popUntil((route) => route.isFirst);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Summary & Confirmation (3/3)")),
      body: ListView(
        padding: const EdgeInsets.all(16.0),
        children: [
          Text(
            "Please review all information before submitting.",
            style: Theme.of(context).textTheme.titleMedium,
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 16),

          _buildSectionCard(
            "Sampling Information",
            [
              _buildDetailRow("1st Sampler:", widget.data.firstSampler),
              _buildDetailRow("2nd Sampler:", widget.data.secondSampler?['first_name']?.toString()),
              _buildDetailRow("Sampling Date:", widget.data.samplingDate),
              _buildDetailRow("Sampling Time:", widget.data.samplingTime),
            ],
          ),

          _buildSectionCard(
            "Station Information",
            [
              _buildDetailRow("State:", widget.data.selectedStateName),
              _buildDetailRow("Category:", widget.data.selectedCategoryName),
              _buildDetailRow("Station ID:", widget.data.selectedStation?['tbl_station_code']?.toString()),
              _buildDetailRow("Station Name:", widget.data.selectedStation?['tbl_station_name']?.toString()),
              _buildDetailRow("Station Latitude:", widget.data.stationLatitude),
              _buildDetailRow("Station Longitude:", widget.data.stationLongitude),
            ],
          ),

          _buildSectionCard(
            "Location Verification",
            [
              _buildDetailRow("Current Latitude:", widget.data.currentLatitude),
              _buildDetailRow("Current Longitude:", widget.data.currentLongitude),
              _buildDetailRow("Distance Difference:",
                  widget.data.distanceDifference != null
                      ? "${(widget.data.distanceDifference! * 1000).toStringAsFixed(0)} meters"
                      : "N/A"
              ),
              _buildDetailRow("Distance Remarks:", widget.data.distanceDifferenceRemarks),
            ],
          ),

          _buildSectionCard(
            "On-Site Information & Photos",
            [
              Consumer<AuthProvider>(
                builder: (context, auth, child) {
                  String classificationName = 'N/A';
                  if (widget.data.classificationId != null && auth.tarballClassifications != null) {
                    try {
                      final classification = auth.tarballClassifications!.firstWhere(
                            (c) => c['classification_id'] == widget.data.classificationId,
                      );
                      classificationName = classification['classification_name'] ?? 'ID not found';
                    } catch (e) {
                      classificationName = 'ID: ${widget.data.classificationId}';
                    }
                  }
                  return _buildDetailRow("Tarball Classification:", classificationName);
                },
              ),
              const Divider(height: 24),
              _buildImageCard("Left Side Coastal View", widget.data.leftCoastalViewImage),
              _buildImageCard("Right Side Coastal View", widget.data.rightCoastalViewImage),
              _buildImageCard("Drawing Vertical Lines", widget.data.verticalLinesImage),
              _buildImageCard("Drawing Horizontal Line", widget.data.horizontalLineImage),
              Visibility(
                visible: widget.data.classificationId != 1,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Divider(height: 24),
                    Text("Optional Photos", style: Theme.of(context).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold)),
                    const SizedBox(height: 8),
                    _buildImageCard("Optional Photo 1", widget.data.optionalImage1, remark: widget.data.optionalRemark1),
                    _buildImageCard("Optional Photo 2", widget.data.optionalImage2, remark: widget.data.optionalRemark2),
                    _buildImageCard("Optional Photo 3", widget.data.optionalImage3, remark: widget.data.optionalRemark3),
                    _buildImageCard("Optional Photo 4", widget.data.optionalImage4, remark: widget.data.optionalRemark4),
                  ],
                ),
              ),
            ],
          ),

          const SizedBox(height: 24),
          _isLoading
              ? const Center(child: CircularProgressIndicator())
              : ElevatedButton.icon(
            onPressed: _submitForm,
            icon: const Icon(Icons.cloud_upload),
            label: const Text('Confirm & Submit'),
            style: ElevatedButton.styleFrom(
              padding: const EdgeInsets.symmetric(vertical: 16),
              textStyle: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  Widget _buildSectionCard(String title, List<Widget> children) {
    return Card(
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: Theme.of(context).textTheme.titleLarge?.copyWith(
                fontWeight: FontWeight.bold,
                color: Theme.of(context).primaryColor,
              ),
            ),
            const Divider(height: 20, thickness: 1),
            ...children,
          ],
        ),
      ),
    );
  }

  Widget _buildDetailRow(String label, String? value) {
    final bool isValueAvailable = value != null && value.isNotEmpty;
    return Visibility(
      visible: isValueAvailable,
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 6.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              flex: 2,
              child: Text(
                label,
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              flex: 3,
              child: Text(
                value ?? 'N/A',
                style: Theme.of(context).textTheme.bodyLarge,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildImageCard(String title, File? image, {String? remark}) {
    if (image == null && (remark == null || remark.isEmpty)) {
      return const SizedBox.shrink();
    }
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(title, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
          const SizedBox(height: 8),
          if (image != null)
            ClipRRect(
              borderRadius: BorderRadius.circular(8.0),
              child: Image.file(image, key: UniqueKey(), height: 200, width: double.infinity, fit: BoxFit.cover),
            )
          else
            Container(
              height: 100,
              width: double.infinity,
              decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(8.0),
                  border: Border.all(color: Colors.grey[300]!)
              ),
              child: const Center(child: Text('No Image Attached', style: TextStyle(color: Colors.grey))),
            ),
          if (remark != null && remark.isNotEmpty)
            Padding(
              padding: const EdgeInsets.only(top: 8.0),
              child: Text('Remark: $remark', style: const TextStyle(fontStyle: FontStyle.italic, color: Colors.white70)),
            ),
        ],
      ),
    );
  }
}