import 'dart:io';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import '../core/database.dart';
import '../core/preferences.dart';
import '../core/theme.dart';
import '../core/l10n.dart';
import '../models/trip.dart';
import '../main.dart';
import 'qr_scanner_screen.dart';
import '../services/export_helper.dart';

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

  @override
  State<TripListScreen> createState() => _TripListScreenState();
}

class _TripListScreenState extends State<TripListScreen> {
  List<Trip> _trips = [];
  bool _isLoading = true;
  String _displayName = '';
  String _themeMode = 'dark';

  @override
  void initState() {
    super.initState();
    _loadData();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _checkNamePrompt();
    });
  }

  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
    });
    final trips = await DatabaseHelper.instance.getAllTrips();
    setState(() {
      _trips = trips;
      _displayName = AppPreferences.displayName;
      _themeMode = AppPreferences.themeMode;
      _isLoading = false;
    });
  }

  void _toggleTheme() async {
    final nextTheme = _themeMode == 'dark' ? 'light' : 'dark';
    await AppPreferences.setThemeMode(nextTheme);
    setState(() {
      _themeMode = nextTheme;
    });
    ThemeNotifier.updateTheme(nextTheme);
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            nextTheme == 'dark' ? L10n.darkModeEnabled : L10n.lightModeEnabled,
          ),
          duration: const Duration(seconds: 1),
        ),
      );
    }
  }

  void _toggleLanguage() async {
    final nextLang = AppPreferences.language == 'en' ? 'cs' : 'en';
    await AppPreferences.setLanguage(nextLang);
    LanguageNotifier.updateLanguage(nextLang);
    _loadData(); // Trigger list date re-format
  }

  Future<void> _editDisplayName() async {
    final controller = TextEditingController(text: _displayName);
    await showDialog(
      context: context,
      builder: (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) {
                  await AppPreferences.setDisplayName(controller.text.trim());
                  setState(() {
                    _displayName = controller.text.trim();
                  });
                  if (!context.mounted) return;
                  Navigator.pop(context);
                }
              },
              child: Text(L10n.ulozit),
            ),
          ],
        );
      },
    );
  }

  void _checkNamePrompt() {
    if (!AppPreferences.hasPromptedName) {
      _promptDisplayName();
    }
  }

  Future<void> _promptDisplayName() async {
    final controller = TextEditingController(text: AppPreferences.displayName.startsWith('Traveler_') ? '' : AppPreferences.displayName);
    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return PopScope(
          canPop: false,
          child: AlertDialog(
            title: Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(6),
                  child: Image.asset(
                    'assets/logo.jpg',
                    width: 28,
                    height: 28,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) => const Icon(Icons.flight_takeoff, color: AppColors.accent),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    AppPreferences.language == 'cs' ? 'Vítejte!' : 'Welcome!',
                  ),
                ),
              ],
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  AppPreferences.language == 'cs'
                      ? 'Zadejte prosím své jméno pro přizpůsobení aplikace:'
                      : 'Please enter your name to personalize the app:',
                  style: const TextStyle(fontSize: 14),
                ),
                const SizedBox(height: 16),
                TextField(
                  controller: controller,
                  autofocus: true,
                  decoration: InputDecoration(
                    labelText: AppPreferences.language == 'cs' ? 'Vaše jméno' : 'Your Name',
                    border: const OutlineInputBorder(),
                  ),
                ),
              ],
            ),
            actions: [
              ElevatedButton(
                onPressed: () async {
                  final entered = controller.text.trim();
                  if (entered.isNotEmpty) {
                    await AppPreferences.setDisplayName(entered);
                    await AppPreferences.setHasPromptedName(true);
                    setState(() {
                      _displayName = entered;
                    });
                    if (context.mounted) {
                      Navigator.pop(context);
                    }
                  }
                },
                child: Text(AppPreferences.language == 'cs' ? 'Pokračovat' : 'Continue'),
              ),
            ],
          ),
        );
      },
    );
  }

  Future<void> _scanQrToJoin() async {
    final tripId = await Navigator.push<String>(
      context,
      MaterialPageRoute(builder: (context) => const QrScannerScreen()),
    );

    if (tripId != null && mounted) {
      _loadData();
      context.push('/active/$tripId');
    }
  }

  Future<void> _confirmDeleteTrip(Trip trip) async {
    final isCs = AppPreferences.language == 'cs';
    bool deleteDownloads = false;

    final confirm = await showDialog<bool>(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setStateDialog) {
            return AlertDialog(
              title: Text(L10n.deleteTripConfirmTitle),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    L10n.deleteTripConfirmBody.replaceAll('\$name', trip.name),
                  ),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      Checkbox(
                        value: deleteDownloads,
                        onChanged: (val) {
                          setStateDialog(() {
                            deleteDownloads = val ?? false;
                          });
                        },
                      ),
                      Expanded(
                        child: GestureDetector(
                          onTap: () {
                            setStateDialog(() {
                              deleteDownloads = !deleteDownloads;
                            });
                          },
                          child: Text(
                            isCs
                                ? 'Smazat také exportované soubory ze složky Downloads/LVM'
                                : 'Also delete exported files from Downloads/LVM',
                            style: const TextStyle(fontSize: 13),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: Text(L10n.zrusit),
                ),
                ElevatedButton(
                  onPressed: () => Navigator.pop(context, true),
                  style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
                  child: Text(L10n.smazat),
                ),
              ],
            );
          },
        );
      },
    );

    if (confirm != true) return;
    if (!mounted) return;

    final messenger = ScaffoldMessenger.of(context);

    // 1. Delete from database
    await DatabaseHelper.instance.deleteTrip(trip.id);

    // 2. Conditionally delete files from Downloads/LVM
    if (deleteDownloads) {
      try {
        final sanitizedTripName = trip.name.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_').trim();
        
        Directory? downloadsDir;
        if (Platform.isAndroid) {
          final pubDownload = Directory('/storage/emulated/0/Download');
          if (await pubDownload.exists()) {
            downloadsDir = pubDownload;
          } else {
            final sdcardDownload = Directory('/sdcard/Download');
            if (await sdcardDownload.exists()) {
              downloadsDir = sdcardDownload;
            }
          }
        }

        if (downloadsDir != null) {
          final lvmDir = Directory('${downloadsDir.path}/LVM');
          if (await lvmDir.exists()) {
            // Delete folder: LVM/<Trip Name>
            final tripFolder = Directory('${lvmDir.path}/$sanitizedTripName');
            if (await tripFolder.exists()) {
              await tripFolder.delete(recursive: true);
            }

            // Delete ZIP file: LVM/<Trip Name>_web.zip
            final webZip = File('${lvmDir.path}/${sanitizedTripName}_web.zip');
            if (await webZip.exists()) {
              await webZip.delete();
            }
          }

          // Delete ZIP file: Downloads/<Trip Name>.zip (desktop version zip)
          final desktopZip = File('${downloadsDir.path}/$sanitizedTripName.zip');
          if (await desktopZip.exists()) {
            await desktopZip.delete();
          }
        }
      } catch (e) {
        debugPrint('Chyba při mazání souborů ze složky Downloads: $e');
      }
    }

    messenger.showSnackBar(
      SnackBar(content: Text(L10n.tripDeleted)),
    );
    _loadData();
  }

  String _formatTripDates(Trip trip) {
    if (trip.startTimeUtc == null && trip.finishTimeUtc == null) {
      return L10n.terminNezacal;
    }
    final df = DateFormat('d. M. yyyy');
    final start = trip.startTimeUtc != null
        ? df.format(DateTime.fromMillisecondsSinceEpoch(trip.startTimeUtc!))
        : '?';
    final finish = trip.finishTimeUtc != null
        ? df.format(DateTime.fromMillisecondsSinceEpoch(trip.finishTimeUtc!))
        : L10n.probiha;
    return '$start – $finish';
  }

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

    return Scaffold(
      appBar: AppBar(
        title: Row(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child: Image.asset(
                'assets/logo.jpg',
                width: 32,
                height: 32,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) => Container(
                  width: 32,
                  height: 32,
                  decoration: const BoxDecoration(
                    shape: BoxShape.circle,
                    color: AppColors.accent,
                  ),
                  child: const Icon(Icons.flight_takeoff, size: 16, color: Colors.white),
                ),
              ),
            ),
            const SizedBox(width: 10),
            Text(
              L10n.appTitle,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 20,
              ),
            ),
          ],
        ),
      ),
      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) => const Icon(Icons.flight_takeoff, size: 40, color: AppColors.accent),
                      ),
                    ),
                    const SizedBox(height: 10),
                    Text(
                      L10n.appTitle,
                      style: theme.textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      _displayName,
                      style: theme.textTheme.bodyMedium?.copyWith(
                        color: theme.hintColor,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
              ListTile(
                leading: const Icon(Icons.person),
                title: Text(AppPreferences.language == 'cs' ? 'Změnit jméno' : 'Change Name'),
                subtitle: Text(_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: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          AppPreferences.language == 'cs' ? 'Ahoj, $_displayName' : 'Hi, $_displayName',
                          style: theme.textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.w600,
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                        Text(
                          L10n.readyForNextAdventure,
                          style: theme.textTheme.bodyMedium,
                        ),
                      ],
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      ElevatedButton.icon(
                        onPressed: () => context.push('/create').then((_) => _loadData()),
                        icon: const Icon(Icons.add),
                        label: Text(L10n.newTrip),
                        style: ElevatedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                          textStyle: const TextStyle(fontSize: 13),
                        ),
                      ),
                      const SizedBox(height: 8),
                      OutlinedButton.icon(
                        onPressed: _scanQrToJoin,
                        icon: const Icon(Icons.qr_code_scanner),
                        label: Text(L10n.pripojitSe),
                        style: OutlinedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                          textStyle: const TextStyle(fontSize: 13),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            const Divider(height: 1),
            Expanded(
              child: _isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : _trips.isEmpty
                      ? _buildEmptyState()
                      : RefreshIndicator(
                          onRefresh: _loadData,
                          child: ListView.builder(
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                            itemCount: _trips.length,
                            itemBuilder: (context, index) {
                              final trip = _trips[index];
                              return _buildTripCard(trip, theme);
                            },
                          ),
                        ),
            ),
          ],
        ),
      ),
    );
  }


  Widget _buildEmptyState() {
    return Center(
      child: SingleChildScrollView(
        physics: const AlwaysScrollableScrollPhysics(),
        child: Padding(
          padding: const EdgeInsets.all(32.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text(
                '✈️',
                style: TextStyle(fontSize: 64),
              ),
              const SizedBox(height: 16),
              Text(
                L10n.noTripsYet,
                style: Theme.of(context).textTheme.titleLarge?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
              ),
              const SizedBox(height: 8),
              Text(
                AppPreferences.language == 'cs'
                    ? 'Vytvořte svou první dovolenou kliknutím na tlačítko „Nová cesta“ výše!'
                    : 'Create your first vacation by clicking the "New Trip" button above!',
                textAlign: TextAlign.center,
                style: const TextStyle(color: Colors.grey),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTripCard(Trip trip, ThemeData theme) {
    final isDark = theme.brightness == Brightness.dark;
    
    String statusText = '';
    Color statusColor = Colors.grey;
    IconData statusIcon = Icons.calendar_month;

    switch (trip.status) {
      case TripStatus.planned:
        statusText = AppPreferences.language == 'cs' ? 'Naplánováno' : 'Planned';
        statusColor = AppColors.accent;
        statusIcon = Icons.schedule;
        break;
      case TripStatus.active:
        statusText = AppPreferences.language == 'cs' ? 'Probíhá' : 'Active';
        statusColor = AppColors.success;
        statusIcon = Icons.play_arrow;
        break;
      case TripStatus.finished:
        statusText = AppPreferences.language == 'cs' ? 'Dokončeno' : 'Finished';
        statusColor = Colors.blueGrey;
        statusIcon = Icons.check_circle;
        break;
      case TripStatus.archived:
        statusText = AppPreferences.language == 'cs' ? 'Archivováno' : 'Archived';
        statusColor = Colors.grey;
        statusIcon = Icons.archive;
        break;
    }

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      clipBehavior: Clip.antiAlias,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(
          color: isDark ? AppColors.darkBorder : AppColors.lightBorder,
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: () {
          if (trip.status == TripStatus.active) {
            context.push('/active/${trip.id}').then((_) => _loadData());
          } else {
            context.push('/detail/${trip.id}').then((_) => _loadData());
          }
        },
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      trip.name,
                      style: theme.textTheme.titleLarge?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: statusColor.withValues(alpha: 0.15),
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(color: statusColor.withValues(alpha: 0.5), width: 1),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(statusIcon, size: 12, color: statusColor),
                        const SizedBox(width: 4),
                        Text(
                          statusText,
                          style: TextStyle(
                            fontSize: 11,
                            fontWeight: FontWeight.bold,
                            color: statusColor,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                children: [
                  const Icon(Icons.date_range, size: 14, color: Colors.grey),
                  const SizedBox(width: 6),
                  Text(
                    _formatTripDates(trip),
                    style: const TextStyle(fontSize: 13, color: Colors.grey),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              const Divider(height: 1),
              const SizedBox(height: 12),
              FutureBuilder<List>(
                future: Future.wait([
                  DatabaseHelper.instance.getPhotosForTrip(trip.id),
                  DatabaseHelper.instance.getPlacesForTrip(trip.id),
                ]),
                builder: (context, snapshot) {
                  int photoCount = 0;
                  int placeCount = 0;
                  if (snapshot.hasData) {
                    photoCount = snapshot.data![0].length;
                    placeCount = snapshot.data![1].length;
                  }
                  final photosStr = AppPreferences.language == 'cs'
                      ? '$photoCount fotografií'
                      : '$photoCount photos';
                  final placesStr = AppPreferences.language == 'cs'
                      ? '$placeCount míst'
                      : '$placeCount places';

                  return Row(
                    children: [
                      Icon(Icons.photo_library, size: 14, color: theme.hintColor),
                      const SizedBox(width: 4),
                      Text(
                        photosStr,
                        style: TextStyle(fontSize: 12, color: theme.hintColor),
                      ),
                      const SizedBox(width: 16),
                      Icon(Icons.location_on, size: 14, color: theme.hintColor),
                      const SizedBox(width: 4),
                      Text(
                        placesStr,
                        style: TextStyle(fontSize: 12, color: theme.hintColor),
                      ),
                      const Spacer(),
                      GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () => _confirmDeleteTrip(trip),
                        child: const Padding(
                          padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                          child: Icon(Icons.delete_outline, size: 18, color: Colors.redAccent),
                        ),
                      ),
                    ],
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
