import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:http/http.dart' as http;
import '../models/trip.dart';
import '../models/photo.dart';
import '../models/place.dart';
import '../core/preferences.dart';
import '../core/l10n.dart';
import 'export_service.dart';

enum ExportMode { netlify, folder, zip }

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

  @override
  State<NetlifyLoginDialog> createState() => _NetlifyLoginDialogState();
}

class _NetlifyLoginDialogState extends State<NetlifyLoginDialog> {
  final _tokenController = TextEditingController();
  bool _isLoading = false;
  String? _errorMessage;

  bool _showTokenInput = false;

  @override
  void initState() {
    super.initState();
    _showTokenInput = AppPreferences.netlifyToken == null;
  }

  @override
  void dispose() {
    _tokenController.dispose();
    super.dispose();
  }

  Future<void> _verifyAndSaveToken() async {
    final token = _tokenController.text.trim();
    if (token.isEmpty) {
      setState(() {
        _errorMessage = AppPreferences.language == 'cs'
            ? 'Zadejte prosím token.'
            : 'Please enter a token.';
      });
      return;
    }

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final response = await http.get(
        Uri.parse('https://api.netlify.com/api/v1/user'),
        headers: {
          'Authorization': 'Bearer $token',
        },
      );

      if (response.statusCode == 200) {
        await AppPreferences.setNetlifyToken(token);
        if (mounted) {
          Navigator.of(context).pop(true);
        }
      } else {
        setState(() {
          _errorMessage = AppPreferences.language == 'cs'
              ? 'Neplatný přístupový token. Ověřte, zda jste jej zkopírovali správně.'
              : 'Invalid access token. Please verify you copied it correctly.';
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = AppPreferences.language == 'cs'
            ? 'Chyba připojení: $e'
            : 'Connection error: $e';
      });
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final isCs = AppPreferences.language == 'cs';

    if (!_showTokenInput) {
      return AlertDialog(
        title: Text(isCs ? 'Nastavení Netlify' : 'Netlify Settings'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.cloud_done, color: Colors.blueAccent, size: 48),
            const SizedBox(height: 16),
            Text(
              isCs ? 'Jste přihlášen k Netlify!' : 'You are logged in to Netlify!',
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            Text(
              isCs
                  ? 'Aplikace bude automaticky nahrávat interaktivní mapy přímo pod váš účet Netlify.'
                  : 'The app will automatically upload interactive maps directly under your Netlify account.',
              textAlign: TextAlign.center,
              style: const TextStyle(fontSize: 13),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () async {
              await AppPreferences.setNetlifyToken(null);
              setState(() {
                _showTokenInput = true;
                _tokenController.clear();
              });
            },
            child: Text(isCs ? 'Odhlásit se' : 'Log Out'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.of(context).pop(true),
            child: Text(isCs ? 'Zavřít' : 'Close'),
          ),
        ],
      );
    }

    return AlertDialog(
      title: Text(isCs ? 'Přihlášení k Netlify' : 'Netlify Login'),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              isCs
                  ? 'Pro přímé a bezpečné nahrávání interaktivních map na váš Netlify účet je nutné zadat Personal Access Token.'
                  : 'To upload interactive maps directly and securely to your Netlify account, you need to enter a Personal Access Token.',
              style: const TextStyle(fontSize: 13),
            ),
            const SizedBox(height: 12),
            Text(
              isCs
                  ? 'Jak získat token (je to zdarma a zabere to 1 minutu):'
                  : 'How to get a token (free and takes 1 minute):',
              style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
            ),
            const SizedBox(height: 6),
            InkWell(
              onTap: () async {
                final uri = Uri.parse('https://app.netlify.com/signup');
                try {
                  await launchUrl(uri, mode: LaunchMode.externalApplication);
                } catch (_) {}
              },
              child: Text(
                isCs ? '1. Pokud ještě nemáte účet, zaregistrujte se zde' : '1. If you do not have an account, register here',
                style: const TextStyle(color: Colors.blue, decoration: TextDecoration.underline, fontSize: 13),
              ),
            ),
            const SizedBox(height: 4),
            InkWell(
              onTap: () async {
                final uri = Uri.parse('https://app.netlify.com/user/settings/applications#personal-access-tokens');
                try {
                  await launchUrl(uri, mode: LaunchMode.externalApplication);
                } catch (_) {}
              },
              child: Text(
                isCs ? '2. Přejděte do nastavení tokenů a klikněte na "Generate new token"' : '2. Go to token settings and click "Generate new token"',
                style: const TextStyle(color: Colors.blue, decoration: TextDecoration.underline, fontSize: 13),
              ),
            ),
            const SizedBox(height: 12),
            Center(
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.asset(
                  'assets/netlify_help.png',
                  height: 220,
                  fit: BoxFit.contain,
                ),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _tokenController,
              decoration: InputDecoration(
                labelText: isCs ? 'Vložte Personal Access Token' : 'Paste Personal Access Token',
                hintText: 'nlay_...',
                border: const OutlineInputBorder(),
                errorText: _errorMessage,
              ),
              obscureText: true,
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () {
            if (AppPreferences.netlifyToken != null) {
              setState(() {
                _showTokenInput = false;
              });
            } else {
              Navigator.of(context).pop(false);
            }
          },
          child: Text(L10n.zrusit),
        ),
        ElevatedButton(
          onPressed: _isLoading ? null : _verifyAndSaveToken,
          child: _isLoading
              ? const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : Text(isCs ? 'Přihlásit se' : 'Log In'),
        ),
      ],
    );
  }
}

