import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:uuid/uuid.dart';
import '../core/database.dart';
import '../core/preferences.dart';
import '../core/l10n.dart';
import '../models/trip.dart';
import '../models/participant.dart';
import '../services/media_scanner.dart';
import '../services/place_clustering.dart';

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

  @override
  State<TripCreateScreen> createState() => _TripCreateScreenState();
}

class _TripCreateScreenState extends State<TripCreateScreen> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _descController = TextEditingController();
  final _passwordController = TextEditingController();
  
  bool _isSaving = false;
  bool _passwordProtect = false;
  bool _obscurePassword = true;

  // Historical trip settings
  bool _tripAlreadyFinished = false;
  DateTime _startDate = DateTime.now().subtract(const Duration(days: 7));
  TimeOfDay _startTime = const TimeOfDay(hour: 0, minute: 0);
  DateTime _endDate = DateTime.now().subtract(const Duration(days: 1));
  TimeOfDay _endTime = const TimeOfDay(hour: 23, minute: 59);

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

  Future<void> _selectStartDate() 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;
      });
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusManager.instance.primaryFocus?.unfocus();
    });
  }

  Future<void> _selectStartTime() async {
    FocusScope.of(context).unfocus();
    final picked = await showTimePicker(
      context: context,
      initialTime: _startTime,
    );
    if (picked != null) {
      setState(() {
        _startTime = picked;
      });
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusManager.instance.primaryFocus?.unfocus();
    });
  }

  Future<void> _selectEndDate() 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;
      });
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusManager.instance.primaryFocus?.unfocus();
    });
  }

  Future<void> _selectEndTime() async {
    FocusScope.of(context).unfocus();
    final picked = await showTimePicker(
      context: context,
      initialTime: _endTime,
    );
    if (picked != null) {
      setState(() {
        _endTime = picked;
      });
    }
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusManager.instance.primaryFocus?.unfocus();
    });
  }

  int _combineDateTime(DateTime date, TimeOfDay time) {
    return DateTime(date.year, date.month, date.day, time.hour, time.minute)
        .millisecondsSinceEpoch;
  }

  Future<void> _saveTrip({required bool startImmediately}) async {
    if (!_formKey.currentState!.validate()) return;

    if (_tripAlreadyFinished) {
      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;
      if (!mounted) return;
    }

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

    final now = DateTime.now().millisecondsSinceEpoch;
    final tripId = const Uuid().v4();
    
    TripStatus status;
    int? startTime;
    int? finishTime;

    if (_tripAlreadyFinished) {
      status = TripStatus.finished;
      startTime = _combineDateTime(_startDate, _startTime);
      finishTime = _combineDateTime(_endDate, _endTime);

      if (startTime >= finishTime) {
        setState(() {
          _isSaving = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(L10n.tripStartMustBeBeforeEnd),
            backgroundColor: Colors.red,
          ),
        );
        return;
      }
    } else {
      status = startImmediately ? TripStatus.active : TripStatus.planned;
      startTime = startImmediately ? now : null;
      finishTime = null;
    }

    final trip = Trip(
      id: tripId,
      name: _nameController.text.trim(),
      startTimeUtc: startTime,
      finishTimeUtc: finishTime,
      createdAtUtc: now,
      status: status,
      ownerParticipantId: AppPreferences.participantId,
      timezoneId: DateTime.now().timeZoneName,
      shareCode: null,
      coverPhotoId: null,
      password: _passwordProtect ? _passwordController.text : null,
    );

    await DatabaseHelper.instance.insertTrip(trip);

    // Create participant record for owner
    final p = Participant(
      id: AppPreferences.participantId,
      tripId: tripId,
      displayName: AppPreferences.displayName,
      deviceId: AppPreferences.deviceId,
      isOwner: true,
      joinedAtUtc: now,
    );
    await DatabaseHelper.instance.insertParticipant(p);

    // Automatic gallery scan for finished trip
    if (_tripAlreadyFinished) {
      try {
        await MediaScanner.scanPhotosForTrip(trip);
        await PlaceClusteringService.clusterTripPlaces(trip);
      } catch (e) {
        debugPrint('Chyba při automatickém skenování fotek: $e');
      }
    }

    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(_tripAlreadyFinished
              ? L10n.tripSavedAndPhotosLoaded
              : startImmediately
                  ? L10n.tripStarted
                  : L10n.tripSavedForLater),
        ),
      );
      Navigator.pop(context);
    }
  }

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

    final dateFormat = DateFormat('d. M. yyyy');

    return Scaffold(
      appBar: AppBar(
        title: Text(L10n.newTripTitle),
      ),
      body: SafeArea(
        child: _isSaving
            ? Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const CircularProgressIndicator(),
                    const SizedBox(height: 16),
                    Text(L10n.savingTripAndScanning),
                  ],
                ),
              )
            : SingleChildScrollView(
                padding: const EdgeInsets.all(24.0),
                child: Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        L10n.enterBasicInfo,
                        style: theme.textTheme.bodyLarge,
                      ),
                      const SizedBox(height: 24),
                      TextFormField(
                        controller: _nameController,
                        decoration: InputDecoration(
                          labelText: L10n.tripNameLabel,
                          hintText: L10n.tripNameHint,
                          border: const OutlineInputBorder(),
                          prefixIcon: const Icon(Icons.map_outlined),
                        ),
                        validator: (value) {
                          if (value == null || value.trim().isEmpty) {
                            return L10n.tripNameValidator;
                          }
                          return null;
                        },
                      ),
                      const SizedBox(height: 20),
                      TextFormField(
                        controller: _descController,
                        maxLines: 3,
                        decoration: InputDecoration(
                          labelText: L10n.descriptionLabel,
                          hintText: L10n.descriptionHint,
                          border: const OutlineInputBorder(),
                          alignLabelWithHint: true,
                          prefixIcon: const Padding(
                            padding: EdgeInsets.only(bottom: 40.0),
                            child: Icon(Icons.description_outlined),
                          ),
                        ),
                      ),
                      const SizedBox(height: 20),
                      Card(
                        elevation: 0,
                        color: theme.colorScheme.surfaceContainerHighest,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                          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(
                                  AppPreferences.language == 'cs'
                                      ? '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.colorScheme.primary
                                      : theme.colorScheme.onSurfaceVariant,
                                ),
                              ),
                              if (_passwordProtect)
                                Padding(
                                  padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
                                  child: TextFormField(
                                    controller: _passwordController,
                                    obscureText: _obscurePassword,
                                    validator: (val) {
                                      if (_passwordProtect && (val == null || val.isEmpty)) {
                                        return L10n.passwordEmptyValidator;
                                      }
                                      return null;
                                    },
                                    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(),
                                    ),
                                  ),
                                ),
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 24),

                      // Historical trip toggle card
                      Card(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                          side: BorderSide(
                            color: isDark ? Colors.white10 : Colors.black12,
                          ),
                        ),
                        child: Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          L10n.tripAlreadyFinished,
                                          style: theme.textTheme.titleMedium?.copyWith(
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        const SizedBox(height: 4),
                                        Text(
                                          L10n.tripAlreadyFinishedDesc,
                                          style: theme.textTheme.bodySmall,
                                        ),
                                      ],
                                    ),
                                  ),
                                  Switch(
                                    value: _tripAlreadyFinished,
                                    onChanged: (val) {
                                      setState(() {
                                        _tripAlreadyFinished = val;
                                      });
                                    },
                                  ),
                                ],
                              ),
                              if (_tripAlreadyFinished) ...[
                                const Divider(height: 20),
                                Text(
                                  L10n.departure,
                                  style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
                                ),
                                const SizedBox(height: 6),
                                Row(
                                  children: [
                                    Expanded(
                                      child: OutlinedButton.icon(
                                        onPressed: _selectStartDate,
                                        icon: const Icon(Icons.calendar_today, size: 16),
                                        label: Text(dateFormat.format(_startDate)),
                                      ),
                                    ),
                                    const SizedBox(width: 12),
                                    Expanded(
                                      child: OutlinedButton.icon(
                                        onPressed: _selectStartTime,
                                        icon: const Icon(Icons.access_time, size: 16),
                                        label: Text(_startTime.format(context)),
                                      ),
                                    ),
                                  ],
                                ),
                                const SizedBox(height: 12),
                                Text(
                                  L10n.arrival,
                                  style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
                                ),
                                const SizedBox(height: 6),
                                Row(
                                  children: [
                                    Expanded(
                                      child: OutlinedButton.icon(
                                        onPressed: _selectEndDate,
                                        icon: const Icon(Icons.calendar_today, size: 16),
                                        label: Text(dateFormat.format(_endDate)),
                                      ),
                                    ),
                                    const SizedBox(width: 12),
                                    Expanded(
                                      child: OutlinedButton.icon(
                                        onPressed: _selectEndTime,
                                        icon: const Icon(Icons.access_time, size: 16),
                                        label: Text(_endTime.format(context)),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ],
                          ),
                        ),
                      ),
                      const SizedBox(height: 32),

                      // Buttons
                      if (_tripAlreadyFinished)
                        SizedBox(
                          width: double.infinity,
                          child: ElevatedButton.icon(
                            onPressed: () => _saveTrip(startImmediately: false),
                            icon: const Icon(Icons.save),
                            label: Text(AppPreferences.language == 'cs' 
                                ? 'Uložit a načíst fotky' 
                                : 'Save and load photos'),
                          ),
                        )
                      else
                        Row(
                          children: [
                            Expanded(
                              child: OutlinedButton(
                                onPressed: () => _saveTrip(startImmediately: false),
                                child: Text(L10n.saveForLater),
                              ),
                            ),
                            const SizedBox(width: 16),
                            Expanded(
                              child: ElevatedButton(
                                onPressed: () => _saveTrip(startImmediately: true),
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Theme.of(context).colorScheme.primary,
                                ),
                                child: Text(AppPreferences.language == 'cs' 
                                    ? 'Zahájit ihned' 
                                    : 'Start now'),
                              ),
                            ),
                          ],
                        ),
                    ],
                  ),
                ),
              ),
      ),
    );
  }
}
