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

class OtpScreen extends ConsumerStatefulWidget {
  final String phone;
  const OtpScreen({super.key, required this.phone});

  @override
  ConsumerState<OtpScreen> createState() => _OtpScreenState();
}

class _OtpScreenState extends ConsumerState<OtpScreen> {
  final _otpController = TextEditingController();
  String? _otpRequestId;

  @override
  void initState() {
    super.initState();
    // Capture OTP request id from current state
    final data = ref.read(authProvider).valueOrNull;
    if (data is AuthOtpSentData) {
      _otpRequestId = data.otpRequestId;
    }
  }

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

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

    // Update OTP request id if state changes (e.g. resend)
    final data = authState.valueOrNull;
    if (data is AuthOtpSentData) {
      _otpRequestId = data.otpRequestId;
    }

    ref.listen(authProvider, (prev, next) {
      if (next is AsyncError) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(next.error.toString())));
      }
    });

    return Scaffold(
      appBar: AppBar(title: const Text('Masukkan OTP')),
      body: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text('Kode OTP telah dikirim ke ${widget.phone}'),
            const SizedBox(height: 24),
            TextField(
              controller: _otpController,
              decoration: const InputDecoration(
                labelText: 'Kode OTP',
                border: OutlineInputBorder(),
              ),
              keyboardType: TextInputType.number,
              maxLength: 6,
            ),
            const SizedBox(height: 12),
            ElevatedButton(
              onPressed: isLoading ? null : () {
                final otp = _otpController.text.trim();
                if (otp.length != 6 || _otpRequestId == null) return;
                ref.read(authProvider.notifier).verifyOtp(_otpRequestId!, otp);
              },
              child: isLoading
                  ? const CircularProgressIndicator()
                  : const Text('Verifikasi'),
            ),
          ],
        ),
      ),
    );
  }
}