class ExportProgressDialog extends StatefulWidget {
  final Trip trip;
  final List<Place> places;
  final List<Photo> photos;
  final ExportMode mode;
  final String? password;

  const ExportProgressDialog({
    super.key,
    required this.trip,
    required this.places,
    required this.photos,
    required this.mode,
    this.password,
  });

  @override
  State<ExportProgressDialog> createState() => _ExportProgressDialogState();
}

class _ExportProgressDialogState extends State<ExportProgressDialog> {
  double _progress = 0.0;
  String _status = '';
  String? _successPath;
  String? _error;

  String _slugify(String name) {
    var slug = name.toLowerCase();
    const czFrom = 'áčďéěíňóřšťúůýž';
    const czTo   = 'acdeeinorstuuyz';
    for (var i = 0; i < czFrom.length; i++) {
      slug = slug.replaceAll(czFrom[i], czTo[i]);
    }
    slug = slug.replaceAll(RegExp(r'[^a-z0-9]'), '-');
    slug = slug.replaceAll(RegExp(r'-+'), '-');
    if (slug.startsWith('-')) slug = slug.substring(1);
    if (slug.endsWith('-')) slug = slug.substring(0, slug.length - 1);
    return slug;
  }

  @override
  void initState() {
    super.initState();
    final isCs = AppPreferences.language == 'cs';
    switch (widget.mode) {
      case ExportMode.netlify:
        _status = isCs ? 'Připravuji export pro Netlify...' : 'Preparing Netlify export...';
        break;
      case ExportMode.folder:
        _status = isCs ? 'Exportuji interaktivní mapu...' : 'Exporting interactive map...';
        break;
      case ExportMode.zip:
        _status = isCs ? 'Připravuji ZIP export...' : 'Preparing ZIP export...';
        break;
    }
    _startExport();
  }

