import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/auth/auth_notifier.dart';
import '../../../core/auth/social_auth_enabled.dart';

/// Shown when anonymity is disabled by admin.
/// User must identify themselves (phone OTP / Google / Apple).
/// Backend upgrades the existing anonymous customer row when the current
/// anonymous_customer_id is passed on sign-in (see AuthNotifier).
class ForceRegisterScreen extends ConsumerStatefulWidget {
  const ForceRegisterScreen({super.key});

  @override
  ConsumerState<ForceRegisterScreen> createState() => _ForceRegisterScreenState();
}

class _ForceRegisterScreenState extends ConsumerState<ForceRegisterScreen> {
  final _phoneController = TextEditingController();

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

  @override
  Widget build(BuildContext context) {
    final authState = ref.watch(authProvider);
    final isLoading = authState is AsyncLoading;

    ref.listen(authProvider, (prev, next) {
      final data = next.valueOrNull;
      if (data is AuthOtpSentData) {
        context.push('/auth/otp', extra: _phoneController.text.trim());
      }
      if (next is AsyncError) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(next.error.toString())));
      }
    });

    return Scaffold(
      appBar: AppBar(title: const Text('Verifikasi Akun')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text(
              'Untuk melanjutkan, kamu perlu mendaftarkan akun.',
              style: TextStyle(fontSize: 16),
            ),
            const SizedBox(height: 24),
            if (kSocialAuthEnabled) ...[
              ElevatedButton.icon(
                icon: const Icon(Icons.g_mobiledata),
                onPressed: isLoading ? null
                    : () => ref.read(authProvider.notifier).loginGoogle(),
                label: const Text('Lanjut dengan Google'),
              ),
              const SizedBox(height: 12),
              ElevatedButton.icon(
                icon: const Icon(Icons.apple),
                onPressed: isLoading ? null
                    : () => ref.read(authProvider.notifier).loginApple(),
                label: const Text('Lanjut dengan Apple'),
              ),
              const Padding(
                padding: EdgeInsets.symmetric(vertical: 24),
                child: Row(children: [
                  Expanded(child: Divider()),
                  Padding(padding: EdgeInsets.symmetric(horizontal: 12), child: Text('atau')),
                  Expanded(child: Divider()),
                ]),
              ),
            ],
            TextField(
              controller: _phoneController,
              decoration: const InputDecoration(
                labelText: 'Nomor HP',
                hintText: '+628xxxxxxxxxx',
                border: OutlineInputBorder(),
              ),
              keyboardType: TextInputType.phone,
            ),
            const SizedBox(height: 12),
            ElevatedButton(
              onPressed: isLoading ? null : () {
                final phone = _phoneController.text.trim();
                if (phone.isEmpty) return;
                ref.read(authProvider.notifier).requestOtp(phone);
              },
              child: isLoading
                  ? const CircularProgressIndicator()
                  : const Text('Kirim OTP'),
            ),
          ],
        ),
      ),
    );
  }
}
