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();

  @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,
                  fontStyle: FontStyle.normal,
                  fontWeight: FontWeight.w400,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
        ),

        // Main Body
        body: 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",
                ),
                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;
                  },
                ),
                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;
                  },
                ),
                const SizedBox(height: 16),

                _labelText("Requirement"),
                _textField(
                  controller: requirementController,
                  hint: "Enter Requirement",
                  fieldName: "Requirement",
                ),
                const SizedBox(height: 16),

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

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

                      if (!_formKey.currentState!.validate()) 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) {
                        CustomSnackBar.showSuccess(
                          context: context,
                          message: enquiryProvider.message ??
                              "Enquiry submitted successfully!",
                        );
                        _formKey.currentState!.reset();
                        nameController.clear();
                        emailController.clear();
                        phoneController.clear();
                        requirementController.clear();
                        noteController.clear();
                      } 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(
                        fontSize: 15,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// Label Text (like "Name", "Email Id")
  Widget _labelText(String title) {
    return Text(
      title,
      style: const TextStyle(
        fontSize: 14,
        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,
    String? Function(String?)? validator,
  }) {
    return FormField<String>(
      validator: validator ??
              (value) {
            if (controller.text.trim().isEmpty) {
              return '$fieldName is required';
            }
            return null;
          },
      builder: (field) {
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              decoration: BoxDecoration(
                color: Color(0xffF6F6F8),
                borderRadius: BorderRadius.circular(12),
                // border: Border.all(
                //   color: field.hasError ? Colors.red : Colors.transparent,
                //   width: 1,
                // ),
              ),
              child: TextFormField(
                controller: controller,
                keyboardType: keyboardType,
                maxLines: maxLines,
                onChanged: (_) => field.didChange(controller.text),
                decoration: InputDecoration(
                  hintText: hint,
                  hintStyle: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[400],
                    fontStyle: FontStyle.normal,
                    fontWeight: FontWeight.w400,
                  ),
                  contentPadding:
                  const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
                  border: InputBorder.none,
                ),
              ),
            ),
            if (field.hasError)
              Padding(
                padding: const EdgeInsets.only(top: 5, left: 4),
                child: Text(
                  field.errorText ?? '',
                  style: const TextStyle(
                    color: Colors.red,
                    fontSize: 12,
                  ),
                ),
              ),
          ],
        );
      },
    );
  }

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