import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';
import '../../Notifier/HelpAndEnquiryProvider.dart';
import '../../Utility/AppColors.dart';
import '../../Utility/CustomSnackbar.dart';

class EnquiryScreen extends StatefulWidget {
  final String sessionId;
  final String accId;

  const EnquiryScreen({
    super.key,
    required this.sessionId,
    required this.accId,
  });

  @override
  State<EnquiryScreen> createState() => _EnquiryScreenState();
}

class _EnquiryScreenState extends State<EnquiryScreen> {
  final _formKey = GlobalKey<FormState>();

  final TextEditingController nameController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController requirementController = TextEditingController();
  final TextEditingController noteController = TextEditingController();

  // Track field validation states for real-time validation
  bool _nameValid = true;
  bool _emailValid = true;
  bool _phoneValid = true;
  bool _requirementValid = true;

  // Success dialog state
  bool _showSuccessDialog = false;

  @override
  Widget build(BuildContext context) {
    final enquiryProvider = Provider.of<HelpAndEnquiryProvider>(context);

    return SafeArea(
      top: false,
      child: Scaffold(
        backgroundColor: Color(0xFFffffff),
        appBar: AppBar(
          automaticallyImplyLeading: false,
          backgroundColor: Color(0xFFFCFCFC),
          elevation: 0,
          title: Row(
            children: [
              InkResponse(
                onTap: () => Navigator.pop(context, true),
                child: SvgPicture.asset(
                  "assets/svg/continue_left_ic.svg",
                  height: 25,
                ),
              ),
              const SizedBox(width: 10),
              const Text(
                "Enquiry",
                style: TextStyle(
                  fontSize: 16,
                  fontFamily: "Poppins",
                  fontStyle: FontStyle.normal,
                  fontWeight: FontWeight.w400,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
        ),

        // Main Body
        body: Stack(
          children: [
            SingleChildScrollView(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _labelText("Name"),
                    _textField(
                      controller: nameController,
                      hint: "Enter Name",
                      fieldName: "Name",
                      onChanged: (value) {
                        setState(() {
                          _nameValid = value.trim().isNotEmpty;
                        });
                      },
                    ),
                    const SizedBox(height: 16),

                    _labelText("Email Id"),
                    _textField(
                      controller: emailController,
                      hint: "Enter Email ID",
                      fieldName: "Email",
                      keyboardType: TextInputType.emailAddress,
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return "Please enter your email";
                        }
                        if (!RegExp(r'^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$')
                            .hasMatch(value.trim())) {
                          return "Enter a valid email";
                        }
                        return null;
                      },
                      onChanged: (value) {
                        setState(() {
                          _emailValid = value != null &&
                              value.trim().isNotEmpty &&
                              RegExp(r'^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$')
                                  .hasMatch(value.trim());
                        });
                      },
                    ),
                    const SizedBox(height: 16),

                    _labelText("Phone No."),
                    _textField(
                      controller: phoneController,
                      hint: "Enter Phone Number",
                      fieldName: "Phone Number",
                      keyboardType: TextInputType.phone,
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return "Please enter your phone number";
                        }
                        if (value.trim().length < 10) {
                          return "Enter a valid phone number";
                        }
                        return null;
                      },
                      onChanged: (value) {
                        setState(() {
                          _phoneValid = value != null &&
                              value.trim().isNotEmpty &&
                              value.trim().length >= 10;
                        });
                      },
                    ),
                    const SizedBox(height: 16),

                    _labelText("Requirement"),
                    _textField(
                      controller: requirementController,
                      hint: "Enter Requirement",
                      fieldName: "Requirement",
                      onChanged: (value) {
                        setState(() {
                          _requirementValid = value.trim().isNotEmpty;
                        });
                      },
                    ),
                    const SizedBox(height: 16),

                    _labelText("Note"),
                    _textField(
                      controller: noteController,
                      hint: "Write a short note",
                      fieldName: "Note",
                      maxLines: 5,
                      isOptional: true,
                    ),
                    const SizedBox(height: 32),

                    // Submit button
                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: enquiryProvider.isLoading
                            ? null
                            : () async {
                          FocusScope.of(context).unfocus();

                          // Validate all fields
                          bool isValid = true;

                          if (nameController.text.trim().isEmpty) {
                            setState(() {
                              _nameValid = false;
                            });
                            isValid = false;
                          }

                          if (emailController.text.trim().isEmpty ||
                              !RegExp(r'^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$')
                                  .hasMatch(emailController.text.trim())) {
                            setState(() {
                              _emailValid = false;
                            });
                            isValid = false;
                          }

                          if (phoneController.text.trim().isEmpty ||
                              phoneController.text.trim().length < 10) {
                            setState(() {
                              _phoneValid = false;
                            });
                            isValid = false;
                          }

                          if (requirementController.text.trim().isEmpty) {
                            setState(() {
                              _requirementValid = false;
                            });
                            isValid = false;
                          }

                          if (!isValid) return;

                          final success =
                          await enquiryProvider.submitEnquiry(
                            sessionId: widget.sessionId,
                            accId: widget.accId,
                            name: nameController.text.trim(),
                            email: emailController.text.trim(),
                            mobile: phoneController.text.trim(),
                            requirement: requirementController.text.trim(),
                            note: noteController.text.trim(),
                          );

                          if (!mounted) return;

                          if (success) {
                            // Show success dialog instead of snackbar
                            setState(() {
                              _showSuccessDialog = true;
                            });

                            // Clear form
                            _formKey.currentState!.reset();
                            nameController.clear();
                            emailController.clear();
                            phoneController.clear();
                            requirementController.clear();
                            noteController.clear();

                            // Reset validation states
                            setState(() {
                              _nameValid = true;
                              _emailValid = true;
                              _phoneValid = true;
                              _requirementValid = true;
                            });

                          } else {
                            CustomSnackBar.showError(
                              context: context,
                              message: enquiryProvider.message ??
                                  "Failed to submit enquiry!",
                            );
                          }
                        },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppColors.buttonColor,
                          foregroundColor: Colors.white,
                          padding: const EdgeInsets.symmetric(vertical: 16),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(28),
                          ),
                          elevation: 0,
                        ),
                        child: enquiryProvider.isLoading
                            ? const SizedBox(
                          height: 22,
                          width: 22,
                          child: CircularProgressIndicator(
                            strokeWidth: 2.5,
                            color: Colors.white,
                          ),
                        )
                            : const Text(
                          "Submit",
                          style: TextStyle(
                            fontFamily: "Poppins",
                            fontSize: 15,
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),

            // Success Dialog
            if (_showSuccessDialog)
              Container(
                color: Colors.black54,
                child: Center(
                  child: Container(
                    width: MediaQuery.of(context).size.width * 0.8,
                    padding: const EdgeInsets.all(24),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        const Text(
                          "Submitted",
                          style: TextStyle(
                            fontSize: 18,
                            fontFamily: "Poppins",
                            fontWeight: FontWeight.w600,
                            color: Colors.black,
                          ),
                        ),
                        const SizedBox(height: 16),
                        const Text(
                          "Thanks for reaching out!\n\nWe've got your application.\nOur representative will call you soon.",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 14,
                            fontFamily: "Poppins",
                            fontWeight: FontWeight.w400,
                            color: Colors.black87,
                          ),
                        ),
                        const SizedBox(height: 24),
                        SizedBox(
                          width: double.infinity,
                          child: ElevatedButton(
                            onPressed: () {
                              setState(() {
                                _showSuccessDialog = false;
                              });
                              Navigator.pop(context);
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: AppColors.buttonColor,
                              foregroundColor: Colors.white,
                              padding: const EdgeInsets.symmetric(vertical: 12),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(28),
                              ),
                            ),
                            child: const Text(
                              "Close",
                              style: TextStyle(
                                fontFamily: "Poppins",
                                fontSize: 15,
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// Label Text (like "Name", "Email Id")
  Widget _labelText(String title) {
    return Text(
      title,
      style: const TextStyle(
        fontSize: 14,
        fontFamily: "Poppins",
        fontStyle: FontStyle.normal,
        fontWeight: FontWeight.w400,
        color: Colors.black,
      ),
    );
  }

  /// Text Field with error message shown below box
  Widget _textField({
    required TextEditingController controller,
    required String hint,
    required String fieldName,
    TextInputType keyboardType = TextInputType.text,
    int maxLines = 1,
    bool isOptional = false,
    String? Function(String?)? validator,
    Function(String)? onChanged,
  }) {
    bool hasError = false;
    String errorText = '';

    // Determine validation state based on field type
    if (fieldName == "Name" && !_nameValid) {
      hasError = true;
      errorText = "Name is required";
    } else if (fieldName == "Email" && !_emailValid) {
      hasError = true;
      if (emailController.text.trim().isEmpty) {
        errorText = "Please enter your email";
      } else {
        errorText = "Enter a valid email";
      }
    } else if (fieldName == "Phone Number" && !_phoneValid) {
      hasError = true;
      if (phoneController.text.trim().isEmpty) {
        errorText = "Please enter your phone number";
      } else {
        errorText = "Enter a valid phone number";
      }
    } else if (fieldName == "Requirement" && !_requirementValid) {
      hasError = true;
      errorText = "Requirement is required";
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          decoration: BoxDecoration(
            color: Color(0xffF6F6F8),
            borderRadius: BorderRadius.circular(12),
            // border: Border.all(
            //   color: hasError ? Colors.red : Colors.transparent,
            //   width: 1,
            // ),
          ),
          child: TextFormField(
            controller: controller,
            keyboardType: keyboardType,
            maxLines: maxLines,
            onChanged: (value) {
              if (onChanged != null) onChanged(value);

              // Clear error when user starts typing
              if (value.isNotEmpty) {
                setState(() {
                  if (fieldName == "Name") _nameValid = true;
                  if (fieldName == "Email") {
                    _emailValid = value.trim().isNotEmpty &&
                        RegExp(r'^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$')
                            .hasMatch(value.trim());
                  }
                  if (fieldName == "Phone Number") {
                    _phoneValid = value.trim().isNotEmpty &&
                        value.trim().length >= 10;
                  }
                  if (fieldName == "Requirement") _requirementValid = true;
                });
              }
            },
            style: TextStyle(
              fontSize: 14,
              fontFamily: "Poppins",
              color: Colors.black,
              fontWeight: FontWeight.w400,
            ),
            decoration: InputDecoration(
              hintText: hint,
              hintStyle: TextStyle(
                fontSize: 14,
                fontFamily: "Poppins",
                color: Colors.grey[400],
                fontStyle: FontStyle.normal,
                fontWeight: FontWeight.w400,
              ),
              contentPadding:
              const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
              border: InputBorder.none,
            ),
          ),
        ),
        if (hasError)
          Padding(
            padding: const EdgeInsets.only(top: 5, left: 4),
            child: Text(
              errorText,
              style: const TextStyle(
                fontFamily: "Poppins",
                color: Colors.red,
                fontSize: 12,
              ),
            ),
          ),
      ],
    );
  }

  @override
  void dispose() {
    nameController.dispose();
    emailController.dispose();
    phoneController.dispose();
    requirementController.dispose();
    noteController.dispose();
    super.dispose();
  }
}