import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../core/database.dart';
import '../core/preferences.dart';
import '../models/trip.dart';
import '../models/participant.dart';
import '../services/sharing_service.dart';

class HostInvitationScreen extends StatefulWidget {
  final Trip trip;

  const HostInvitationScreen({super.key, required this.trip});

  @override
  State<HostInvitationScreen> createState() => _HostInvitationScreenState();
}

class _HostInvitationScreenState extends State<HostInvitationScreen> {
  String? _localIp;
  int? _serverPort;
  String? _qrUrl;
  bool _isLoading = true;
  String? _errorMessage;
  List<Participant> _joinedParticipants = [];

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

  Future<void> _setupServer() async {
    final isCs = AppPreferences.language == 'cs';
    try {
      final ip = await SharingService.instance.getLocalIpAddress();
      if (ip == null) {
        throw Exception(isCs
            ? 'Nepodařilo se zjistit lokální IP adresu. Zkontrolujte, zda jste připojeni k Wi-Fi síti.'
            : 'Failed to retrieve local IP address. Please check your Wi-Fi connection.');
      }

      // Start the server
      final port = await SharingService.instance.startServer(widget.trip.id);

      // Load existing participants
      final db = DatabaseHelper.instance;
      final participants = await db.getParticipantsForTrip(widget.trip.id);

      // Register join callback
      SharingService.instance.onParticipantJoined = (participant) {
        if (mounted) {
          setState(() {
            _joinedParticipants.add(participant);
          });
        }
      };

      final encodedTripName = Uri.encodeComponent(widget.trip.name);
      final encodedOwnerName = Uri.encodeComponent(AppPreferences.displayName);
      final qrUrl = 'lvm://join?host=$ip&port=$port&tripId=${widget.trip.id}&tripName=$encodedTripName&ownerName=$encodedOwnerName&ownerId=${AppPreferences.participantId}';

      setState(() {
        _localIp = ip;
        _serverPort = port;
        _qrUrl = qrUrl;
        // Filter out host (self) from the list of joined participants for display
        _joinedParticipants = participants.where((p) => p.id != AppPreferences.participantId).toList();
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _errorMessage = e.toString();
        _isLoading = false;
      });
    }
  }

  @override
  void dispose() {
    // Stop server and clean callback
    SharingService.instance.onParticipantJoined = null;
    SharingService.instance.stopServer();
    super.dispose();
  }

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

    return Scaffold(
      appBar: AppBar(
        title: Text(isCs ? 'Sdílet a připojit nablízko' : 'Share and Connect Nearby'),
      ),
      body: SafeArea(
        child: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : _errorMessage != null
                ? _buildErrorState(theme)
                : SingleChildScrollView(
                    padding: const EdgeInsets.all(24.0),
                    child: Column(
                      children: [
                        // Status Card
                        Container(
                          width: double.infinity,
                          padding: const EdgeInsets.all(16),
                          decoration: BoxDecoration(
                            color: theme.colorScheme.primary.withValues(alpha: 0.05),
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(
                              color: theme.colorScheme.primary.withValues(alpha: 0.15),
                            ),
                          ),
                          child: Column(
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  const Icon(Icons.wifi, color: Colors.green),
                                  const SizedBox(width: 8),
                                  Text(
                                    isCs ? 'Server spuštěn na Wi-Fi' : 'Server started on Wi-Fi',
                                    style: theme.textTheme.titleMedium?.copyWith(
                                      fontWeight: FontWeight.bold,
                                      color: Colors.green,
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 6),
                              Text(
                                '${isCs ? "IP adresa" : "IP Address"}: $_localIp:$_serverPort',
                                style: theme.textTheme.bodyMedium?.copyWith(
                                  fontFamily: 'monospace',
                                  fontSize: 12,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 24),

                        // QR Code
                        if (_qrUrl != null)
                          Card(
                            color: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(16),
                            ),
                            elevation: 4,
                            child: Padding(
                              padding: const EdgeInsets.all(16.0),
                              child: QrImageView(
                                data: _qrUrl!,
                                version: QrVersions.auto,
                                size: 230.0,
                                gapless: false,
                              ),
                            ),
                          ),
                        const SizedBox(height: 16),
                        Text(
                          isCs
                              ? 'Ukažte tento QR kód ostatním účastníkům cesty, aby ho naskenovali ve své aplikaci.'
                              : 'Show this QR code to other trip participants to scan it in their app.',
                          textAlign: TextAlign.center,
                          style: const TextStyle(color: Colors.grey, fontSize: 13),
                        ),
                        const SizedBox(height: 32),

                        // Joined participants header
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '${isCs ? "Připojení účastníci" : "Connected participants"} (${_joinedParticipants.length})',
                              style: theme.textTheme.titleMedium?.copyWith(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            if (_joinedParticipants.isNotEmpty)
                              const Icon(Icons.check_circle, color: Colors.green, size: 20),
                          ],
                        ),
                        const SizedBox(height: 12),
                        const Divider(),

                        // Joined participants list
                        if (_joinedParticipants.isEmpty)
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 24.0),
                            child: Text(
                              isCs ? 'Čekám na připojení prvního účastníka...' : 'Waiting for the first participant to connect...',
                              style: TextStyle(color: theme.hintColor, fontStyle: FontStyle.italic),
                            ),
                          )
                        else
                          ListView.builder(
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            itemCount: _joinedParticipants.length,
                            itemBuilder: (context, index) {
                              final p = _joinedParticipants[index];
                              return Card(
                                margin: const EdgeInsets.only(bottom: 8),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8),
                                  side: BorderSide(
                                    color: isDark ? Colors.white10 : Colors.black12,
                                  ),
                                ),
                                child: ListTile(
                                  leading: const CircleAvatar(
                                    child: Icon(Icons.person),
                                  ),
                                  title: Text(
                                    p.displayName,
                                    style: const TextStyle(fontWeight: FontWeight.w600),
                                  ),
                                  subtitle: Text(
                                    '${isCs ? "Zařízení" : "Device"}: ${p.deviceId.substring(0, 8)}...',
                                    style: const TextStyle(fontSize: 12),
                                  ),
                                  trailing: const Icon(Icons.done, color: Colors.green),
                                ),
                              );
                            },
                          ),
                      ],
                    ),
                  ),
      ),
    );
  }

  Widget _buildErrorState(ThemeData theme) {
    final isCs = AppPreferences.language == 'cs';
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 64, color: Colors.red),
            const SizedBox(height: 16),
            Text(
              isCs ? 'Nepodařilo se spustit server' : 'Failed to start server',
              style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 12),
            Text(
              _errorMessage ?? (isCs ? 'Neznámá chyba' : 'Unknown error'),
              textAlign: TextAlign.center,
              style: const TextStyle(color: Colors.grey),
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: () {
                setState(() {
                  _isLoading = true;
                  _errorMessage = null;
                });
                _setupServer();
              },
              child: Text(isCs ? 'Zkusit znovu' : 'Try Again'),
            ),
          ],
        ),
      ),
    );
  }
}
