// lib/screens/marine/manual/info_centre_document.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:environment_monitoring_app/services/local_storage_service.dart';
import '../../../auth_provider.dart';

// (The MarineDocument model class remains the same)
class MarineDocument {
  final int id;
  final String title;
  final String module;
  final String? group;
  final String url;
  final String? departmentName;

  MarineDocument({
    required this.id,
    required this.title,
    required this.module,
    this.group,
    required this.url,
    this.departmentName,
  });

  factory MarineDocument.fromMap(Map<String, dynamic> map) {
    return MarineDocument(
      id: map['id'],
      title: map['title'],
      module: map['module'],
      group: map['group'],
      url: map['url'],
      departmentName: map['department_name'],
    );
  }
}


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

  @override
  State<MarineInfoCentreDocument> createState() => _MarineInfoCentreDocumentState();
}

class _MarineInfoCentreDocumentState extends State<MarineInfoCentreDocument> {
  final LocalStorageService _localStorageService = LocalStorageService();
  late List<MarineDocument> _documents;

  // --- STATE FOR NEW UI ---
  // Holds all available groups for the dropdown
  List<String> _documentGroups = [];
  // Holds the currently selected group from the dropdown
  String? _selectedGroup;

  Set<String> _downloadedUrls = {};
  Map<String, double> _downloadProgress = {};

  @override
  void initState() {
    super.initState();
    _documents = _getFilteredDocumentsFromProvider();

    // --- NEW: Populate the list of groups for the dropdown ---
    // Get unique group names from the documents
    final groups = _documents.map((doc) => doc.group ?? 'Uncategorized').toSet().toList();
    // Add "All Documents" as the first option
    _documentGroups = ['All Documents', ...groups];
    // Set the initial value of the dropdown
    _selectedGroup = _documentGroups.first;

    _checkInitialDownloadStatus();
  }

  List<MarineDocument> _getFilteredDocumentsFromProvider() {
    final documentsData = Provider.of<AuthProvider>(context, listen: false).documents;
    if (documentsData == null || documentsData.isEmpty) {
      return [];
    }

    var allDocuments = documentsData.map((map) => MarineDocument.fromMap(map)).toList();

    return allDocuments.where((doc) {
      return doc.departmentName == 'Marine' && doc.module == 'Manual';
    }).toList();
  }

  Future<void> _checkInitialDownloadStatus() async {
    final downloaded = <String>{};
    for (var doc in _documents) {
      if (await _localStorageService.isDocumentDownloaded(doc.url)) {
        downloaded.add(doc.url);
      }
    }
    if (mounted) {
      setState(() {
        _downloadedUrls = downloaded;
      });
    }
  }

  Future<void> _handleDownload(MarineDocument doc) async {
    setState(() {
      _downloadProgress[doc.url] = 0.0;
    });

    try {
      await _localStorageService.downloadDocument(
        docUrl: doc.url,
        onReceiveProgress: (progress) {
          if (mounted) {
            setState(() {
              _downloadProgress[doc.url] = progress;
            });
          }
        },
      );
      if (mounted) {
        setState(() {
          _downloadedUrls.add(doc.url);
          _downloadProgress.remove(doc.url);
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Download failed for ${doc.title}')),
        );
        setState(() {
          _downloadProgress.remove(doc.url);
        });
      }
    }
  }

  Future<void> _viewDocument(MarineDocument doc) async {
    final localPath = await _localStorageService.getLocalDocumentPath(doc.url);
    if (localPath != null && mounted) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => PdfViewerScreen(
            filePath: localPath,
            title: doc.title,
          ),
        ),
      );
    }
  }

  Widget _buildTrailingWidget(MarineDocument doc) {
    if (_downloadProgress.containsKey(doc.url)) {
      return SizedBox(
        width: 24,
        height: 24,
        child: CircularProgressIndicator(
          value: _downloadProgress[doc.url],
          strokeWidth: 3,
        ),
      );
    }

    if (_downloadedUrls.contains(doc.url)) {
      return IconButton(
        icon: const Icon(Icons.visibility, color: Colors.green),
        tooltip: 'View Document',
        onPressed: () => _viewDocument(doc),
      );
    }

    return IconButton(
      icon: const Icon(Icons.download_for_offline, color: Colors.blueAccent),
      tooltip: 'Download for Offline',
      onPressed: () => _handleDownload(doc),
    );
  }

  @override
  Widget build(BuildContext context) {
    // --- NEW: Filter the list based on the dropdown selection ---
    final filteredDocs = _selectedGroup == 'All Documents'
        ? _documents
        : _documents.where((doc) => (doc.group ?? 'Uncategorized') == _selectedGroup).toList();

    return Scaffold(
      appBar: AppBar(
        title: const Text("Marine Manuals"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // --- NEW: Styled Dropdown for filtering ---
            DropdownButtonFormField<String>(
              value: _selectedGroup,
              decoration: InputDecoration(
                labelText: 'Filter by Group',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              ),
              items: _documentGroups.map((String group) {
                return DropdownMenuItem<String>(
                  value: group,
                  child: Text(group),
                );
              }).toList(),
              onChanged: (newValue) {
                setState(() {
                  _selectedGroup = newValue;
                });
              },
            ),
            const SizedBox(height: 20),

            // --- NEW: List title ---
            Text(
              _selectedGroup!,
              style: Theme.of(context).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const Divider(height: 20),

            // --- NEW: Use Expanded to make the list scrollable within the Column ---
            Expanded(
              child: _documents.isEmpty
                  ? const Center(child: Text("No Marine Manual documents found."))
                  : ListView.builder(
                itemCount: filteredDocs.length,
                itemBuilder: (context, index) {
                  final doc = filteredDocs[index];
                  // --- NEW: Wrap each item in a Card for modern styling ---
                  return Card(
                    elevation: 2.0,
                    margin: const EdgeInsets.symmetric(vertical: 6.0),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: ListTile(
                      // --- NEW: Styled icon ---
                      leading: CircleAvatar(
                        backgroundColor: Colors.red.shade100,
                        child: const Icon(Icons.picture_as_pdf, color: Colors.redAccent),
                      ),
                      title: Text(doc.title),
                      trailing: _buildTrailingWidget(doc),
                      onTap: _downloadedUrls.contains(doc.url)
                          ? () => _viewDocument(doc)
                          : null,
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}


class PdfViewerScreen extends StatelessWidget {
  final String filePath;
  final String title;

  const PdfViewerScreen({
    super.key,
    required this.filePath,
    required this.title,
  });

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: PDFView(
        filePath: filePath,
        enableSwipe: true,
        swipeHorizontal: false,
        autoSpacing: false,
        pageFling: false,
      ),
    );
  }
}