import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher.dart';
import '../core/database.dart';
import '../core/theme.dart';
import '../core/preferences.dart';
import '../core/l10n.dart';
import '../main.dart';
import '../models/trip.dart';
import '../models/photo.dart';
import '../models/place.dart';
import '../widgets/photo_thumbnail.dart';
import '../services/sharing_service.dart';
import '../services/place_clustering.dart';
import '../services/export_helper.dart';
import 'host_invitation_screen.dart';
import '../services/media_scanner.dart';
import '../services/geocoding_service.dart';
import 'photo_viewer_screen.dart';
import 'trip_preview_screen.dart';
import 'package:permission_handler/permission_handler.dart';




class TripDetailScreen extends StatefulWidget {
  final String tripId;

  const TripDetailScreen({super.key, required this.tripId});

  @override
  State<TripDetailScreen> createState() => _TripDetailScreenState();
}

class _TripDetailScreenState extends State<TripDetailScreen> {
  Trip? _trip;
  List<Photo> _photos = [];
  List<Place> _places = [];
  bool _isLoading = true;
  bool _isSyncing = false;
  bool _isScanning = false;
  bool _isEnriching = false;
  bool _showWikiPrompt = true;



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

  Future<void> _loadTrip() async {
    setState(() {
      _isLoading = true;
    });
    final trip = await DatabaseHelper.instance.getTrip(widget.tripId);
    if (trip != null) {
      final photos = await DatabaseHelper.instance.getPhotosForTrip(widget.tripId);
      final places = await DatabaseHelper.instance.getPlacesForTrip(widget.tripId);
      setState(() {
        _trip = trip;
        _photos = photos;
        _places = places;
        _isLoading = false;
      });
    } else {
      setState(() {
        _isLoading = false;
      });
    }
  }

  void _toggleTheme() async {
    final current = AppPreferences.themeMode;
    final nextTheme = current == 'dark' ? 'light' : 'dark';
    await AppPreferences.setThemeMode(nextTheme);
    ThemeNotifier.updateTheme(nextTheme);
    setState(() {});
  }

  void _toggleLanguage() async {
    final nextLang = AppPreferences.language == 'en' ? 'cs' : 'en';
    await AppPreferences.setLanguage(nextLang);
    LanguageNotifier.updateLanguage(nextLang);
    _loadTrip();
  }

  Future<void> _editDisplayName() async {
    final updated = await showDialog<bool>(
      context: context,
      builder: (context) => _EditDisplayNameDialog(),
    );
    if (updated == true) {
      setState(() {});
    }
  }

