import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

import 'package:doormile/main.dart';
import 'package:doormile/shared/state/app_state.dart';
import 'package:doormile/core/utils/snackbar_utils.dart';
import 'package:doormile/core/theme/app_colors.dart';
import 'package:doormile/core/theme/app_theme.dart';
import 'package:doormile/core/widgets/common.dart';

enum PinMode { enter, set, reset }

class PinScreen extends StatefulWidget {
  final PinMode mode;
  const PinScreen({super.key, required this.mode});

  @override
  State<PinScreen> createState() => _PinScreenState();
}

class _PinScreenState extends State<PinScreen> {
  final _controllers = List.generate(4, (_) => TextEditingController());
  final _nodes = List.generate(4, (_) => FocusNode());
  String _code = '';
  bool _loading = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) _nodes[0].requestFocus();
    });
  }

  void _onBackspaceOnEmpty(int i) {
    if (i > 0) {
      _controllers[i - 1].clear();
      _nodes[i - 1].requestFocus();
      _updateCode();
    }
  }

  void _onChanged(int i, String v) {
    if (v.length > 1) {
      final chars = v.replaceAll(RegExp(r'[^0-9]'), '').split('');
      for (int j = 0; j < 4; j++) {
        _controllers[j].text = j < chars.length ? chars[j] : '';
      }
      _nodes[3].requestFocus();
      _updateCode();
      if (_code.length == 4) _submit();
      return;
    }
    if (v.isNotEmpty && i < 3) _nodes[i + 1].requestFocus();
    _updateCode();
    if (_code.length == 4) _submit();
  }

  void _updateCode() {
    setState(() {
      _code = _controllers.map((c) => c.text).join();
    });
  }

  void _submit() async {
    FocusScope.of(context).unfocus();
    setState(() => _loading = true);
    final state = context.read<AppState>();
    
    try {
      if (widget.mode == PinMode.set) {
        await state.registerWithPin(_code);
      } else if (widget.mode == PinMode.reset) {
        await state.resetPinWithBackend(_code);
      } else {
        await state.verifyPinWithBackend(_code);
      }
      
      if (!mounted) return;
      Navigator.pushNamedAndRemoveUntil(context, Routes.home, (r) => false);
    } catch (e) {
      if (!mounted) return;
      setState(() => _loading = false);
      SnackbarUtils.showError(context, e.toString());
      for (var c in _controllers) c.clear();
      _nodes[0].requestFocus();
      _updateCode();
    }
  }

  void _forgotPin() async {
    setState(() => _loading = true);
    await context.read<AppState>().sendOtp(
      context.read<AppState>().phone,
      resetPin: true,
      onSuccess: () {
        if (!mounted) return;
        setState(() => _loading = false);
        Navigator.pushNamed(context, Routes.otp);
      },
      onError: (err) {
        if (!mounted) return;
        setState(() => _loading = false);
        SnackbarUtils.showError(context, err);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    String title = 'Enter PIN';
    String subtitle = 'Enter your 4-digit security PIN to log in.';
    if (widget.mode == PinMode.set) {
      title = 'Set PIN';
      subtitle = 'Create a 4-digit security PIN for your account.';
    } else if (widget.mode == PinMode.reset) {
      title = 'Set New PIN';
      subtitle = 'Create a new 4-digit security PIN.';
    }

    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topRight,
            end: Alignment.bottomLeft,
            colors: [
              AppColors.tertiary.withValues(alpha: 0.05),
              Colors.white,
              AppColors.primary.withValues(alpha: 0.05),
            ],
          ),
        ),
        child: Stack(
          children: [
            SafeArea(
            child: SingleChildScrollView(
              padding: const EdgeInsets.symmetric(horizontal: 24),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  SizedBox(height: MediaQuery.of(context).size.height * 0.12),
                  Container(
                    width: 100,
                    height: 100,
                    decoration: BoxDecoration(
                      color: AppColors.primary.withValues(alpha: 0.1),
                      shape: BoxShape.circle,
                    ),
                    child: const Icon(Icons.lock_outline, size: 48, color: AppColors.primary),
                  ),
                  const SizedBox(height: 32),
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 32,
                      fontWeight: FontWeight.bold,
                      color: AppColors.primary,
                      fontFamily: AppTheme.fontFamily,
                    ),
                  ),
                  const SizedBox(height: 12),
                  Text(
                    subtitle,
                    textAlign: TextAlign.center,
                    style: const TextStyle(
                      fontSize: 18,
                      color: Colors.black54,
                      fontFamily: AppTheme.fontFamily,
                    ),
                  ),
                  const SizedBox(height: 48),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: List.generate(
                      4,
                      (i) => _PinBox(
                        controller: _controllers[i],
                        node: _nodes[i],
                        onChanged: (v) => _onChanged(i, v),
                        onBackspaceOnEmpty: () => _onBackspaceOnEmpty(i),
                      ),
                    ),
                  ),
                  const SizedBox(height: 24),
                  if (widget.mode == PinMode.enter)
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const SizedBox(), // Empty space for left side
                        InkWell(
                          onTap: _forgotPin,
                          child: const Text(
                            "Forget Pin?",
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: AppColors.primary,
                              fontFamily: AppTheme.fontFamily,
                              decoration: TextDecoration.underline,
                            ),
                          ),
                        ),
                      ],
                    ),
                  if (_loading) ...[
                    const SizedBox(height: 32),
                    const CircularProgressIndicator(color: AppColors.primary),
                  ],
                ],
              ),
            ),
          ),
          
          // Back Button
          Positioned(
            top: MediaQuery.of(context).padding.top + 16,
            left: 16,
            child: InkWell(
              onTap: () => Navigator.pop(context),
              borderRadius: BorderRadius.circular(30),
              child: Container(
                padding: const EdgeInsets.all(10),
                decoration: const BoxDecoration(
                  color: Colors.black12,
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.arrow_back,
                  color: Colors.black,
                  size: 24,
                ),
              ),
            ),
          ),
        ],
      ),
      ),
    );
  }
}

