import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/photo.dart';
import '../models/trip.dart';
import '../models/place.dart';
import '../services/media_scanner.dart';
import '../services/place_clustering.dart';
import '../core/database.dart';
import '../core/preferences.dart';
import '../core/l10n.dart';

class PhotoViewerScreen extends StatefulWidget {
  final Trip trip;
  final List<Photo> photos;
  final List<Place> places;
  final int initialIndex;

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

  @override
  State<PhotoViewerScreen> createState() => _PhotoViewerScreenState();
}

class _PhotoViewerScreenState extends State<PhotoViewerScreen> {
  late List<Photo> _photos;
  late PageController _pageController;
  late int _currentIndex;
  bool _isDeleting = false;

  @override
  void initState() {
    super.initState();
    _photos = List.from(widget.photos);
    _currentIndex = widget.initialIndex;
    _pageController = PageController(initialPage: widget.initialIndex);
  }

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

  Place? _getPlaceForPhoto(Photo photo) {
    final time = photo.dateTakenUtc ?? photo.dateAddedUtc;
    if (time == null) return null;
    for (final place in widget.places) {
      if (place.arrivalTimeUtc != null && place.departureTimeUtc != null) {
        if (time >= place.arrivalTimeUtc! && time <= place.departureTimeUtc!) {
          return place;
        }
      }
    }
    return null;
  }

  void _showPhotoInfo() {
    if (_photos.isEmpty) return;
    final photo = _photos[_currentIndex];
    final place = _getPlaceForPhoto(photo);
    final time = photo.dateTakenUtc ?? photo.dateAddedUtc;
    final timeText = time != null
        ? DateFormat('d. M. yyyy HH:mm').format(DateTime.fromMillisecondsSinceEpoch(time))
        : (AppPreferences.language == 'cs' ? 'Neznámý čas' : 'Unknown time');

    final placeName = place?.name ?? (AppPreferences.language == 'cs' ? 'Mimo hlavní zastávky' : 'Outside main stops');
    final placeDesc = place?.description ?? (AppPreferences.language == 'cs' ? 'Tato fotografie nebyla přiřazena k žádné konkrétní zastávce.' : 'This photo is not assigned to any specific stop.');

    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) {
        final localTheme = Theme.of(context);
        return SafeArea(
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      const Icon(Icons.info_outline, color: Colors.blue),
                      const SizedBox(width: 8),
                      Text(
                        AppPreferences.language == 'cs' ? 'Podrobnosti o fotografii' : 'Photo Details',
                        style: localTheme.textTheme.titleMedium?.copyWith(
                              fontWeight: FontWeight.bold,
                            ),
                      ),
                    ],
                  ),
                  const Divider(height: 24),
                  Text(
                    AppPreferences.language == 'cs' ? 'Lokalita:' : 'Location:',
                    style: localTheme.textTheme.bodySmall?.copyWith(fontWeight: FontWeight.bold, color: Colors.grey),
                  ),
                  Text(
                    placeName,
                    style: localTheme.textTheme.bodyLarge?.copyWith(fontWeight: FontWeight.w600),
                  ),
                  const SizedBox(height: 12),
                  Text(
                    AppPreferences.language == 'cs' ? 'Čas pořízení:' : 'Date Taken:',
                    style: localTheme.textTheme.bodySmall?.copyWith(fontWeight: FontWeight.bold, color: Colors.grey),
                  ),
                  Text(timeText, style: localTheme.textTheme.bodyMedium),
                  if (photo.latitude != null && photo.longitude != null) ...[
                    const SizedBox(height: 12),
                    Text(
                      AppPreferences.language == 'cs' ? 'GPS Souřadnice:' : 'GPS Coordinates:',
                      style: localTheme.textTheme.bodySmall?.copyWith(fontWeight: FontWeight.bold, color: Colors.grey),
                    ),
                    Text('${photo.latitude!.toStringAsFixed(6)}, ${photo.longitude!.toStringAsFixed(6)}',
                        style: localTheme.textTheme.bodyMedium),
                  ],
                  const SizedBox(height: 12),
                  Text(
                    AppPreferences.language == 'cs' ? 'Popis místa:' : 'Place Description:',
                    style: localTheme.textTheme.bodySmall?.copyWith(fontWeight: FontWeight.bold, color: Colors.grey),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    placeDesc,
                    style: localTheme.textTheme.bodyMedium,
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Future<void> _deleteCurrentPhoto() async {
    if (_isDeleting || _photos.isEmpty) return;

    final confirm = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(AppPreferences.language == 'cs' ? 'Smazat fotografii?' : 'Delete photo?'),
        content: Text(AppPreferences.language == 'cs'
            ? 'Tato fotografie bude trvale odebrána z vašeho itineráře cesty.'
            : 'This photo will be permanently removed from your itinerary.'),
        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;

    setState(() {
      _isDeleting = true;
    });

    try {
      final currentPhoto = _photos[_currentIndex];

      // 1. Delete from database immediately
      await DatabaseHelper.instance.deletePhoto(currentPhoto.id);

      // 2. Remove photo locally and update UI instantly
      final removedIndex = _currentIndex;
      setState(() {
        _photos.removeAt(removedIndex);
        _isDeleting = false;
        if (_currentIndex >= _photos.length) {
          _currentIndex = _photos.length - 1;
        }
      });

      if (_photos.isEmpty) {
        if (mounted) {
          Navigator.pop(context);
        }
      } else {
        // We use PageController.jumpToPage to go to the new item. 
        // We call it inside postFrameCallback to let the PageView rebuild with the new length.
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            _pageController.jumpToPage(_currentIndex);
          }
        });
      }

