import 'package:flutter/material.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/features/profile/tpin/change_tpin_otp_screen.dart';
import 'package:kmobile/widgets/pin_input_field.dart';
import '../../../api/services/change_password_service.dart';

class ChangeTpinScreen extends StatefulWidget {
  final String mobileNumber;
  const ChangeTpinScreen({super.key, required this.mobileNumber});

  @override
  State<ChangeTpinScreen> createState() => _ChangeTpinScreenState();
}

class _ChangeTpinScreenState extends State<ChangeTpinScreen> {
  final _formKey = GlobalKey<FormState>();
  final _oldTpinController = TextEditingController();
  final _newTpinController = TextEditingController();
  final _confirmTpinController = TextEditingController();
  final ChangePasswordService _changePasswordService =
      getIt<ChangePasswordService>();
  bool _isLoading = false;

  @override
  void dispose() {
    _oldTpinController.dispose();
    _newTpinController.dispose();
    _confirmTpinController.dispose();
    super.dispose();
  }

  void _handleChangeTpin() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
      });
      try {
        // 1. Get OTP for TPIN change.
        await _changePasswordService.getOtpTpin(
            mobileNumber: widget.mobileNumber);

        // 2. Navigate to the OTP screen on success.
        if (mounted) {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => ChangeTpinOtpScreen(
                oldTpin: _oldTpinController.text,
                newTpin: _newTpinController.text,
                mobileNumber: widget.mobileNumber,
              ),
            ),
          );
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Failed to send OTP: $e')),
          );
        }
      } finally {
        if (mounted) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Change TPIN'),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('Current TPIN'),
              const SizedBox(height: 8),
              PinInputField(
                controller: _oldTpinController,
                validator: (value) {
                  if (value == null || value.length != 6) {
                    return 'Please enter your 6-digit old TPIN';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 24),
              const Text('New TPIN'),
              const SizedBox(height: 8),
              PinInputField(
                controller: _newTpinController,
                validator: (value) {
                  if (value == null || value.length != 6) {
                    return 'Please enter a 6-digit new TPIN';
                  }
                  if (value == _oldTpinController.text) {
                    return 'New TPIN must be different from the old one.';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 24),
              const Text('Confirm New TPIN'),
              const SizedBox(height: 8),
              PinInputField(
                controller: _confirmTpinController,
                validator: (value) {
                  if (value == null || value.length != 6) {
                    return 'Please confirm your new TPIN';
                  }
                  if (value != _newTpinController.text) {
                    return 'TPINs do not match';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 32),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _isLoading ? null : _handleChangeTpin,
                  child: _isLoading
                      ? const SizedBox(
                          height: 24,
                          width: 24,
                          child: CircularProgressIndicator(
                            color: Colors.white,
                            strokeWidth: 2.5,
                          ),
                        )
                      : const Text('Proceed'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
