import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart' as permission;
// Material colors only
// Glass 제거: Material 3 Card 사용
import '../routes/app_routes.dart';
import '../l10n/app_localizations.dart';
import '../services/sms_service.dart';
import '../utils/platform_helper.dart';

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

  @override
  State<SmsPermissionScreen> createState() => _SmsPermissionScreenState();
}

class _SmsPermissionScreenState extends State<SmsPermissionScreen> {
  bool _requesting = false;

  Future<void> _handleRequest() async {
    if (_requesting) return;
    setState(() => _requesting = true);

    try {
      if (!PlatformHelper.isAndroid) {
        // iOS/Web은 권한 흐름 없이 메인으로 이동
        if (mounted) {
          Navigator.of(context).pushReplacementNamed(AppRoutes.main);
        }
        return;
      }

      final status = await permission.Permission.sms.status;
      if (status.isGranted) {
        if (mounted) {
          Navigator.of(context).pushReplacementNamed(AppRoutes.main);
        }
        return;
      }

      // 권한 요청
      final granted = await SMSService.requestSMSPermission();
      if (mounted) {
        if (granted) {
          Navigator.of(context).pushReplacementNamed(AppRoutes.main);
        } else {
          final newStatus = await permission.Permission.sms.status;
          if (newStatus.isPermanentlyDenied) {
            // 설정 열기 유도
            _showSettingsDialog();
          }
          // 거부지만 영구 거부가 아니라면 그대로 대기 (사용자가 다시 시도 가능)
        }
      }
    } finally {
      if (mounted) setState(() => _requesting = false);
    }
  }

  void _showSettingsDialog() {
    final loc = AppLocalizations.of(context);
    showDialog(
      context: context,
      builder: (_) => AlertDialog(
        title: Text(loc.smsPermissionRequired),
        content: Text(loc.permanentlyDeniedMessage),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(AppLocalizations.of(context).cancel),
          ),
          TextButton(
            onPressed: () async {
              await permission.openAppSettings();
              if (mounted) Navigator.of(context).pop();
            },
            child: Text(loc.openSettings),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final loc = AppLocalizations.of(context);
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.sms,
                    size: 64, color: Theme.of(context).colorScheme.primary),
                const SizedBox(height: 16),
                Text(
                  loc.smsPermissionTitle,
                  style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                        color: Theme.of(context).colorScheme.onSurface,
                        fontWeight: FontWeight.bold,
                      ),
                ),
                const SizedBox(height: 8),
                Text(
                  loc.smsPermissionRequired,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      color: Theme.of(context).colorScheme.onSurfaceVariant),
                ),
                const SizedBox(height: 16),
                Card(
                  elevation: 1,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                    side: BorderSide(
                      color: Theme.of(context)
                          .colorScheme
                          .outline
                          .withValues(alpha: 0.5),
                    ),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(loc.smsPermissionReasonTitle,
                            style:
                                const TextStyle(fontWeight: FontWeight.bold)),
                        const SizedBox(height: 8),
                        Text(loc.smsPermissionReasonBody),
                        const SizedBox(height: 12),
                        Text(loc.smsPermissionScopeTitle,
                            style:
                                const TextStyle(fontWeight: FontWeight.bold)),
                        const SizedBox(height: 8),
                        Text(loc.smsPermissionScopeBody),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 24),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton.icon(
                    onPressed: _requesting ? null : _handleRequest,
                    icon: const Icon(Icons.lock_open),
                    label: Text(
                        _requesting ? loc.requesting : loc.requestPermission),
                  ),
                ),
                const SizedBox(height: 8),
                TextButton(
                  onPressed: () => Navigator.of(context)
                      .pushReplacementNamed(AppRoutes.main),
                  child: Text(loc.later),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}
