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_api_service.dart';
import 'package:environment_monitoring_app/services/local_storage_service.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> {
  final MarineApiService _marineApiService = MarineApiService();
  final LocalStorageService _localStorageService = LocalStorageService();
  bool _isLoading = false;

  Future<void> _submitForm() async {
    setState(() => _isLoading = true);

    // Step 1: Orchestrated Server Submission
    final result = await _marineApiService.submitTarballSample(
      formData: widget.data.toFormData(),
      imageFiles: widget.data.toImageFiles(),
    );

    if (!mounted) return;

    // Step 2: Update the data model with submission results
    widget.data.submissionStatus = result['status'];
    widget.data.submissionMessage = result['message'];
    widget.data.reportId = result['reportId']?.toString();

    // Step 3: Local Save with the complete data, including submission status.
    final String? localPath = await _localStorageService.saveTarballSamplingData(widget.data);

    if (mounted) {
      if (localPath != null) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text("Submission log saved locally to: $localPath")),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text("Warning: Could not save submission log locally."), backgroundColor: Colors.orange),
        );
      }
    }

    setState(() => _isLoading = false);

    // Step 4: Handle UI feedback based on the final status
    final status = result['status'];
    final message = result['message'] ?? 'An unknown error occurred.';

    debugPrint("Submission final status: $status. Report ID: ${widget.data.reportId}. Message: $message");

    if (status == 'L3') {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(message), backgroundColor: Colors.green),
      );
      Navigator.of(context).popUntil((route) => route.isFirst);
    } else { // L1 or L2 failures
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(message), backgroundColor: (status == 'L2' ? Colors.orange : Colors.red), duration: const Duration(seconds: 5)),
      );
    }
  }

  @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 Details",
            [
              _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 Code:", 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!.toStringAsFixed(2)} km"
                      : "N/A"
              ),
            ],
          ),

          _buildSectionCard(
            "On-Site Information & Photos",
            [
              // CORRECTED: Look up the classification name from the provider using the ID.
              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),
              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) {
    return 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 != null && value.isNotEmpty ? value : 'N/A',
              style: Theme.of(context).textTheme.bodyLarge,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildImageCard(String title, File? image, {String? remark}) {
    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.black54)),
            ),
        ],
      ),
    );
  }
}