class _PinBox extends StatelessWidget {
  final TextEditingController controller;
  final FocusNode node;
  final ValueChanged<String> onChanged;
  final VoidCallback onBackspaceOnEmpty;

  const _PinBox({
    required this.controller,
    required this.node,
    required this.onChanged,
    required this.onBackspaceOnEmpty,
  });

  @override
  Widget build(BuildContext context) {
    final filled = controller.text.isNotEmpty;
    
    return Container(
      width: 58,
      height: 64,
      decoration: BoxDecoration(
        color: filled ? AppColors.primary : Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: filled ? AppColors.primary.withValues(alpha: 0.3) : Colors.black.withValues(alpha: 0.04),
            blurRadius: filled ? 12 : 20,
            offset: const Offset(0, 8),
          ),
        ],
        border: Border.all(
          color: filled ? AppColors.primary : Colors.grey.shade200,
          width: 1.5,
        ),
      ),
      child: RawKeyboardListener(
        focusNode: FocusNode(),
        onKey: (event) {
          if (event is RawKeyDownEvent &&
              event.logicalKey == LogicalKeyboardKey.backspace &&
              controller.text.isEmpty) {
            onBackspaceOnEmpty();
          }
        },
        child: TextField(
          controller: controller,
          focusNode: node,
          onChanged: onChanged,
          textAlign: TextAlign.center,
          textAlignVertical: TextAlignVertical.center,
          obscureText: true,
          obscuringCharacter: '●',
          keyboardType: TextInputType.number,
          maxLength: 1,
          style: TextStyle(
            fontSize: 28,
            fontWeight: FontWeight.bold,
            color: filled ? Colors.white : AppColors.primary,
          ),
          decoration: const InputDecoration(
            counterText: "",
            contentPadding: EdgeInsets.zero,
            border: InputBorder.none,
            enabledBorder: InputBorder.none,
            focusedBorder: InputBorder.none,
            filled: false,
          ),
        ),
      ),
    );
  }
}
