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';
import 'package:doormile/core/widgets/logo.dart';

class SignupScreen extends StatefulWidget {
  const SignupScreen({super.key});

  @override
  State<SignupScreen> createState() => _SignupScreenState();
}

class _SignupScreenState extends State<SignupScreen> {
  final _name = TextEditingController();
  final _email = TextEditingController();
  final _phone = TextEditingController();
  bool _loading = false;

  bool get _valid =>
      _name.text.trim().isNotEmpty &&
      _email.text.trim().isNotEmpty &&
      _phone.text.replaceAll(' ', '').length == 10;

  void _sendOtp() async {
    if (!_valid) return;
    FocusScope.of(context).unfocus();
    setState(() => _loading = true);
    
    await context.read<AppState>().sendOtp(
      _phone.text,
      firstName: _name.text.trim(),
      email: _email.text.trim(),
      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
  void dispose() {
    _name.dispose();
    _email.dispose();
    _phone.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.surface,
      appBar: AppBar(
        leading: BackButton(color: AppColors.primary, onPressed: () => Navigator.pop(context)),
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.symmetric(horizontal: 24),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const DoormileMark(size: 64),
                    const SizedBox(height: 32),
                    Text('Create Account', style: AppTheme.headlineLg),
                    const SizedBox(height: 6),
                    Text('Join Doormile for eco-friendly deliveries',
                        style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant)),
                    const SizedBox(height: 40),
                    
                    // Name Field
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.only(left: 4, bottom: 6),
                        child: Text('Full Name',
                            style: AppTheme.labelMd
                                .copyWith(color: AppColors.onSurfaceVariant)),
                      ),
                    ),
                    _CustomTextField(
                      controller: _name,
                      hint: 'e.g. Rahul Sharma',
                      icon: Icons.person_outline,
                      onChanged: () => setState(() {}),
                    ),
                    const SizedBox(height: 20),

                    // Email Field
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.only(left: 4, bottom: 6),
                        child: Text('Email Address',
                            style: AppTheme.labelMd
                                .copyWith(color: AppColors.onSurfaceVariant)),
                      ),
                    ),
                    _CustomTextField(
                      controller: _email,
                      hint: 'e.g. rahul@example.com',
                      icon: Icons.email_outlined,
                      keyboardType: TextInputType.emailAddress,
                      onChanged: () => setState(() {}),
                    ),
                    const SizedBox(height: 20),

                    // Phone Field
                    Align(
                      alignment: Alignment.centerLeft,
                      child: Padding(
                        padding: const EdgeInsets.only(left: 4, bottom: 6),
                        child: Text('Mobile Number',
                            style: AppTheme.labelMd
                                .copyWith(color: AppColors.onSurfaceVariant)),
                      ),
                    ),
                    _PhoneField(controller: _phone, onChanged: () => setState(() {})),
                    const SizedBox(height: 36),

                    PrimaryButton(
                      label: 'Send OTP',
                      loading: _loading,
                      onPressed: _valid ? _sendOtp : null,
                    ),
                    const SizedBox(height: 20),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _CustomTextField extends StatelessWidget {
  final TextEditingController controller;
  final String hint;
  final IconData icon;
  final TextInputType? keyboardType;
  final VoidCallback onChanged;

  const _CustomTextField({
    required this.controller,
    required this.hint,
    required this.icon,
    this.keyboardType,
    required this.onChanged,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: AppColors.outlineVariant),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          Icon(icon, size: 20, color: AppColors.onSurfaceVariant),
          const SizedBox(width: 12),
          Expanded(
            child: TextField(
              controller: controller,
              onChanged: (_) => onChanged(),
              keyboardType: keyboardType,
              style: AppTheme.bodyLg,
              cursorColor: AppColors.primary,
              decoration: InputDecoration(
                filled: false,
                border: InputBorder.none,
                focusedBorder: InputBorder.none,
                enabledBorder: InputBorder.none,
                errorBorder: InputBorder.none,
                disabledBorder: InputBorder.none,
                hintText: hint,
                hintStyle: AppTheme.bodyLg.copyWith(color: AppColors.outlineVariant),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _PhoneField extends StatelessWidget {
  final TextEditingController controller;
  final VoidCallback onChanged;
  const _PhoneField({required this.controller, required this.onChanged});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: AppColors.outlineVariant),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Row(
        children: [
          Text('+91',
              style: AppTheme.bodyMd
                  .copyWith(color: AppColors.primary, fontWeight: FontWeight.w600)),
          const Icon(Icons.expand_more, size: 20, color: AppColors.onSurfaceVariant),
          Container(
            width: 1,
            height: 28,
            margin: const EdgeInsets.symmetric(horizontal: 12),
            color: AppColors.outlineVariant,
          ),
          Expanded(
            child: TextField(
              controller: controller,
              onChanged: (_) => onChanged(),
              keyboardType: TextInputType.phone,
              maxLength: 11,
              inputFormatters: [_PhoneFormatter()],
              style: AppTheme.bodyLg.copyWith(letterSpacing: 1),
              cursorColor: AppColors.primary,
              decoration: InputDecoration(
                filled: false,
                counterText: '',
                border: InputBorder.none,
                focusedBorder: InputBorder.none,
                enabledBorder: InputBorder.none,
                errorBorder: InputBorder.none,
                disabledBorder: InputBorder.none,
                hintText: '00000 00000',
                hintStyle:
                    AppTheme.bodyLg.copyWith(color: AppColors.outlineVariant, letterSpacing: 1),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

/// Formats input as "XXXXX XXXXX".
class _PhoneFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    final digits = newValue.text.replaceAll(RegExp(r'\D'), '');
    final trimmed = digits.length > 10 ? digits.substring(0, 10) : digits;
    String out = trimmed;
    if (trimmed.length > 5) {
      out = '${trimmed.substring(0, 5)} ${trimmed.substring(5)}';
    }
    return TextEditingValue(
      text: out,
      selection: TextSelection.collapsed(offset: out.length),
    );
  }
}
