import 'package:flutter/cupertino.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:webrtc_controller_flutter/l10n/app_localizations.dart';

import '../auth_controller.dart';

/// 登录对话框：输入用户名/密码，调用登录保存令牌。
class LoginDialog extends ConsumerStatefulWidget {
  const LoginDialog({super.key});

  @override
  ConsumerState<LoginDialog> createState() => _LoginDialogState();
}

class _LoginDialogState extends ConsumerState<LoginDialog> {
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();

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

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);
    return CupertinoAlertDialog(
      title: Text(l10n.login),
      content: Padding(
        padding: const EdgeInsets.only(top: 12),
        child: Column(
          children: [
            CupertinoTextField(
              controller: _usernameController,
              placeholder: l10n.username,
              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 12),
            ),
            const SizedBox(height: 10),
            CupertinoTextField(
              controller: _passwordController,
              placeholder: l10n.password,
              obscureText: true,
              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 12),
            ),
          ],
        ),
      ),
      actions: [
        CupertinoDialogAction(
          child: Text(l10n.cancel),
          onPressed: () => Navigator.of(context).pop(false),
        ),
        CupertinoDialogAction(
          child: Text(l10n.login),
          onPressed: () async {
            final user = _usernameController.text.trim();
            final pass = _passwordController.text.trim();
            if (user.isEmpty || pass.isEmpty) {
              _showAlert(context, l10n.usernamePasswordRequired);
              return;
            }
            final ok = await ref
                .read(authControllerProvider.notifier)
                .login(user, pass);
            if (!context.mounted) return;
            if (ok) {
              Navigator.of(context).pop(true);
            } else {
              final error = ref.read(authControllerProvider).valueOrNull?.error;
              debugPrint('login error: $error');
              _showAlert(
                context,
                l10n.loginFailed(error ?? ''),
              );
            }
          },
        ),
      ],
    );
  }

  static void _showAlert(BuildContext context, String message) {
    showCupertinoDialog<void>(
      context: context,
      builder: (ctx) => CupertinoAlertDialog(
        content: Text(message),
        actions: [
          CupertinoDialogAction(
            child: const Text('确定'),
            onPressed: () => Navigator.of(ctx).pop(),
          ),
        ],
      ),
    );
  }
}