  Future<void> _startExport() async {
    final isCs = AppPreferences.language == 'cs';
    try {
      String path;
      switch (widget.mode) {
        case ExportMode.netlify:
          final zipPath = await ExportService.instance.exportInteractiveMapAsZip(
            widget.trip,
            widget.places,
            widget.photos,
            (prog, stat) {
              if (mounted) {
                setState(() {
                  _progress = prog * 0.4;
                  _status = stat;
                });
              }
            },
            password: widget.password,
          );

          if (!mounted) return;
          setState(() {
            _status = isCs ? 'Odesílám interaktivní mapu na Netlify...' : 'Uploading interactive map to Netlify...';
            _progress = 0.4;
          });

          final token = AppPreferences.netlifyToken;
          if (token == null) {
            throw Exception(isCs ? 'Chybí přístupový token Netlify.' : 'Netlify access token is missing.');
          }

          final zipFile = File(zipPath);
          if (!await zipFile.exists()) {
            throw Exception(isCs ? 'ZIP soubor nebyl nalezen.' : 'ZIP file not found.');
          }
          final bytes = await zipFile.readAsBytes();

          String? siteId = AppPreferences.getNetlifySiteId(widget.trip.id);
          String? siteUrl = AppPreferences.getNetlifyUrl(widget.trip.id);

          final client = http.Client();
          try {
            if (siteId != null) {
              final checkResponse = await client.get(
                Uri.parse('https://api.netlify.com/api/v1/sites/$siteId'),
                headers: {'Authorization': 'Bearer $token'},
              );
              if (checkResponse.statusCode == 404) {
                siteId = null;
                siteUrl = null;
                await AppPreferences.setNetlifySiteId(widget.trip.id, null);
                await AppPreferences.setNetlifyUrl(widget.trip.id, null);
              }
            }

            if (siteId == null) {
              if (mounted) {
                setState(() {
                  _status = isCs ? 'Vytvářím web na Netlify...' : 'Creating site on Netlify...';
                });
              }

              String? customName = _slugify(widget.trip.name);
              if (customName.isEmpty) {
                customName = null;
              }

              http.Response createResponse;
              if (customName != null) {
                // Try 1: Exact trip name slug
                createResponse = await client.post(
                  Uri.parse('https://api.netlify.com/api/v1/sites'),
                  headers: {
                    'Authorization': 'Bearer $token',
                    'Content-Type': 'application/json',
                  },
                  body: jsonEncode({'name': customName}),
                );

                // If taken (422), try 2: Trip name slug with a random suffix
                if (createResponse.statusCode == 422) {
                  final randomSuffix = (1000 + (DateTime.now().millisecondsSinceEpoch % 9000)).toString();
                  createResponse = await client.post(
                    Uri.parse('https://api.netlify.com/api/v1/sites'),
                    headers: {
                      'Authorization': 'Bearer $token',
                      'Content-Type': 'application/json',
                    },
                    body: jsonEncode({'name': '$customName-$randomSuffix'}),
                  );
                }

                // If still failing, fallback to random Netlify name
                if (createResponse.statusCode < 200 || createResponse.statusCode >= 300) {
                  createResponse = await client.post(
                    Uri.parse('https://api.netlify.com/api/v1/sites'),
                    headers: {
                      'Authorization': 'Bearer $token',
                      'Content-Type': 'application/json',
                    },
                    body: '{}',
                  );
                }
              } else {
                createResponse = await client.post(
                  Uri.parse('https://api.netlify.com/api/v1/sites'),
                  headers: {
                    'Authorization': 'Bearer $token',
                    'Content-Type': 'application/json',
                  },
                  body: '{}',
                );
              }

              if (createResponse.statusCode >= 200 && createResponse.statusCode < 300) {
                final data = jsonDecode(createResponse.body);
                siteId = data['id'];
                siteUrl = data['ssl_url'] ?? data['url'];
                if (siteId != null) {
                  await AppPreferences.setNetlifySiteId(widget.trip.id, siteId);
                  await AppPreferences.setNetlifyUrl(widget.trip.id, siteUrl);
                }
              } else {
                throw Exception(isCs 
                    ? 'Nepodařilo se vytvořit stránku na Netlify (kód ${createResponse.statusCode})' 
                    : 'Failed to create site on Netlify (code ${createResponse.statusCode})');
              }
            }

            if (mounted) {
              setState(() {
                _status = isCs ? 'Nahrávám soubory na Netlify...' : 'Uploading files to Netlify...';
                _progress = 0.7;
              });
            }

            final deployResponse = await client.post(
              Uri.parse('https://api.netlify.com/api/v1/sites/$siteId/deploys'),
              headers: {
                'Authorization': 'Bearer $token',
                'Content-Type': 'application/zip',
              },
              body: bytes,
            );

            if (deployResponse.statusCode >= 200 && deployResponse.statusCode < 300) {
              if (mounted) {
                setState(() {
                  _progress = 1.0;
                });
              }
              path = siteUrl!;
            } else {
              throw Exception(isCs 
                  ? 'Nahrávání selhalo (kód ${deployResponse.statusCode})' 
                  : 'Upload failed (code ${deployResponse.statusCode})');
            }
          } finally {
            client.close();
          }
          break;

        case ExportMode.folder:
          path = await ExportService.instance.exportInteractiveMap(
            widget.trip,
            widget.places,
            widget.photos,
            (prog, stat) {
              if (mounted) {
                setState(() {
                  _progress = prog;
                  _status = stat;
                });
              }
            },
            password: widget.password,
          );
          break;

        case ExportMode.zip:
          path = await ExportService.instance.exportTripToZip(
            widget.trip,
            (prog, stat) {
              if (mounted) {
                setState(() {
                  _progress = prog;
                  _status = stat;
                });
              }
            },
          );
          break;
      }

      if (mounted) {
        setState(() {
          _successPath = path;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _error = e.toString();
        });
        if (e.toString().contains('401') || e.toString().contains('Unauthorized')) {
          AppPreferences.setNetlifyToken(null);
        }
      }
    }
  }

