import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../admin/data/admin_repository.dart';
import '../../admin/domain/receipt_alias.dart';
import '../../auth/data/auth_providers.dart';

class UserAliasesScreen extends ConsumerStatefulWidget {
  const UserAliasesScreen({super.key});

  @override
  ConsumerState<UserAliasesScreen> createState() => _UserAliasesScreenState();
}

class _UserAliasesScreenState extends ConsumerState<UserAliasesScreen> {
  List<ReceiptAlias> _aliases = [];
  bool _isLoading = true;
  String? _error;

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

  Future<void> _load() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });
    try {
      final aliases = await ref.read(adminRepositoryProvider).listReceiptAliases();
      if (!mounted) return;
      setState(() {
        _aliases = aliases;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() => _error = 'Kunde inte ladda alias: $e');
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  Future<void> _delete(ReceiptAlias alias) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Ta bort alias'),
        content: Text('Ta bort alias "${alias.receiptName}" → ${alias.displayProductName}?'),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Avbryt')),
          FilledButton(
            onPressed: () => Navigator.pop(ctx, true),
            child: const Text('Ta bort'),
          ),
        ],
      ),
    );
    if (confirmed != true || !mounted) return;
    try {
      await ref.read(adminRepositoryProvider).removeReceiptAlias(alias.id);
      await _load();
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Alias borttaget.')),
        );
      }
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Kunde inte ta bort alias: $e')),
      );
    }
  }

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

    return Scaffold(
      appBar: AppBar(
        title: const Text('Mina kvittoalias'),
        actions: [
          IconButton(
            onPressed: _load,
            icon: const Icon(Icons.refresh),
            tooltip: 'Uppdatera',
          ),
        ],
      ),
      body: Builder(builder: (_) {
        if (_isLoading) return const Center(child: CircularProgressIndicator());
        if (_error != null) {
          return Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(_error!, style: TextStyle(color: theme.colorScheme.error)),
                const SizedBox(height: 12),
                FilledButton(onPressed: _load, child: const Text('Försök igen')),
              ],
            ),
          );
        }
        if (_aliases.isEmpty) {
          return Center(
            child: Padding(
              padding: const EdgeInsets.all(32),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.link_off_outlined, size: 48, color: theme.colorScheme.outlineVariant),
                  const SizedBox(height: 16),
                  Text(
                    'Inga alias sparade ännu.',
                    style: theme.textTheme.bodyLarge,
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'Alias skapas automatiskt när du sparar kvittorader i inventariet.',
                    style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.onSurfaceVariant),
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          );
        }
        return ListView.separated(
          padding: const EdgeInsets.all(16),
          itemCount: _aliases.length,
          separatorBuilder: (_, __) => const Divider(height: 1),
          itemBuilder: (ctx, i) {
            final alias = _aliases[i];
            return ListTile(
              leading: Icon(
                Icons.link_outlined,
                color: theme.colorScheme.primary,
              ),
              title: Text(
                alias.receiptName,
                style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w500),
              ),
              subtitle: Text(
                '→ ${alias.displayProductName}',
                style: theme.textTheme.bodySmall,
              ),
              trailing: IconButton(
                icon: const Icon(Icons.delete_outline),
                tooltip: 'Ta bort alias',
                color: theme.colorScheme.error,
                onPressed: () => _delete(alias),
              ),
            );
          },
        );
      }),
    );
  }
}
