import '../../../l10n/app_localizations.dart';

import 'package:flutter/material.dart';
import 'package:kmobile/api/services/auth_service.dart';
import 'package:kmobile/api/services/payment_service.dart';
import 'package:kmobile/data/models/transfer.dart';
import 'package:kmobile/di/injection.dart';
import 'package:kmobile/features/fund_transfer/screens/payment_animation.dart';
import 'package:kmobile/features/fund_transfer/screens/tpin_prompt_screen.dart';
import 'package:kmobile/features/fund_transfer/screens/transaction_success_screen.dart';
import 'package:material_symbols_icons/material_symbols_icons.dart';

class TransactionPinScreen extends StatefulWidget {
  final Transfer transactionData;
  const TransactionPinScreen({super.key, required this.transactionData});

  @override
  State<TransactionPinScreen> createState() => _TransactionPinScreen();
}

class _TransactionPinScreen extends State<TransactionPinScreen> {
  final List<String> _pin = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _checkIfTpinIsSet();
  }

  Future<void> _checkIfTpinIsSet() async {
    setState(() => _loading = true);
    try {
      final authService = getIt<AuthService>();
      final isSet = await authService.checkTpin();
      if (!isSet && mounted) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (_) => const TpinSetupPromptScreen()),
        );
      } else if (mounted) {
        setState(() => _loading = false);
      }
    } catch (e) {
      if (mounted) {
        setState(() => _loading = false);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(AppLocalizations.of(context).tpinStatusFailed),
          ),
        );
      }
    }
  }

  void _onKeyPressed(String value) {
    setState(() {
      if (value == 'back') {
        if (_pin.isNotEmpty) _pin.removeLast();
      } else if (_pin.length < 6) {
        _pin.add(value);
      }
    });
  }

  Widget _buildPinIndicators() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: List.generate(6, (index) {
        return Container(
          margin: const EdgeInsets.symmetric(horizontal: 8),
          width: 20,
          height: 20,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(color: Colors.blue, width: 2),
            color: index < _pin.length ? Colors.blue : Colors.transparent,
          ),
        );
      }),
    );
  }

  Widget _buildKey(String label, {IconData? icon}) {
    return Expanded(
      child: InkWell(
        onTap: () async {
          if (label == 'back') {
            _onKeyPressed('back');
          } else if (label == 'done') {
            // Handle submit if needed
            if (_pin.length == 6) {
              await sendTransaction();
            } else {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(AppLocalizations.of(context).enter6DigitTpin),
                ),
              );
            }
          } else {
            _onKeyPressed(label);
          }
        },
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 20),
          child: Center(
            child: icon != null
                ? Icon(icon, size: 28)
                : Text(label, style: const TextStyle(fontSize: 24)),
          ),
        ),
      ),
    );
  }

  Widget _buildKeypad() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(children: [_buildKey('1'), _buildKey('2'), _buildKey('3')]),
        Row(children: [_buildKey('4'), _buildKey('5'), _buildKey('6')]),
        Row(children: [_buildKey('7'), _buildKey('8'), _buildKey('9')]),
        Row(
          children: [
            _buildKey('done', icon: Icons.check),
            _buildKey('0'),
            _buildKey('back', icon: Icons.backspace_outlined),
          ],
        ),
      ],
    );
  }

  Future<void> sendTransaction() async {
    final paymentService = getIt<PaymentService>();
    final transfer = widget.transactionData;
    transfer.tpin = _pin.join();
    try {
      final paymentResponse = paymentService.processQuickPayWithinBank(
        transfer,
      );

      Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (_) =>
              PaymentAnimationScreen(paymentResponse: paymentResponse),
        ),
      );
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text(e.toString())));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Symbols.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        title: Text(
          AppLocalizations.of(context).tpin,
          style: TextStyle(color: Colors.black, fontWeight: FontWeight.w500),
        ),
        centerTitle: false,
      ),
      body: Padding(
        padding: const EdgeInsets.only(bottom: 20.0),
        child: Column(
          children: [
            const Spacer(),
            Text(
              AppLocalizations.of(context).enterTpin,
              style: TextStyle(fontSize: 18),
            ),
            const SizedBox(height: 20),
            _buildPinIndicators(),
            const Spacer(),
            _buildKeypad(),
          ],
        ),
      ),
    );
  }
}