      // 3. Re-cluster in background without blocking UI
      Future.microtask(() async {
        try {
          await PlaceClusteringService.clusterTripPlaces(widget.trip);
        } catch (_) {}
      });

    } catch (e) {
      setState(() {
        _isDeleting = false;
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(AppPreferences.language == 'cs'
                ? 'Chyba při mazání fotografie: $e'
                : 'Error deleting photo: $e'),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        iconTheme: const IconThemeData(color: Colors.white),
        title: Text(
          _photos.isEmpty ? 'Prohlížeč' : '${_currentIndex + 1} z ${_photos.length}',
          style: const TextStyle(color: Colors.white),
        ),
        actions: [
          if (!_isDeleting && _photos.isNotEmpty)
            IconButton(
              icon: const Icon(Icons.delete_outline, color: Colors.redAccent),
              onPressed: _deleteCurrentPhoto,
              tooltip: 'Smazat fotku',
            ),
        ],
      ),
      body: _photos.isEmpty
          ? const Center(child: CircularProgressIndicator())
          : Stack(
              children: [
                PageView.builder(
                  controller: _pageController,
                  itemCount: _photos.length,
                  onPageChanged: (index) {
                    setState(() {
                      _currentIndex = index;
                    });
                  },
                  itemBuilder: (context, index) {
                    final photo = _photos[index];
                    return Container(
                      key: ValueKey(photo.id),
                      color: Colors.black,
                      child: photo.contentUri.startsWith('content://')
                          ? FutureBuilder<Uint8List>(
                              // Load high quality resized image (1280x1280) for performance & smooth swiping
                              future: MediaScanner.getThumbnail(photo.contentUri, width: 1280, height: 1280),
                              builder: (context, snapshot) {
                                if (snapshot.connectionState == ConnectionState.waiting) {
                                  return const Center(
                                    child: CircularProgressIndicator(color: Colors.white),
                                  );
                                }
                                if (snapshot.hasError) {
                                  return const Center(
                                    child: Icon(Icons.broken_image, size: 64, color: Colors.white54),
                                  );
                                }
                                return InteractiveViewer(
                                  minScale: 1.0,
                                  maxScale: 4.0,
                                  child: Image.memory(
                                    snapshot.data!,
                                    fit: BoxFit.contain,
                                  ),
                                );
                              },
                            )
                          : InteractiveViewer(
                              minScale: 1.0,
                              maxScale: 4.0,
                              child: Image.file(
                                File(photo.contentUri),
                                fit: BoxFit.contain,
                                cacheWidth: 1280, // cache resized image in memory for smooth swiping
                                errorBuilder: (context, error, stackTrace) {
                                  return const Center(
                                    child: Icon(Icons.broken_image, size: 64, color: Colors.white54),
                                  );
                                },
                              ),
                            ),
                    );
                  },
                ),
                Positioned(
                  bottom: 24,
                  right: 24,
                  child: FloatingActionButton(
                    heroTag: 'info_fab',
                    mini: true,
                    backgroundColor: Colors.black.withValues(alpha: 0.6),
                    foregroundColor: Colors.white,
                    onPressed: _showPhotoInfo,
                    child: const Icon(Icons.info_outline),
                  ),
                ),
              ],
            ),
    );
  }
}