  Widget _buildDialogMenuItem({
    required BuildContext context,
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    final theme = Theme.of(context);
    return Expanded(
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(icon, color: theme.colorScheme.primary, size: 28),
              const SizedBox(height: 6),
              Text(
                label,
                style: TextStyle(
                  fontSize: 11,
                  fontWeight: FontWeight.w600,
                  color: theme.colorScheme.onSurface,
                ),
                textAlign: TextAlign.center,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final isCs = AppPreferences.language == 'cs';
    
    String title = '';
    switch (widget.mode) {
      case ExportMode.netlify:
        title = isCs ? 'Publikování na Netlify' : 'Publish to Netlify';
        break;
      case ExportMode.folder:
        title = isCs ? 'Export složky' : 'Folder Export';
        break;
      case ExportMode.zip:
        title = isCs ? 'Export do ZIP' : 'ZIP Export';
        break;
    }

    if (_error != null) {
      return AlertDialog(
        title: Text(isCs ? 'Chyba při exportu' : 'Export Error'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.error_outline, color: Colors.red, size: 48),
            const SizedBox(height: 16),
            Text(
              _error!,
              style: const TextStyle(fontSize: 13),
            ),
          ],
        ),
        actions: [
          ElevatedButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(isCs ? 'Zavřít' : 'Close'),
          ),
        ],
      );
    }

    if (_successPath != null) {
      if (widget.mode == ExportMode.netlify) {
        return AlertDialog(
          title: Text(title),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Center(
                  child: Icon(Icons.cloud_done, color: Colors.blueAccent, size: 48),
                ),
                const SizedBox(height: 16),
                Text(
                  isCs
                      ? 'Vaše interaktivní mapa byla úspěšně nahrána a je online!'
                      : 'Your interactive map was successfully uploaded and is online!',
                  style: const TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 12),
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.black12,
                    borderRadius: BorderRadius.circular(6),
                  ),
                  child: InkWell(
                    onTap: () async {
                      final uri = Uri.parse(_successPath!);
                      try {
                        await launchUrl(uri, mode: LaunchMode.externalApplication);
                      } catch (_) {}
                    },
                    child: Text(
                      _successPath!,
                      style: const TextStyle(
                        fontFamily: 'monospace',
                        fontSize: 11,
                        color: Colors.blue,
                        decoration: TextDecoration.underline,
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 20),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildDialogMenuItem(
                      context: context,
                      icon: Icons.open_in_browser,
                      label: isCs ? 'Otevřít mapu' : 'Open map',
                      onTap: () async {
                        final uri = Uri.parse(_successPath!);
                        try {
                          await launchUrl(uri, mode: LaunchMode.externalApplication);
                        } catch (_) {}
                      },
                    ),
                    _buildDialogMenuItem(
                      context: context,
                      icon: Icons.copy,
                      label: isCs ? 'Kopírovat' : 'Copy link',
                      onTap: () {
                        Clipboard.setData(ClipboardData(text: _successPath!));
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text(isCs
                                ? 'Odkaz byl zkopírován do schránky.'
                                : 'Link copied to clipboard.'),
                          ),
                        );
                      },
                    ),
                    _buildDialogMenuItem(
                      context: context,
                      icon: Icons.share,
                      label: isCs ? 'Sdílet' : 'Share map',
                      onTap: () {
                        final shareText = isCs
                            ? 'Podívejte se na interaktivní mapu ${widget.trip.name} z aplikace Live Vacation Memories: $_successPath'
                            : 'Check out the interactive map ${widget.trip.name} from the Live Vacation Memories app: $_successPath';
                        final box = context.findRenderObject() as RenderBox?;
                        final sharePositionOrigin = box != null
                            ? box.localToGlobal(Offset.zero) & box.size
                            : null;
                        SharePlus.instance.share(
                          ShareParams(
                            text: shareText,
                            sharePositionOrigin: sharePositionOrigin,
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text(isCs ? 'Zavřít' : 'Close'),
            ),
          ],
        );
      } else {
        String successText = '';
        if (widget.mode == ExportMode.folder) {
          successText = isCs
              ? 'Složka s kompletní interaktivní HTML mapou a fotografiemi byla vytvořena v Downloads/LVM.'
              : 'Folder with complete interactive HTML map and photos was created in Downloads/LVM.';
        } else {
          successText = isCs
              ? 'ZIP archiv byl úspěšně vytvořen. Můžete jej přenést do počítače a importovat v desktopové verzi.'
              : 'ZIP archive was successfully created. You can transfer it to your computer and import in the desktop app.';
        }

        return AlertDialog(
          title: Text(title),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Center(
                child: Icon(Icons.check_circle, color: Colors.green, size: 48),
              ),
              const SizedBox(height: 16),
              Text(successText),
              const SizedBox(height: 12),
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.black12,
                  borderRadius: BorderRadius.circular(6),
                ),
                child: Text(
                  _successPath!,
                  style: const TextStyle(fontFamily: 'monospace', fontSize: 11),
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                Clipboard.setData(ClipboardData(text: _successPath!));
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text(isCs
                        ? 'Cesta k souboru byla zkopírována.'
                        : 'Path copied to clipboard.'),
                  ),
                );
              },
              child: Text(isCs ? 'Kopírovat cestu' : 'Copy path'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text(isCs ? 'Hotovo' : 'Done'),
            ),
          ],
        );
      }
    }

    return AlertDialog(
      title: Text(title),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          LinearProgressIndicator(value: _progress),
          const SizedBox(height: 16),
          Text(
            _status,
            style: const TextStyle(fontSize: 13),
          ),
        ],
      ),
    );
  }
}

