import 'package:bookmywages/consts_widgets/app_assets.dart';
import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/consts_widgets/comman_button.dart';
import 'package:bookmywages/consts_widgets/comman_textformfiled.dart';
import 'package:bookmywages/routers/consts_router.dart';
import 'package:bookmywages/viewmodel/api_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

class SignUpScreen extends ConsumerStatefulWidget {
  const SignUpScreen({super.key});

  @override
  ConsumerState<SignUpScreen> createState() => _SignUpScreenState();
}

class _SignUpScreenState extends ConsumerState<SignUpScreen> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _mobilenumberController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  bool _obscurePassword = true;

  @override
  void dispose() {
    _usernameController.dispose();
    _mobilenumberController.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  void _onSignUp() async {
    final userData = {
      'name': _usernameController.text.trim(),
      'number': _mobilenumberController.text.trim(),
      'email': _emailController.text.trim(),
      'password': _passwordController.text.trim(),
    };

    try {
      final result = await ref.read(signupFutureProvider(userData).future);

      final userId = result['data'][0]['id'];

      if (mounted) {
        Fluttertoast.showToast(
          msg: "Signup Successful: ${result['message'] ?? 'Success'}",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.green,
          textColor: Colors.white,
        );

        Get.toNamed(RouterConts.otp, arguments: userId);

        // Pass userId to OTP screen
      }
    } catch (e) {
      if (mounted) {
        Fluttertoast.showToast(
          msg: "Signup Failed: ${e.toString()}",
          toastLength: Toast.LENGTH_LONG,
          gravity: ToastGravity.BOTTOM,
          backgroundColor: Colors.red,
          textColor: Colors.white,
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    final double horizontalPadding = screenSize.width * 0.05;

    // ignore: deprecated_member_use
    return WillPopScope(
      onWillPop: () async {
        // context.push(RouterConts.welcomepage); // Actually go back
        return false; // Prevent default behavior (optional)
      },

      child: Scaffold(
        backgroundColor: AppColors.secondprimary,
        resizeToAvoidBottomInset: true,
        body: SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Image.asset(
                  AppAssets.login,
                  width: screenSize.width,
                  fit: BoxFit.cover,
                ),
                Transform.translate(
                  offset: const Offset(0, -150),
                  child: Container(
                    width: double.infinity,
                    margin: EdgeInsets.symmetric(horizontal: horizontalPadding),
                    padding: EdgeInsets.all(screenSize.width * 0.05),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(32.73),
                      border: Border.all(
                        width: 1.09,
                        color: const Color(0xFFA39898),
                      ),
                      boxShadow: const [
                        BoxShadow(
                          offset: Offset(0, -4),
                          blurRadius: 12.3,
                          color: Color(0x66E0E0E0),
                        ),
                        BoxShadow(
                          offset: Offset(0, 4),
                          blurRadius: 4,
                          color: Color(0x66000000),
                        ),
                      ],
                      color: Colors.white,
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Text(
                          "Sign up",
                          style: TextStyle(
                            fontSize: 32,
                            fontFamily: "Gilroy-ExtraBold",
                            fontWeight: FontWeight.w800,
                            height: 1.0,
                            letterSpacing: 0.64,
                          ),
                        ),
                        SizedBox(height: screenSize.height * 0.03),

                        CommonTextFormField(
                          hintText: 'Enter your username',
                          controller: _usernameController,
                          prefixIcon: const Icon(
                            Icons.person,
                            color: AppColors.hittext,
                          ),
                        ),
                        const SizedBox(height: 16),

                        CommonTextFormField(
                          hintText: 'Enter your mobile number',
                          controller: _mobilenumberController,
                          prefixIcon: const Icon(
                            Icons.phone,
                            color: AppColors.hittext,
                          ),
                        ),
                        const SizedBox(height: 16),

                        CommonTextFormField(
                          hintText: 'Enter your email',
                          controller: _emailController,
                          prefixIcon: const Icon(
                            Icons.email,
                            color: AppColors.hittext,
                          ),
                        ),
                        const SizedBox(height: 16),

                        CommonTextFormField(
                          hintText: 'Enter your password',
                          controller: _passwordController,
                          obscureText: _obscurePassword,
                          prefixIcon: const Icon(
                            Icons.lock,
                            color: AppColors.hittext,
                          ),
                          suffixIcon: IconButton(
                            icon: Icon(
                              _obscurePassword
                                  ? Icons.visibility_off
                                  : Icons.visibility,
                              color: AppColors.hittext,
                            ),
                            onPressed: () {
                              setState(() {
                                _obscurePassword = !_obscurePassword;
                              });
                            },
                          ),
                        ),

                        const SizedBox(height: 15),

                        CommanButton(
                          text: 'Sign up',
                          textStyle: const TextStyle(
                            fontFamily: 'Gilroy-Black',
                            fontWeight: FontWeight.w800,
                            fontSize: 20,
                            height: 1.0,
                            color: AppColors.secondprimary,
                          ),
                          onPressed: _onSignUp,
                          isPrimary: true,
                          backgroundColor: AppColors.primary,
                          textColor: AppColors.secondprimary,
                          width: 230,
                        ),

                        const SizedBox(height: 10),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
