import 'package:flutter/material.dart';
// import 'package:flutter_svg/flutter_svg.dart';
import '../widgets/app_background.dart';
import '../widgets/settings_bar.dart';
import '../widgets/onboarding_button.dart';
import '../../models/advance_request.dart';
import '../../core/services/request_service.dart';
import '../../core/di/injection_container.dart';
import '../../data/datasources/user_local_data_source.dart';
import '../../domain/usecases/create_advance_usecase.dart';
import '../../domain/models/advance_request_model.dart';
import '../../core/error/failures.dart';

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

  @override
  State<RequestAdvanceScreen> createState() => _RequestAdvanceScreenState();
}

class _RequestAdvanceScreenState extends State<RequestAdvanceScreen> {
  
  // Text controller for amount
  final TextEditingController amountController = TextEditingController();
  // Text controller for reason
  final TextEditingController reasonController = TextEditingController();

  // Use the singleton instance
  final RequestService _requestService = RequestService();

  // Use case
  final CreateAdvanceUseCase _createAdvanceUseCase = sl<CreateAdvanceUseCase>();

  String _getFailureMessage(Failure failure) {
    if (failure is ServerFailure) {
      return failure.message;
    } else if (failure is NetworkFailure) {
      return failure.message;
    }
    return 'حدث خطأ غير متوقع';
  }

  // Method to save the advance request
  Future<void> _saveAdvanceRequest() async {
    if (amountController.text.isEmpty || reasonController.text.isEmpty) {
      // Show an error message if fields are empty
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('الرجاء إدخال جميع الحقول'),
            backgroundColor: Colors.red,
          ),
        );
      }
      return;
    }

    // Parse the amount to double
    final amount = double.tryParse(amountController.text);
    if (amount == null || amount <= 0) {
      // Show an error message if amount is invalid
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('الرجاء إدخال مبلغ صحيح'),
            backgroundColor: Colors.red,
          ),
        );
      }
      return;
    }

    // Get employee ID
    final employeeId = await sl<UserLocalDataSource>().getCachedEmployeeId();
    if (employeeId == null) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('خطأ: لم يتم العثور على رقم الموظف'),
            backgroundColor: Colors.red,
          ),
        );
      }
      return;
    }

    // Show loading indicator
    if (mounted) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(child: CircularProgressIndicator()),
      );
    }

    try {
      // Create advance request model
      final advanceRequestModel = AdvanceRequestModel(
        employeeId: employeeId,
        date: DateTime.now(),
        amount: amount,
        reason: reasonController.text,
      );

      final result = await _createAdvanceUseCase(advanceRequestModel);

      if (mounted) {
        Navigator.pop(context); // Close loading dialog

        result.fold(
          (failure) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(_getFailureMessage(failure)),
                backgroundColor: Colors.red,
              ),
            );
          },
          (response) {
            // Also save locally for UI display
            final advanceRequest = AdvanceRequest(
              id: response.data?.id ?? DateTime.now().millisecondsSinceEpoch.toString(),
              amount: amount,
              reason: reasonController.text,
              status: "waiting", // Default status
            );
            _requestService.addAdvanceRequest(advanceRequest);

            // Show success message
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('تم إرسال طلب السلفة بنجاح'),
                backgroundColor: Colors.green,
              ),
            );

            // Navigate back to the previous screen
            Navigator.pop(context);
          },
        );
      }
    } catch (e) {
      if (mounted) {
        Navigator.pop(context); // Close loading dialog
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('حدث خطأ غير متوقع: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: AppBackground(
        child: SafeArea(
          child: Column(
            children: [
              // Settings bar
              SettingsBar(
                selectedIndex: -1,
                onTap: (_) {},
                showBackButton: true,
                onBackTap: () => Navigator.pop(context),
                iconPaths: const [
                  "assets/images/user.svg",
                  "assets/images/bell.svg",
                ],
              ),

              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.symmetric(horizontal: 25),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Title for advance request
                      const Align(
                        alignment: Alignment.topRight,
                        child: Text(
                          "طلب سلفة",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 28,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),

                      const SizedBox(height: 40),
                      //=============================
                      // AMOUNT INPUT
                      //=============================
                      Align(
                        alignment: Alignment.centerRight,
                        child: const Text(
                          "المبلغ المطلوب",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),

                      const SizedBox(height: 6),

                      Directionality(
                        textDirection: TextDirection.rtl,
                        child: Container(
                          width: double.infinity,
                          padding: const EdgeInsets.symmetric(horizontal: 20),
                          height: 58,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(14),
                            boxShadow: const [
                              BoxShadow(
                                color: Color(0x22000000),
                                blurRadius: 8,
                                offset: Offset(0, 3),
                              ),
                            ],
                          ),
                          child: TextField(
                            controller: amountController,
                            textAlign: TextAlign.right,
                            keyboardType: TextInputType.number,
                            decoration: const InputDecoration(
                              border: InputBorder.none,
                              hintText: "دع .000 ",
                              hintStyle: TextStyle(color: Colors.grey),
                            ),
                          ),
                        ),
                      ),

                      const SizedBox(height: 25),

                      // =============================
                      // REASON TEXTFIELD
                      // =============================
                      Align(
                        alignment: Alignment.centerRight,
                        child: Directionality(
                          textDirection: TextDirection.rtl,
                          child: const Text(
                            "السبب",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 18,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),

                      // OUTER BORDER CONTAINER
                      Container(
                        padding: const EdgeInsets.all(
                          15,
                        ), // border thickness space
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Color(0xFF00FFAA), // green border
                            width: 0.5,
                          ),
                          borderRadius: BorderRadius.circular(14),
                        ),

                        // INNER TEXTFIELD CONTAINER
                        child: Container(
                          height: 100,
                          padding: const EdgeInsets.symmetric(
                            horizontal: 14,
                            vertical: 10,
                          ),
                          decoration: BoxDecoration(
                            color: const Color(0xFFEAEAEA),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          // Added Directionality to fix text direction
                          child: Directionality(
                            textDirection: TextDirection.rtl,
                            child: TextField(
                              controller: reasonController,
                              maxLines: 5,
                              textAlign:
                                  TextAlign
                                      .right, // Added this to align text to the right
                              decoration: const InputDecoration(
                                border: InputBorder.none,
                                hintText:
                                    "اكتب السبب", // Added placeholder text
                                hintStyle: TextStyle(color: Colors.grey),
                              ),
                            ),
                          ),
                        ),
                      ),

                      const SizedBox(height: 70),

                      // CONFIRM BUTTON
                      Center(
                        child: OnboardingButton(
                          text: "تأكيد الطلب",
                          backgroundColor: const Color(0xFFD1FEF0),
                          textColor: Colors.black,
                          onPressed: _saveAdvanceRequest, // Call the save method
                        ),
                      ),

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