import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:go_router/go_router.dart';
import '../core/database.dart';
import '../core/theme.dart';
import '../models/trip.dart';
import '../models/photo.dart';
import '../models/place.dart';
import '../services/media_scanner.dart';
import '../widgets/photo_thumbnail.dart';
import '../services/place_clustering.dart';
import 'host_invitation_screen.dart';



class TripActiveScreen extends StatefulWidget {
  final String tripId;

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

  @override
  State<TripActiveScreen> createState() => _TripActiveScreenState();
}

class _TripActiveScreenState extends State<TripActiveScreen> {
  Trip? _trip;
  List<Photo> _photos = [];
  List<Place> _places = [];
  bool _isLoading = true;
  bool _isScanning = false;

  @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;
      });
    }
  }

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

    final initialDate = _trip!.startTimeUtc != null
        ? DateTime.fromMillisecondsSinceEpoch(_trip!.startTimeUtc!)
        : DateTime.now();

    final pickedDate = await showDatePicker(
      context: context,
      initialDate: initialDate,
      firstDate: DateTime(2020),
      lastDate: DateTime.now(),
    );

    if (pickedDate != null && mounted) {
      final pickedTime = await showTimePicker(
        context: context,
        initialTime: TimeOfDay.fromDateTime(initialDate),
      );

      if (pickedTime != null) {
        final newStart = DateTime(
          pickedDate.year,
          pickedDate.month,
          pickedDate.day,
          pickedTime.hour,
          pickedTime.minute,
        );

        final updatedTrip = Trip(
          id: _trip!.id,
          name: _trip!.name,
          startTimeUtc: newStart.millisecondsSinceEpoch,
          finishTimeUtc: _trip!.finishTimeUtc,
          createdAtUtc: _trip!.createdAtUtc,
          status: _trip!.status,
          ownerParticipantId: _trip!.ownerParticipantId,
          timezoneId: _trip!.timezoneId,
          shareCode: _trip!.shareCode,
          coverPhotoId: _trip!.coverPhotoId,
        );

        await DatabaseHelper.instance.updateTrip(updatedTrip);
        _loadTrip();
      }
    }
  }

  Future<void> _scanPhotos() async {
    if (_trip == null) return;
    
    setState(() {
      _isScanning = true;
    });

    try {
      final photos = await MediaScanner.scanPhotosForTrip(_trip!);
      await PlaceClusteringService.clusterTripPlaces(_trip!);
      
      if (mounted) {
        setState(() {
          _isScanning = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Skenování dokončeno. Nalezeno ${photos.length} nových fotografií.')),
        );
        _loadTrip();
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isScanning = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Chyba při skenování: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

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

    final confirm = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Ukončit cestu?'),
        content: const Text(
          'Tímto uzavřete záznam cesty a spustí se závěrečné zpracování fotografií.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('Zrušit'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.pop(context, true),
            style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
            child: const Text('Ukončit'),
          ),
        ],
      ),
    );

    if (confirm == true && mounted) {
      final now = DateTime.now().millisecondsSinceEpoch;
      final updatedTrip = Trip(
        id: _trip!.id,
        name: _trip!.name,
        startTimeUtc: _trip!.startTimeUtc,
        finishTimeUtc: now,
        createdAtUtc: _trip!.createdAtUtc,
        status: TripStatus.finished,
        ownerParticipantId: _trip!.ownerParticipantId,
        timezoneId: _trip!.timezoneId,
        shareCode: _trip!.shareCode,
        coverPhotoId: _trip!.coverPhotoId,
      );

      await DatabaseHelper.instance.updateTrip(updatedTrip);
      await PlaceClusteringService.clusterTripPlaces(updatedTrip);
      if (mounted) {
        context.pushReplacement('/detail/${_trip!.id}');
      }
    }
  }

  int _calculateDaysElapsed() {
    if (_trip == null || _trip!.startTimeUtc == null) return 1;
    final start = DateTime.fromMillisecondsSinceEpoch(_trip!.startTimeUtc!);
    final diff = DateTime.now().difference(start).inDays;
    return diff + 1;
  }

  @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: const Text('Chyba')),
        body: const Center(child: Text('Cesta nebyla nalezena')),
      );
    }

    final startDateText = _trip!.startTimeUtc != null
        ? DateFormat('d. M. yyyy, HH:mm').format(
            DateTime.fromMillisecondsSinceEpoch(_trip!.startTimeUtc!),
          )
        : 'Neznámý začátek';

    return Scaffold(
      appBar: AppBar(
        title: Text(_trip!.name),
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(24.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Trip Header Info
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [Color(0xFF1E3A8A), Color(0xFF3B82F6)],
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                  ),
                  borderRadius: BorderRadius.circular(16),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text(
                          'Cesta probíhá',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
                          decoration: BoxDecoration(
                            color: Colors.white24,
                            borderRadius: BorderRadius.circular(20),
                          ),
                          child: Text(
                            'Den ${_calculateDaysElapsed()}',
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),
                    Text(
                      _trip!.name,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 28,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 16),
                    GestureDetector(
                      onTap: _changeStartTime,
                      child: Row(
                        children: [
                          const Icon(Icons.access_time, color: Colors.white70, size: 16),
                          const SizedBox(width: 6),
                          Expanded(
                            child: Text(
                              'Od $startDateText (klepnutím upravíte)',
                              style: const TextStyle(
                                color: Colors.white70,
                                fontSize: 13,
                                decoration: TextDecoration.underline,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 32),

              // Statistics Section
              Text(
                'Dnešní statistika',
                style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 16),
              Row(
                children: [
                  Expanded(
                    child: _buildStatCard(
                      icon: Icons.photo_library,
                      value: '${_photos.length}',
                      label: 'fotografií',
                      theme: theme,
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: _buildStatCard(
                      icon: Icons.location_on,
                      value: '${_places.length}',
                      label: 'míst',
                      theme: theme,
                    ),
                  ),
                ],
              ),
              if (_photos.isNotEmpty) ...[
                const SizedBox(height: 24),
                Text(
                  'Nalezené fotografie',
                  style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 12),
                SizedBox(
                  height: 100,
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal,
                    itemCount: _photos.length,
                    itemBuilder: (context, index) {
                      final photo = _photos[index];
                      return Padding(
                        padding: const EdgeInsets.only(right: 8.0),
                        child: PhotoThumbnail(photo: photo, size: 100),
                      );
                    },
                  ),
                ),
              ],
              const Spacer(),

              // Action buttons
              if (_isScanning)
                const Center(
                  child: Padding(
                    padding: EdgeInsets.all(16.0),
                    child: Column(
                      children: [
                        CircularProgressIndicator(),
                        SizedBox(height: 12),
                        Text('Skenuji média a EXIF metadata...'),
                      ],
                    ),
                  ),
                )
              else
                Column(
                  children: [
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton.icon(
                        onPressed: _scanPhotos,
                        icon: const Icon(Icons.refresh),
                        label: const Text('Zkontrolovat fotky'),
                      ),
                    ),
                    const SizedBox(height: 12),
                    Row(
                      children: [
                        Expanded(
                          child: OutlinedButton.icon(
                            onPressed: () {
                              if (_trip != null) {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => HostInvitationScreen(trip: _trip!),
                                  ),
                                ).then((_) => _loadTrip());
                              }
                            },
                            icon: const Icon(Icons.person_add),
                            label: const Text('Přidat účastníka'),
                          ),
                        ),

                        const SizedBox(width: 16),
                        Expanded(
                          child: ElevatedButton.icon(
                            onPressed: _finishTrip,
                            icon: const Icon(Icons.stop),
                            label: const Text('Ukončit cestu'),
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.red,
                              foregroundColor: Colors.white,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStatCard({
    required IconData icon,
    required String value,
    required String label,
    required ThemeData theme,
  }) {
    final isDark = theme.brightness == Brightness.dark;
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: isDark ? AppColors.darkBgSecondary : AppColors.lightBgSecondary,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: isDark ? AppColors.darkBorder : AppColors.lightBorder,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, color: AppColors.accent, size: 24),
          const SizedBox(height: 12),
          Text(
            value,
            style: theme.textTheme.headlineMedium?.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(
            label,
            style: theme.textTheme.bodyMedium,
          ),
        ],
      ),
    );
  }
}