  Future<void> _startSync() async {
    if (_trip == null) return;
    setState(() {
      _isSyncing = true;
    });
    try {
      final count = await SharingService.instance.syncPhotosFromHost(_trip!);
      await PlaceClusteringService.clusterTripPlaces(_trip!);
      await _loadTrip();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Synchronizace dokončena. Staženo $count nových fotografií.'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('Chyba synchronizace'),
            content: Text('Nepodařilo se synchronizovat data:\n${e.toString()}'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('Zavřít'),
              ),
            ],
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isSyncing = false;
        });
      }
    }
  }

  Future<void> _scanPhotos() async {
    if (_trip == null) return;

    final proceed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(AppPreferences.language == 'cs' ? 'Vyžadován přístup k fotkám' : 'Photo Access Required'),
        content: Text(AppPreferences.language == 'cs'
            ? 'Pro automatické vytvoření itineráře a načtení fotek potřebuje aplikace plný přístup ke všem fotografiím. Pokud v následujícím dialogu zvolíte jen omezený nebo částečný přístup, skenování nebude fungovat a nenačtou se žádné fotografie. Zvolte prosím možnost povolit přístup ke všem fotografiím.'
            : 'To automatically create your itinerary and import photos, the app needs full access to all photos. If you select limited or partial access in the next prompt, the scan will not work and no photos will be loaded. Please choose to allow access to all photos.'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: Text(L10n.zrusit),
          ),
          ElevatedButton(
            onPressed: () => Navigator.pop(context, true),
            child: Text(AppPreferences.language == 'cs' ? 'Rozumím a chci načíst' : 'Got it, proceed'),
          ),
        ],
      ),
    );
    if (proceed != true) return;

    setState(() {
      _isScanning = true;
    });
    try {
      final photos = await MediaScanner.scanPhotosForTrip(_trip!);
      await PlaceClusteringService.clusterTripPlaces(_trip!);
      await _loadTrip();
      setState(() {
        _showWikiPrompt = true;
      });
      if (mounted) {
        final isLimited = await Permission.photos.isLimited;
        if (!mounted) return;
        if (isLimited) {
          showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text(AppPreferences.language == 'cs' ? 'Omezený přístup k fotkám' : 'Limited photo access'),
              content: Text(AppPreferences.language == 'cs'
                  ? 'Povolili jste přístup pouze k vybraným fotografiím. Pokud se nenačetly všechny, můžete v nastavení telefonu povolit přístup ke všem fotkám, nebo vybrat další.'
                  : 'You have allowed access to selected photos only. If not all photos were loaded, you can allow access to all photos in system settings, or choose more.'),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: Text(AppPreferences.language == 'cs' ? 'Rozumím' : 'I understand'),
                ),
              ],
            ),
          );
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(AppPreferences.language == 'cs' 
                  ? 'Skenování dokončeno. Nalezeno ${photos.length} fotografií.' 
                  : 'Scanning completed. Found ${photos.length} photos.'),
              backgroundColor: Colors.green,
            ),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(AppPreferences.language == 'cs' 
                ? 'Chyba při skenování: ${e.toString()}' 
                : 'Error during scanning: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isScanning = false;
        });
      }
    }
  }

  Future<void> _enrichPlacesWithWikipedia() async {
    if (_trip == null || _places.isEmpty) return;
    setState(() {
      _isEnriching = true;
    });
    try {
      for (final place in _places) {
        final wikiInfo = await GeocodingService.getWikipediaInfo(place.latitude, place.longitude);
        if (wikiInfo != null) {
          final enrichedPlace = Place(
            id: place.id,
            tripId: place.tripId,
            dayNumber: place.dayNumber,
            name: wikiInfo['title'] ?? place.name,
            latitude: place.latitude,
            longitude: place.longitude,
            arrivalTimeUtc: place.arrivalTimeUtc,
            departureTimeUtc: place.departureTimeUtc,
            description: wikiInfo['description'] ?? place.description,
          );
          await DatabaseHelper.instance.insertPlace(enrichedPlace);
        }
        await Future.delayed(const Duration(milliseconds: 500));
      }
      await _loadTrip();
      setState(() {
        _showWikiPrompt = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(AppPreferences.language == 'cs' 
                ? 'Popisky míst z Wikipedie byly úspěšně doplněny!' 
                : 'Place descriptions from Wikipedia successfully added!'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(AppPreferences.language == 'cs' 
                ? 'Chyba při stahování z Wikipedie: $e' 
                : 'Error downloading from Wikipedia: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isEnriching = false;
        });
      }
    }
  }

  Future<void> _editTripDetails() async {
    if (_trip == null) return;

    final isCs = AppPreferences.language == 'cs';

    final saved = await showDialog<bool>(
      context: context,
      builder: (context) => _EditTripDialog(trip: _trip!),
    );

    if (saved == true) {
      if (!mounted) return;

      // Ask if they want to re-scan photos
      final reScan = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: Text(isCs ? 'Znovu načíst fotky?' : 'Reload photos?'),
          content: Text(
            isCs
                ? 'Změnili jste termín cesty. Chcete automaticky znovu prohledat galerii a načíst fotky pro nové období?'
                : 'You have changed the trip dates. Do you want to automatically search the gallery and load photos for the new period?',
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context, false),
              child: Text(isCs ? 'Ne' : 'No'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.pop(context, true),
              child: Text(isCs ? 'Ano, načíst' : 'Yes, load'),
            ),
          ],
        ),
      );

      if (reScan == true) {
        _scanPhotos();
      } else {
        _loadTrip();
      }
    }
  }

  void _openPreview() {
    if (_trip == null) return;
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => TripPreviewScreen(
          trip: _trip!,
          places: _places,
          photos: _photos,
        ),
      ),
    );
  }


  Future<void> _renamePlace(Place place) async {
    final updated = await showDialog<bool>(
      context: context,
      builder: (context) => _RenamePlaceDialog(place: place),
    );
    if (updated == true) {
      _loadTrip();
    }
  }

  Future<void> _showOnMap(Place place) async {
    final url = Uri.parse('https://www.google.com/maps/search/?api=1&query=${place.latitude},${place.longitude}');
    try {
      final success = await launchUrl(url, mode: LaunchMode.externalApplication);
      if (!success) {
        final geoUrl = Uri.parse('geo:${place.latitude},${place.longitude}?q=${place.latitude},${place.longitude}');
        await launchUrl(geoUrl);
      }
    } catch (e) {
      try {
        final geoUrl = Uri.parse('geo:${place.latitude},${place.longitude}?q=${place.latitude},${place.longitude}');
        await launchUrl(geoUrl);
      } catch (e2) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Nelze otevřít mapovou aplikaci.')),
          );
        }
      }
    }
  }

  Map<int, List<Place>> _groupPlacesByDay() {
    final Map<int, List<Place>> groups = {};
    for (final place in _places) {
      groups.putIfAbsent(place.dayNumber, () => []).add(place);
    }
    return groups;
  }

  List<Photo> _getPhotosForPlace(Place place) {
    if (place.arrivalTimeUtc == null || place.departureTimeUtc == null) return [];
    return _photos.where((p) {
      final time = p.dateTakenUtc ?? 0;
      return time >= place.arrivalTimeUtc! && time <= place.departureTimeUtc!;
    }).toList();
  }

  Widget _buildBottomMenuItem({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
    Color? color,
  }) {
    final isSyncIcon = icon == Icons.sync || icon == Icons.wifi;
    return Expanded(
      child: InkWell(
        onTap: _isSyncing && isSyncIcon ? null : onTap,
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 6.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              _isSyncing && isSyncIcon
                  ? const SizedBox(
                      width: 24,
                      height: 24,
                      child: CircularProgressIndicator(strokeWidth: 2),
                    )
                  : Icon(icon, color: color ?? Theme.of(context).colorScheme.primary, size: 24),
              const SizedBox(height: 4),
              Text(
                label,
                style: TextStyle(
                  fontSize: 11,
                  fontWeight: FontWeight.w600,
                  color: color ?? Theme.of(context).colorScheme.onSurface,
                ),
                textAlign: TextAlign.center,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    if (_isLoading) {
      return const Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    if (_trip == null) {
      return Scaffold(
        appBar: AppBar(title: Text(AppPreferences.language == 'cs' ? 'Chyba' : 'Error')),
        body: Center(child: Text(AppPreferences.language == 'cs' ? 'Cesta nebyla nalezena' : 'Trip not found')),
      );
    }

    final startDateText = _trip!.startTimeUtc != null
        ? DateFormat('d. M. yyyy').format(DateTime.fromMillisecondsSinceEpoch(_trip!.startTimeUtc!))
        : '?';
    final finishDateText = _trip!.finishTimeUtc != null
        ? DateFormat('d. M. yyyy').format(DateTime.fromMillisecondsSinceEpoch(_trip!.finishTimeUtc!))
        : L10n.probiha;

    final isDark = Theme.of(context).brightness == Brightness.dark;

    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          title: Text(_trip!.name),
        ),
        endDrawer: Drawer(
          child: SafeArea(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                DrawerHeader(
                  decoration: BoxDecoration(
                    color: theme.colorScheme.primaryContainer.withValues(alpha: 0.2),
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(10),
                        child: Image.asset(
                          'assets/logo.jpg',
                          width: 54,
                          height: 54,
                          fit: BoxFit.cover,
                          errorBuilder: (context, error, stackTrace) => Icon(Icons.flight_takeoff, size: 40, color: theme.colorScheme.secondary),
                        ),
                      ),
                      const SizedBox(height: 10),
                      Text(
                        L10n.appTitle,
                        style: theme.textTheme.titleMedium?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        AppPreferences.displayName,
                        style: theme.textTheme.bodyMedium?.copyWith(
                          color: theme.hintColor,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
                ListTile(
                  leading: const Icon(Icons.edit, color: Colors.blueAccent),
                  title: Text(AppPreferences.language == 'cs' ? 'Upravit dovolenou' : 'Edit Vacation'),
                  subtitle: Text('$startDateText – $finishDateText'),
                  onTap: () {
                    Navigator.pop(context);
                    _editTripDetails();
                  },
                ),
                const Divider(),
                ListTile(
                  leading: Icon(
                    (_trip!.ownerParticipantId == AppPreferences.displayName || 
                     _trip!.ownerParticipantId == AppPreferences.participantId ||
                     _trip!.shareCode == null)
                        ? Icons.wifi
                        : Icons.sync,
                    color: Colors.green,
                  ),
                  title: Text(
                    (_trip!.ownerParticipantId == AppPreferences.displayName || 
                     _trip!.ownerParticipantId == AppPreferences.participantId ||
                     _trip!.shareCode == null)
                        ? (AppPreferences.language == 'cs' ? 'Sdílet fotky' : 'Share Photos')
                        : (AppPreferences.language == 'cs' ? 'Synchronizovat' : 'Synchronize'),
                  ),
                  subtitle: _isSyncing
                      ? Text(AppPreferences.language == 'cs' ? 'Probíhá synchronizace...' : 'Syncing...')
                      : Text(AppPreferences.language == 'cs' ? 'Propojit zařízení' : 'Connect devices'),
                  onTap: () {
                    Navigator.pop(context);
                    if (_trip!.ownerParticipantId == AppPreferences.displayName || 
                        _trip!.ownerParticipantId == AppPreferences.participantId ||
                        _trip!.shareCode == null) {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => HostInvitationScreen(trip: _trip!),
                        ),
                      ).then((_) => _loadTrip());
                    } else {
                      _startSync();
                    }
                  },
                ),
                const Divider(),
                ListTile(
                  leading: const Icon(Icons.map, color: Colors.orangeAccent),
                  title: Text(AppPreferences.language == 'cs' ? 'Ukaž mapu' : 'Show Map'),
                  subtitle: Text(AppPreferences.language == 'cs' ? 'Zobrazit interaktivní náhled' : 'Show interactive preview'),
                  onTap: () {
                    Navigator.pop(context);
                    _openPreview();
                  },
                ),
                const Divider(),
                ListTile(
                  leading: const Icon(Icons.cloud_upload, color: Colors.purpleAccent),
                  title: Text(AppPreferences.language == 'cs' ? 'Uložit projekt' : 'Save Project'),
                  subtitle: Text(AppPreferences.language == 'cs' ? 'Export a sdílení na Netlify/ZIP' : 'Export & share options'),
                  onTap: () {
                    Navigator.pop(context);
                    ExportHelper.showShareOptionsDialog(
                      context: context,
                      trip: _trip!,
                      places: _places,
                      photos: _photos,
                    );
                  },
                ),
                const Divider(),
                ListTile(
                  leading: const Icon(Icons.person),
                  title: Text(AppPreferences.language == 'cs' ? 'Změnit jméno' : 'Change Name'),
                  subtitle: Text(AppPreferences.displayName),
                  onTap: () {
                    Navigator.pop(context);
                    _editDisplayName();
                  },
                ),
                const Divider(),
                ListTile(
                  leading: const Icon(Icons.cloud_queue),
                  title: Text(AppPreferences.language == 'cs' ? 'Nastavení Netlify' : 'Netlify Settings'),
                  subtitle: Text(
                    AppPreferences.netlifyToken != null
                        ? (AppPreferences.language == 'cs' ? 'Přihlášen' : 'Logged In')
                        : (AppPreferences.language == 'cs' ? 'Nepřihlášen' : 'Not Logged In'),
                  ),
                  onTap: () {
                    Navigator.pop(context);
                    showDialog(
                      context: context,
                      builder: (context) => const NetlifyLoginDialog(),
                    ).then((_) {
                      setState(() {});
                    });
                  },
                ),
                const Divider(),
                ListTile(
                  leading: Icon(isDark ? Icons.light_mode : Icons.dark_mode),
                  title: Text(AppPreferences.language == 'cs' ? 'Změnit motiv' : 'Change Theme'),
                  subtitle: Text(
                    isDark
                        ? (AppPreferences.language == 'cs' ? 'Tmavý režim' : 'Dark Mode')
                        : (AppPreferences.language == 'cs' ? 'Světlý režim' : 'Light Mode'),
                  ),
                  onTap: () {
                    _toggleTheme();
                  },
                ),
                const Divider(),
                ListTile(
                  leading: Text(
                    AppPreferences.language == 'en' ? '🇨🇿' : '🇬🇧',
                    style: const TextStyle(fontSize: 20),
                  ),
                  title: Text(AppPreferences.language == 'cs' ? 'Změnit jazyk' : 'Change Language'),
                  subtitle: Text(
                    AppPreferences.language == 'cs' ? 'Čeština' : 'English',
                  ),
                  onTap: () {
                    _toggleLanguage();
                  },
                ),
                const Spacer(),
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Text(
                    'v1.0.0',
                    textAlign: TextAlign.center,
                    style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
                  ),
                ),
              ],
            ),
          ),
        ),
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Summary Card
                Card(
                  margin: EdgeInsets.zero,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Row(
                      children: [
                        Container(
                          width: 48,
                          height: 48,
                          decoration: BoxDecoration(
                            color: theme.colorScheme.primary.withValues(alpha: 0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Icon(
                            Icons.calendar_today,
                            color: theme.colorScheme.primary,
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                '$startDateText – $finishDateText',
                                style: theme.textTheme.titleMedium?.copyWith(
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),

                const SizedBox(height: 20),

                // Tab Bar
                TabBar(
                  tabs: [
                    Tab(icon: const Icon(Icons.photo_library), text: L10n.gallery),
                    Tab(icon: const Icon(Icons.map), text: L10n.itinerary),
                  ],
                  labelColor: theme.colorScheme.primary,
                  unselectedLabelColor: theme.hintColor,
                  indicatorColor: theme.colorScheme.primary,
                ),
                const SizedBox(height: 16),

                // Tab Bar Views
                Expanded(
                  child: TabBarView(
                    children: [
                      _buildGalleryTab(theme),
                      _buildItineraryTab(theme),
                    ],
                  ),
                ),

                const SizedBox(height: 16),
              ],
            ),
          ),
        ),
        bottomNavigationBar: Container(
          decoration: BoxDecoration(
            color: theme.colorScheme.surface,
            border: Border(
              top: BorderSide(
                color: theme.dividerColor.withValues(alpha: 0.5),
                width: 1,
              ),
            ),
          ),
          child: SafeArea(
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _buildBottomMenuItem(
                    icon: Icons.edit,
                    label: AppPreferences.language == 'cs' ? 'Upravit' : 'Edit',
                    onTap: _editTripDetails,
                  ),
                  _buildBottomMenuItem(
                    icon: (_trip!.ownerParticipantId == AppPreferences.displayName || 
                           _trip!.ownerParticipantId == AppPreferences.participantId ||
                           _trip!.shareCode == null)
                        ? Icons.wifi
                        : Icons.sync,
                    label: (_trip!.ownerParticipantId == AppPreferences.displayName || 
                           _trip!.ownerParticipantId == AppPreferences.participantId ||
                           _trip!.shareCode == null)
                        ? (AppPreferences.language == 'cs' ? 'Sdílet fotky' : 'Share Photos')
                        : (AppPreferences.language == 'cs' ? 'Synchronizovat' : 'Synchronize'),
                    onTap: () {
                      if (_trip!.ownerParticipantId == AppPreferences.displayName || 
                          _trip!.ownerParticipantId == AppPreferences.participantId ||
                          _trip!.shareCode == null) {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => HostInvitationScreen(trip: _trip!),
                          ),
                        ).then((_) => _loadTrip());
                      } else {
                        _startSync();
                      }
                    },
                  ),
                  _buildBottomMenuItem(
                    icon: Icons.map,
                    label: AppPreferences.language == 'cs' ? 'Ukaž mapu' : 'Show Map',
                    onTap: _openPreview,
                  ),
                  _buildBottomMenuItem(
                    icon: Icons.cloud_upload,
                    label: AppPreferences.language == 'cs' ? 'Uložit projekt' : 'Save Project',
                    onTap: () {
                      ExportHelper.showShareOptionsDialog(
                        context: context,
                        trip: _trip!,
                        places: _places,
                        photos: _photos,
                      );
                    },
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildGalleryTab(ThemeData theme) {
    if (_isScanning) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const CircularProgressIndicator(),
            const SizedBox(height: 16),
            Text(AppPreferences.language == 'cs' ? 'Prohledávám galerii a čtu EXIF data...' : 'Scanning gallery and reading EXIF data...'),
          ],
        ),
      );
    }

    if (_photos.isEmpty) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.photo_library_outlined, size: 48, color: theme.hintColor),
              const SizedBox(height: 12),
              Text(
                AppPreferences.language == 'cs' ? 'Žádné fotografie nebyly nalezeny.' : 'No photos were found.',
                style: theme.textTheme.bodyLarge?.copyWith(color: theme.hintColor),
              ),
              const SizedBox(height: 8),
              Text(
                AppPreferences.language == 'cs'
                    ? 'Ujistěte se, že máte nastaven správný termín cesty a nechte aplikaci vyhledat fotky.'
                    : 'Please make sure you have the correct dates set and search for photos.',
                textAlign: TextAlign.center,
                style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
              ),
              const SizedBox(height: 24),
              ElevatedButton.icon(
                onPressed: _scanPhotos,
                icon: const Icon(Icons.refresh),
                label: Text(AppPreferences.language == 'cs' ? 'Vyhledat fotky v galerii' : 'Scan photos in gallery'),
              ),
            ],
          ),
        ),
      );
    }


    return GridView.builder(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        crossAxisSpacing: 8,
        mainAxisSpacing: 8,
      ),
      itemCount: _photos.length,
      itemBuilder: (context, index) {
        final photo = _photos[index];
        return GestureDetector(
          onTap: () async {
            await Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => PhotoViewerScreen(
                  trip: _trip!,
                  photos: _photos,
                  places: _places,
                  initialIndex: index,
                ),
              ),
            );
            _loadTrip(); // Refresh photos and itinerary after viewing/deleting
          },
          child: PhotoThumbnail(photo: photo, size: 100),
        );
      },
    );
  }

  Widget _buildItineraryTab(ThemeData theme) {
    if (_isScanning) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const CircularProgressIndicator(),
            const SizedBox(height: 16),
            Text(L10n.scanningPhotosProgress),
          ],
        ),
      );
    }

    if (_places.isEmpty) {
      return Center(
        child: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(24.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.map_outlined, size: 48, color: theme.hintColor),
                const SizedBox(height: 12),
                Text(
                  L10n.noPlacesRecognized,
                  style: theme.textTheme.bodyLarge?.copyWith(color: theme.hintColor),
                ),
                const SizedBox(height: 8),
                Text(
                  L10n.scanPhotosDesc,
                  textAlign: TextAlign.center,
                  style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
                ),
                const SizedBox(height: 24),
                ElevatedButton.icon(
                  onPressed: _scanPhotos,
                  icon: const Icon(Icons.refresh),
                  label: Text(L10n.scanPhotosButton),
                ),
              ],
            ),
          ),
        ),
      );
    }


    final grouped = _groupPlacesByDay();
    final sortedDays = grouped.keys.toList()..sort();

    final wikiCard = Card(
      margin: const EdgeInsets.only(bottom: 16, left: 16, right: 16),
      elevation: 1,
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.auto_awesome, color: Colors.blueAccent, size: 20),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    AppPreferences.language == 'cs' ? 'Chcete doplnit popisky z Wikipedie?' : 'Add descriptions from Wikipedia?',
                    style: theme.textTheme.titleSmall?.copyWith(fontWeight: FontWeight.bold),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 6),
            Text(
              AppPreferences.language == 'cs'
                  ? 'Aplikace vyhledá památky a zajímavá místa v okolí a stáhne k nim popisy.'
                  : 'The app searches for sights and interesting places nearby and downloads descriptions.',
              style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
            ),
            const SizedBox(height: 10),
            _isEnriching
                ? Column(
                    children: [
                      const LinearProgressIndicator(),
                      const SizedBox(height: 6),
                      Text(L10n.enrichingProgress, style: const TextStyle(fontSize: 12)),
                    ],
                  )
                : Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      ElevatedButton.icon(
                        onPressed: _enrichPlacesWithWikipedia,
                        icon: const Icon(Icons.download, size: 16),
                        label: Text(AppPreferences.language == 'cs' ? 'Doplnit z Wikipedie' : 'Add from Wikipedia'),
                        style: ElevatedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                        ),
                      ),
                    ],
                  ),
          ],
        ),
      ),
    );

    return ListView.builder(
      itemCount: sortedDays.length + (_showWikiPrompt ? 1 : 0),
      itemBuilder: (context, index) {
        if (_showWikiPrompt) {
          if (index == 0) {
            return Padding(
              padding: const EdgeInsets.only(top: 8.0, bottom: 12.0),
              child: wikiCard,
            );
          }
          final dayIndex = index - 1;
          final day = sortedDays[dayIndex];
          final dayPlaces = grouped[day]!;

          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Day Header
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 12.0),
                child: Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      decoration: BoxDecoration(
                        color: theme.colorScheme.primary,
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Text(
                        '${L10n.dayLabel} $day',
                        style: const TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 14,
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Container(
                        height: 1,
                        color: theme.dividerColor,
                      ),
                    ),
                  ],
                ),
              ),
              // Places List on that day
              ...dayPlaces.map((place) => _buildPlaceItem(place, theme)),
            ],
          );
        } else {
          final day = sortedDays[index];
          final dayPlaces = grouped[day]!;

          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Day Header
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 12.0),
                child: Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      decoration: BoxDecoration(
                        color: theme.colorScheme.primary,
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Text(
                        '${L10n.dayLabel} $day',
                        style: const TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 14,
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: Container(
                        height: 1,
                        color: theme.dividerColor,
                      ),
                    ),
                  ],
                ),
              ),
              // Places List on that day
              ...dayPlaces.map((place) => _buildPlaceItem(place, theme)),
            ],
          );
        }
      },
    );
  }


  Widget _buildPlaceItem(Place place, ThemeData theme) {
    final placePhotos = _getPhotosForPlace(place);

    final arrivalText = place.arrivalTimeUtc != null
        ? DateFormat('HH:mm').format(DateTime.fromMillisecondsSinceEpoch(place.arrivalTimeUtc!))
        : '?';
    final departureText = place.departureTimeUtc != null
        ? DateFormat('HH:mm').format(DateTime.fromMillisecondsSinceEpoch(place.departureTimeUtc!))
        : '?';

    return Container(
      margin: const EdgeInsets.only(left: 16.0, bottom: 20.0),
      decoration: BoxDecoration(
        border: Border(
          left: BorderSide(color: theme.colorScheme.primary.withValues(alpha: 0.3), width: 2),
        ),
      ),
      padding: const EdgeInsets.only(left: 20.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            place.name ?? (AppPreferences.language == 'cs' ? 'Zastávka' : 'Stop'),
                            style: theme.textTheme.titleMedium?.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        IconButton(
                          icon: const Icon(Icons.edit, size: 14),
                          onPressed: () => _renamePlace(place),
                          constraints: const BoxConstraints(),
                          padding: const EdgeInsets.symmetric(horizontal: 8),
                          tooltip: AppPreferences.language == 'cs' ? 'Upravit' : 'Edit',
                        ),
                      ],
                    ),
                    Text(
                      AppPreferences.language == 'cs'
                          ? 'Čas pobytu: $arrivalText – $departureText'
                          : 'Time spent: $arrivalText – $departureText',
                      style: theme.textTheme.bodyMedium?.copyWith(fontSize: 12),
                    ),
                  ],
                ),
              ),
              IconButton(
                icon: const Icon(Icons.navigation, color: AppColors.accent),
                onPressed: () => _showOnMap(place),
                tooltip: AppPreferences.language == 'cs' ? 'Ukázat na mapě' : 'Show on map',
              ),
            ],
          ),
          if (place.description != null) ...[
            const SizedBox(height: 6),
            Text(
              place.description!,
              style: theme.textTheme.bodyMedium?.copyWith(fontSize: 13),
            ),
          ],
          if (placePhotos.isNotEmpty) ...[
            const SizedBox(height: 12),
            SizedBox(
              height: 70,
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: placePhotos.length,
                itemBuilder: (context, index) {
                  final photo = placePhotos[index];
                  final globalIndex = _photos.indexWhere((p) => p.id == photo.id);
                  return Padding(
                    padding: const EdgeInsets.only(right: 6.0),
                    child: GestureDetector(
                      onTap: () async {
                        if (globalIndex != -1) {
                          await Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => PhotoViewerScreen(
                                trip: _trip!,
                                photos: _photos,
                                places: _places,
                                initialIndex: globalIndex,
                              ),
                            ),
                          );
                          _loadTrip();
                        }
                      },
                      child: PhotoThumbnail(photo: photo, size: 70),
                    ),
                  );
                },
              ),
            ),
          ],
        ],
      ),
    );
  }
}

