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

/// 鉴权方式枚举。
enum AuthMode { none, code, password }

/// 连接鉴权对话框：选择免密 / 动态验证码 / 固定密码。
///
/// 返回 [AuthSelection]；取消返回 null。
Future<AuthSelection?> showAuthDialog(BuildContext context) {
  return showCupertinoDialog<AuthSelection>(
    context: context,
    builder: (ctx) => const AuthDialog(),
  );
}

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

  @override
  State<AuthDialog> createState() => _AuthDialogState();
}

class _AuthDialogState extends State<AuthDialog> {
  AuthMode _selected = AuthMode.none;
  final _valueController = TextEditingController();

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

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);

    Widget buildOption(
      AuthMode mode,
      String title,
      String desc,
    ) {
      final selected = _selected == mode;
      return GestureDetector(
        onTap: () => setState(() => _selected = mode),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
          margin: const EdgeInsets.only(bottom: 8),
          decoration: BoxDecoration(
            border: Border.all(
              color: selected
                  ? CupertinoColors.activeBlue
                  : CupertinoColors.systemGrey4,
            ),
            borderRadius: BorderRadius.circular(10),
            color: selected
                ? CupertinoColors.activeBlue.withValues(alpha: 0.06)
                : null,
          ),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      title,
                      style: const TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      desc,
                      style: const TextStyle(
                        fontSize: 12,
                        color: CupertinoColors.systemGrey,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 8),
              Icon(
                selected
                    ? CupertinoIcons.check_mark_circled_solid
                    : CupertinoIcons.circle,
                color: selected
                    ? CupertinoColors.activeBlue
                    : CupertinoColors.systemGrey,
              ),
            ],
          ),
        ),
      );
    }

    return CupertinoAlertDialog(
      title: Text(l10n.authTitle),
      content: Column(
        children: [
          const SizedBox(height: 12),
          buildOption(
            AuthMode.none,
            l10n.authNone,
            l10n.authNoneDesc,
          ),
          buildOption(
            AuthMode.code,
            l10n.authCode,
            l10n.authCodeDesc,
          ),
          buildOption(
            AuthMode.password,
            l10n.authPassword,
            l10n.authPasswordDesc,
          ),
          const SizedBox(height: 4),
          CupertinoTextField(
            controller: _valueController,
            enabled: _selected != AuthMode.none,
            placeholder: switch (_selected) {
              AuthMode.none => l10n.authNonePlaceholder,
              AuthMode.password => l10n.authPasswordPlaceholder,
              AuthMode.code => l10n.authCodePlaceholder,
            },
            obscureText: true,
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
          ),
        ],
      ),
      actions: [
        CupertinoDialogAction(
          child: Text(l10n.cancel),
          onPressed: () => Navigator.of(context).pop(),
        ),
        CupertinoDialogAction(
          child: Text(l10n.connect),
          onPressed: () {
            final val = _valueController.text.trim();
            if (_selected != AuthMode.none && val.isEmpty) {
              _showAlert(context, l10n.authValueRequired);
              return;
            }
            Navigator.of(context).pop(
              AuthSelection(
                mode: _selected,
                value: _selected == AuthMode.none ? '' : val,
              ),
            );
          },
        ),
      ],
    );
  }

  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(),
          ),
        ],
      ),
    );
  }
}

/// 鉴权选择结果。
class AuthSelection {
  final AuthMode mode;
  final String value;
  const AuthSelection({required this.mode, required this.value});

  String get type => switch (mode) {
        AuthMode.none => 'NONE',
        AuthMode.code => 'CODE',
        AuthMode.password => 'PASSWORD',
      };
}
