import 'dart:io';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import '../models/trip.dart';
import '../models/photo.dart';
import '../models/place.dart';
import '../services/html_generator.dart';
import '../services/export_helper.dart';
import '../core/preferences.dart';

class TripPreviewScreen extends StatefulWidget {
  final Trip trip;
  final List<Place> places;
  final List<Photo> photos;

  const TripPreviewScreen({
    super.key,
    required this.trip,
    required this.places,
    required this.photos,
  });

  @override
  State<TripPreviewScreen> createState() => _TripPreviewScreenState();
}

class _TripPreviewScreenState extends State<TripPreviewScreen> {
  late final WebViewController _controller;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();

    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (String url) {
            setState(() {
              _isLoading = false;
            });
          },
        ),
      );

    _initWebViewSettings();
    _loadHtml();
  }

  Future<void> _initWebViewSettings() async {
    final platform = _controller.platform;
    if (Platform.isAndroid && platform is AndroidWebViewController) {
      await platform.setAllowContentAccess(true);
      await platform.setAllowFileAccess(true);
    }
  }

  void _loadHtml() {
    final html = HtmlGenerator.generateHtml(
      widget.trip,
      widget.places,
      widget.photos,
    );
    _controller.loadHtmlString(html, baseUrl: 'http://localhost/');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppPreferences.language == 'cs' ? 'Náhled: ${widget.trip.name}' : 'Preview: ${widget.trip.name}'),
        actions: [
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: () => ExportHelper.showShareOptionsDialog(
              context: context,
              trip: widget.trip,
              places: widget.places,
              photos: widget.photos,
            ),
            tooltip: AppPreferences.language == 'cs' ? 'Možnosti sdílení' : 'Sharing options',
          ),
        ],
      ),
      body: Stack(
        children: [
          WebViewWidget(controller: _controller),
          if (_isLoading)
            const Center(
              child: CircularProgressIndicator(),
            ),
        ],
      ),
    );
  }
}