class ExportHelper {
  static Future<void> showShareOptionsDialog({
    required BuildContext context,
    required Trip trip,
    required List<Place> places,
    required List<Photo> photos,
  }) async {
    await showDialog(
      context: context,
      builder: (context) {
        return _ShareOptionsDialog(
          trip: trip,
          places: places,
          photos: photos,
        );
      },
    );
  }

  static Future<void> _runExport(
    BuildContext context,
    Trip trip,
    List<Place> places,
    List<Photo> photos,
    ExportMode mode, {
    String? password,
  }) async {
    if (mode == ExportMode.netlify) {
      if (AppPreferences.netlifyToken == null) {
        final loggedIn = await showDialog<bool>(
          context: context,
          builder: (context) => const NetlifyLoginDialog(),
        );
        if (loggedIn != true) return;
      }
    }

    if (context.mounted) {
      await showDialog<dynamic>(
        context: context,
        barrierDismissible: false,
        builder: (dialogContext) => ExportProgressDialog(
          trip: trip,
          places: places,
          photos: photos,
          mode: mode,
          password: password,
        ),
      );
    }
  }
}

class _ShareOptionsDialog extends StatelessWidget {
  final Trip trip;
  final List<Place> places;
  final List<Photo> photos;

  const _ShareOptionsDialog({
    required this.trip,
    required this.places,
    required this.photos,
  });

