import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:get/get.dart';
import 'package:taxglide/consts/app_asstes.dart';
import 'package:taxglide/consts/app_colors.dart';
import 'package:taxglide/consts/app_style.dart';
import 'package:taxglide/consts/comman_button.dart';
import 'package:taxglide/consts/comman_container_auth.dart';
import 'package:taxglide/consts/comman_textformfileds.dart';
import 'package:taxglide/consts/responsive_helper.dart';
import 'package:taxglide/consts/validation_popup.dart';
import 'package:taxglide/controller/api_contoller.dart';
import 'package:taxglide/router/consts_routers.dart';

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

  @override
  ConsumerState<ForgotScreen> createState() => _ForgotScreenState();
}

class _ForgotScreenState extends ConsumerState<ForgotScreen> {
  final TextEditingController _emailController = TextEditingController();
  final ValidationPopup _validationPopup = ValidationPopup();
  bool _isEmployee = false;

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    if (args != null && args is Map<String, dynamic>) {
      _isEmployee = args['isEmployee'] ?? false;
    }
  }

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

  Future<void> _handleForgotRequest() async {
    final email = _emailController.text.trim();

    if (!_validationPopup.validateEmail(context, email)) {
      return;
    }

    await ref.read(forgotPasswordProvider.notifier).requestOtp(email, _isEmployee);
    final state = ref.read(forgotPasswordProvider);

    state.when(
      data: (data) {
        if (data['success'] == true) {
          _validationPopup.showSuccessMessage(
            context,
            "OTP sent to your email!",
          );
          Get.toNamed(
            _isEmployee ? ConstRouters.employeeotp : ConstRouters.otp,
            arguments: {
              'email': email,
              'isEmployee': _isEmployee,
              'fromForgot': true,
            },
          );
        } else if (data['error'] != null) {
          _validationPopup.showErrorMessage(context, data['error'].toString());
        }
      },
      loading: () {},
      error: (err, _) {
        _validationPopup.showErrorMessage(context, "Error: $err");
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final forgotState = ref.watch(forgotPasswordProvider);
    final r = ResponsiveUtils(context);

    final logoWidth = r.getValue<double>(mobile: 120, tablet: 141, desktop: 160);
    final logoHeight = r.getValue<double>(mobile: 85, tablet: 100, desktop: 115);
    final titleFontSize = r.fontSize(mobile: 26, tablet: 32, desktop: 36);
    final subtitleFontSize = r.fontSize(mobile: 13, tablet: 14, desktop: 15);
    final spacingSM = r.spacing(mobile: 15, tablet: 20, desktop: 24);
    final spacingMD = r.spacing(mobile: 20, tablet: 22, desktop: 26);
    final spacingLG = r.spacing(mobile: 20, tablet: 22, desktop: 28);

    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Color(0xFFFFF8F0),
              Color(0xFFEBC894),
              Color(0xFFE8DAF2),
              Color(0xFFB49EF4),
            ],
            stops: [0.0, 0.3, 0.6, 1.0],
          ),
        ),
        child: Center(
          child: SingleChildScrollView(
            child: CommonContainerAuth(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                    AppAssets.taxgildelogoauth,
                    width: logoWidth,
                    height: logoHeight,
                  ),
                  SizedBox(height: spacingSM),
                  Text(
                    "Forgot Password",
                    style: AppTextStyles.bold.copyWith(
                      fontSize: titleFontSize,
                      color: AppColors.authheading,
                    ),
                  ),
                  SizedBox(height: spacingSM),
                  Text(
                    "Enter your email to receive an OTP",
                    textAlign: TextAlign.center,
                    style: AppTextStyles.medium.copyWith(
                      fontSize: subtitleFontSize,
                      color: AppColors.authleading,
                    ),
                  ),
                  SizedBox(height: spacingLG),
                  CommanTextFormField(
                    controller: _emailController,
                    hintText: 'Enter your Email',
                    keyboardType: TextInputType.emailAddress,
                    prefixIcon: Icons.email_outlined,
                  ),
                  SizedBox(height: spacingLG),
                  forgotState.isLoading
                      ? const CircularProgressIndicator()
                      : CommanButton(
                          text: "Send OTP",
                          onPressed: _handleForgotRequest,
                        ),
                  SizedBox(height: spacingMD),
                  TextButton(
                    onPressed: () => Get.back(),
                    child: Text(
                      "Back to Login",
                      style: AppTextStyles.semiBold.copyWith(
                        color: AppColors.authsignup,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