class _EditDisplayNameDialog extends StatefulWidget {
  @override
  State<_EditDisplayNameDialog> createState() => _EditDisplayNameDialogState();
}

class _EditDisplayNameDialogState extends State<_EditDisplayNameDialog> {
  late final TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: AppPreferences.displayName);
  }

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

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(L10n.changeName),
      content: TextField(
        controller: _controller,
        decoration: InputDecoration(
          hintText: L10n.enterNameHint,
          border: const OutlineInputBorder(),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: Text(L10n.zrusit),
        ),
        ElevatedButton(
          onPressed: () async {
            if (_controller.text.trim().isNotEmpty) {
              final navigator = Navigator.of(context);
              await AppPreferences.setDisplayName(_controller.text.trim());
              navigator.pop(true);
            }
          },
          child: Text(L10n.ulozit),
        ),
      ],
    );
  }
}

class _EditTripDialog extends StatefulWidget {
  final Trip trip;

  const _EditTripDialog({required this.trip});

  @override
  State<_EditTripDialog> createState() => _EditTripDialogState();
}

class _EditTripDialogState extends State<_EditTripDialog> {
  late final TextEditingController _nameController;
  late final TextEditingController _passwordController;
  late DateTime _startDate;
  late TimeOfDay _startTime;
  late DateTime _endDate;
  late TimeOfDay _endTime;
  late bool _passwordProtect;
  bool _obscurePassword = true;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text: widget.trip.name);
    _passwordController = TextEditingController(text: widget.trip.password ?? '');
    _passwordProtect = widget.trip.password != null && widget.trip.password!.isNotEmpty;

    _startDate = widget.trip.startTimeUtc != null
        ? DateTime.fromMillisecondsSinceEpoch(widget.trip.startTimeUtc!)
        : DateTime.now().subtract(const Duration(days: 7));
    _startTime = widget.trip.startTimeUtc != null
        ? TimeOfDay.fromDateTime(DateTime.fromMillisecondsSinceEpoch(widget.trip.startTimeUtc!))
        : const TimeOfDay(hour: 0, minute: 0);

    _endDate = widget.trip.finishTimeUtc != null
        ? DateTime.fromMillisecondsSinceEpoch(widget.trip.finishTimeUtc!)
        : DateTime.now().subtract(const Duration(days: 1));
    _endTime = widget.trip.finishTimeUtc != null
        ? TimeOfDay.fromDateTime(DateTime.fromMillisecondsSinceEpoch(widget.trip.finishTimeUtc!))
        : const TimeOfDay(hour: 23, minute: 59);
  }

  @override
  void dispose() {
    _nameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isCs = AppPreferences.language == 'cs';
    final dateFormat = DateFormat('d. M. yyyy');
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return AlertDialog(
      title: Text(isCs ? 'Upravit údaje cesty' : 'Edit trip details'),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              controller: _nameController,
              decoration: InputDecoration(
                labelText: isCs ? 'Název cesty' : 'Trip Name',
                border: const OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 20),
            Text(
              isCs ? 'Začátek cesty (Odjezd):' : 'Start of trip (Departure):',
              style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
            ),
            const SizedBox(height: 6),
            Row(
              children: [
                Expanded(
                  child: OutlinedButton(
                    onPressed: () async {
                      FocusScope.of(context).unfocus();
                      final picked = await showDatePicker(
                        context: context,
                        initialDate: _startDate,
                        firstDate: DateTime(2020),
                        lastDate: DateTime.now(),
                      );
                      if (picked != null) {
                        setState(() => _startDate = picked);
                      }
                    },
                    child: Text(dateFormat.format(_startDate)),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: OutlinedButton(
                    onPressed: () async {
                      FocusScope.of(context).unfocus();
                      final picked = await showTimePicker(
                        context: context,
                        initialTime: _startTime,
                      );
                      if (picked != null) {
                        setState(() => _startTime = picked);
                      }
                    },
                    child: Text(_startTime.format(context)),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Text(
              isCs ? 'Konec cesty (Návrat):' : 'End of trip (Arrival):',
              style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
            ),
            const SizedBox(height: 6),
            Row(
              children: [
                Expanded(
                  child: OutlinedButton(
                    onPressed: () async {
                      FocusScope.of(context).unfocus();
                      final picked = await showDatePicker(
                        context: context,
                        initialDate: _endDate,
                        firstDate: DateTime(2020),
                        lastDate: DateTime.now(),
                      );
                      if (picked != null) {
                        setState(() => _endDate = picked);
                      }
                    },
                    child: Text(dateFormat.format(_endDate)),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: OutlinedButton(
                    onPressed: () async {
                      FocusScope.of(context).unfocus();
                      final picked = await showTimePicker(
                        context: context,
                        initialTime: _endTime,
                      );
                      if (picked != null) {
                        setState(() => _endTime = picked);
                      }
                    },
                    child: Text(_endTime.format(context)),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 20),
            Card(
              elevation: 0,
              color: Theme.of(context).colorScheme.surfaceContainerHighest,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
                side: BorderSide(
                  color: isDark ? Colors.white10 : Colors.black12,
                ),
              ),
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
                child: Column(
                  children: [
                    SwitchListTile(
                      value: _passwordProtect,
                      onChanged: (val) {
                        setState(() {
                          _passwordProtect = val;
                        });
                      },
                      title: Text(L10n.passwordProtectLabel),
                      subtitle: Text(
                        isCs
                            ? 'Zašifruje data interaktivní mapy'
                            : 'Encrypts the interactive map data',
                        style: const TextStyle(fontSize: 12),
                      ),
                      secondary: Icon(
                        _passwordProtect ? Icons.lock : Icons.lock_open,
                        color: _passwordProtect
                            ? Theme.of(context).colorScheme.primary
                            : Theme.of(context).colorScheme.onSurfaceVariant,
                      ),
                    ),
                    if (_passwordProtect)
                      Padding(
                        padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
                        child: TextFormField(
                          controller: _passwordController,
                          obscureText: _obscurePassword,
                          decoration: InputDecoration(
                            labelText: L10n.passwordInputLabel,
                            hintText: L10n.passwordInputHint,
                            prefixIcon: const Icon(Icons.password),
                            suffixIcon: IconButton(
                              icon: Icon(
                                _obscurePassword
                                    ? Icons.visibility
                                    : Icons.visibility_off,
                              ),
                              onPressed: () {
                                setState(() {
                                  _obscurePassword = !_obscurePassword;
                                });
                              },
                            ),
                            border: const OutlineInputBorder(),
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: Text(L10n.zrusit),
        ),
        ElevatedButton(
          onPressed: () async {
            if (_nameController.text.trim().isEmpty) return;
            if (_passwordProtect && _passwordController.text.trim().isEmpty) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(L10n.passwordEmptyValidator),
                  backgroundColor: Colors.red,
                ),
              );
              return;
            }

            final startMillis = DateTime(_startDate.year, _startDate.month, _startDate.day, _startTime.hour, _startTime.minute).millisecondsSinceEpoch;
            final endMillis = DateTime(_endDate.year, _endDate.month, _endDate.day, _endTime.hour, _endTime.minute).millisecondsSinceEpoch;

            if (startMillis >= endMillis) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(L10n.tripStartMustBeBeforeEnd),
                  backgroundColor: Colors.red,
                ),
              );
              return;
            }

            final updatedTrip = Trip(
              id: widget.trip.id,
              name: _nameController.text.trim(),
              startTimeUtc: startMillis,
              finishTimeUtc: endMillis,
              createdAtUtc: widget.trip.createdAtUtc,
              status: widget.trip.status,
              ownerParticipantId: widget.trip.ownerParticipantId,
              timezoneId: widget.trip.timezoneId,
              shareCode: widget.trip.shareCode,
              coverPhotoId: widget.trip.coverPhotoId,
              password: _passwordProtect ? _passwordController.text.trim() : null,
            );

            final navigator = Navigator.of(context);
            await DatabaseHelper.instance.updateTrip(updatedTrip);
            navigator.pop(true);
          },
          child: Text(L10n.ulozit),
        ),
      ],
    );
  }
}

class _RenamePlaceDialog extends StatefulWidget {
  final Place place;

  const _RenamePlaceDialog({required this.place});

  @override
  State<_RenamePlaceDialog> createState() => _RenamePlaceDialogState();
}

class _RenamePlaceDialogState extends State<_RenamePlaceDialog> {
  late final TextEditingController _nameController;
  late final TextEditingController _descController;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text: widget.place.name);
    _descController = TextEditingController(text: widget.place.description);
  }

  @override
  void dispose() {
    _nameController.dispose();
    _descController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(AppPreferences.language == 'cs' ? 'Upravit zastávku' : 'Edit Stop'),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: _nameController,
              decoration: InputDecoration(
                labelText: AppPreferences.language == 'cs' ? 'Název místa' : 'Place Name',
                border: const OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            TextField(
              controller: _descController,
              maxLines: 3,
              decoration: InputDecoration(
                labelText: AppPreferences.language == 'cs' ? 'Popis místa' : 'Place Description',
                border: const OutlineInputBorder(),
              ),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: Text(L10n.zrusit),
        ),
        ElevatedButton(
          onPressed: () async {
            if (_nameController.text.trim().isNotEmpty) {
              final updatedPlace = Place(
                id: widget.place.id,
                tripId: widget.place.tripId,
                dayNumber: widget.place.dayNumber,
                name: _nameController.text.trim(),
                latitude: widget.place.latitude,
                longitude: widget.place.longitude,
                arrivalTimeUtc: widget.place.arrivalTimeUtc,
                departureTimeUtc: widget.place.departureTimeUtc,
                description: _descController.text.trim(),
              );
              final navigator = Navigator.of(context);
              await DatabaseHelper.instance.insertPlace(updatedPlace);
              navigator.pop(true);
            }
          },
          child: Text(L10n.ulozit),
        ),
      ],
    );
  }
}