  @override
  Widget build(BuildContext context) {
    final isCs = AppPreferences.language == 'cs';

    return AlertDialog(
      title: Text(isCs ? 'Možnosti sdílení' : 'Sharing Options'),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.cloud_upload, color: Colors.blueAccent, size: 28),
              title: Text(
                isCs ? '(Doporučeno) Publikovat na Netlify' : '(Recommended) Publish to Netlify',
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              subtitle: Text(
                AppPreferences.netlifyToken != null
                    ? (isCs
                        ? (trip.password != null && trip.password!.isNotEmpty
                            ? 'Nahraje zabezpečenou mapu na váš účet Netlify'
                            : 'Nahraje mapu přímo na váš účet Netlify')
                        : (trip.password != null && trip.password!.isNotEmpty
                            ? 'Uploads password-protected map to Netlify'
                            : 'Uploads map directly to your Netlify account'))
                    : (isCs ? 'Vyžaduje přihlášení k Netlify' : 'Requires Netlify login'),
              ),
              trailing: AppPreferences.netlifyToken != null
                  ? IconButton(
                      icon: const Icon(Icons.logout, size: 20),
                      tooltip: isCs ? 'Odhlásit se z Netlify' : 'Log out from Netlify',
                      onPressed: () async {
                        final navigator = Navigator.of(context);
                        final messenger = ScaffoldMessenger.of(context);
                        await AppPreferences.setNetlifyToken(null);
                        navigator.pop();
                        messenger.showSnackBar(
                          SnackBar(
                            content: Text(isCs
                                ? 'Byl jste odhlášen z Netlify.'
                                : 'Logged out from Netlify.'),
                          ),
                        );
                      },
                    )
                  : null,
              onTap: () {
                Navigator.pop(context);
                ExportHelper._runExport(
                  context,
                  trip,
                  places,
                  photos,
                  ExportMode.netlify,
                  password: trip.password,
                );
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.folder_open, color: Colors.orange, size: 28),
              title: Text(isCs ? 'Uložit jako webovou aplikaci' : 'Save as Web Application'),
              subtitle: Text(
                isCs
                    ? (trip.password != null && trip.password!.isNotEmpty
                        ? 'Vytvoří složku se zabezpečenou mapou v Downloads/LVM'
                        : 'Vytvoří složku s HTML mapou a fotkami v Downloads/LVM')
                    : (trip.password != null && trip.password!.isNotEmpty
                        ? 'Creates folder with protected map in Downloads/LVM'
                        : 'Creates HTML map folder and photos in Downloads/LVM'),
              ),
              onTap: () {
                Navigator.pop(context);
                ExportHelper._runExport(
                  context,
                  trip,
                  places,
                  photos,
                  ExportMode.folder,
                  password: trip.password,
                );
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.archive, color: Colors.green, size: 28),
              title: Text(isCs ? 'Uložit jako ZIP archiv' : 'Save as ZIP Archive'),
              subtitle: Text(
                isCs
                    ? 'Vytvoří ZIP pro import do desktopové aplikace LVM (nepodporuje heslo)'
                    : 'Creates ZIP for LVM desktop application import (no password)',
              ),
              onTap: () {
                Navigator.pop(context);
                ExportHelper._runExport(
                  context,
                  trip,
                  places,
                  photos,
                  ExportMode.zip,
                );
              },
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: Text(L10n.zrusit),
        ),
      ],
    );
  }
}
