// lib/screens/ask_form_screen.dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '/theme/theme.dart';

class AskFormScreen extends StatefulWidget {
  const AskFormScreen({Key? key}) : super(key: key);

  @override
  State<AskFormScreen> createState() => _AskFormScreenState();
}

class _AskFormScreenState extends State<AskFormScreen> {
  final _formKey = GlobalKey<FormState>();

  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _detailsController = TextEditingController();

  bool _isSubmitting = false;

  static const String _createAskUrl =
      "https://rmbferodeunited.in/api/create_ask.php";

  Future<void> _submitAsk() async {
    if (!_formKey.currentState!.validate()) return;

    setState(() => _isSubmitting = true);

    try {
      final response = await http.post(
        Uri.parse(_createAskUrl),
        body: {
          "name": _nameController.text.trim(),
          "phone": _phoneController.text.trim(),
          "details": _detailsController.text.trim(),
        },
      );

      final decoded = jsonDecode(response.body);
      final status = decoded["status"] ?? "error";
      final message = decoded["message"] ?? "Something went wrong";

      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(message)),
      );

      if (status == "success") {
        _detailsController.clear();
      }
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("Error submitting ask")),
      );
    } finally {
      if (mounted) {
        setState(() => _isSubmitting = false);
      }
    }
  }

  InputDecoration _inputDecoration(String label) {
    return InputDecoration(
      labelText: label,
      labelStyle: medium14Grey,
      filled: true,
      fillColor: whiteColor,
      contentPadding: const EdgeInsets.symmetric(
        horizontal: fixPadding,
        vertical: fixPadding,
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: const BorderSide(color: greyD4Color),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: const BorderSide(color: primaryColor, width: 1.5),
      ),
      errorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: const BorderSide(color: redColor),
      ),
      focusedErrorBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: const BorderSide(color: redColor, width: 1.5),
      ),
    );
  }

  @override
  void dispose() {
    _nameController.dispose();
    _phoneController.dispose();
    _detailsController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: whiteF3Color,

      /// HEADER — BACKGROUND PRIMARY COLOR, WHITE TEXT SIZE 18
      appBar: AppBar(
        backgroundColor: primaryColor,
        elevation: 0,
        foregroundColor: whiteColor,
        centerTitle: true,
        title: Text(
          "Specific Ask",
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: whiteColor,
          ),
        ),
      ),

      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(fixPadding),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "Create Your Request",
                style: semibold20Black33,
              ),
              height5Space,
              Text(
                "Please fill the details below and submit your specific ask.",
                style: medium14Grey,
              ),
              heightSpace,

              Expanded(
                child: Form(
                  key: _formKey,
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Align(
                          alignment: Alignment.centerLeft,
                          child: Text("Name", style: medium14Black33),
                        ),
                        height5Space,
                        TextFormField(
                          controller: _nameController,
                          style: medium14Black,
                          decoration:
                          _inputDecoration("Enter your name"),
                          validator: (value) =>
                          value == null || value.trim().isEmpty
                              ? "Enter name"
                              : null,
                        ),
                        heightSpace,

                        Align(
                          alignment: Alignment.centerLeft,
                          child: Text("Phone", style: medium14Black33),
                        ),
                        height5Space,
                        TextFormField(
                          controller: _phoneController,
                          style: medium14Black,
                          decoration:
                          _inputDecoration("Enter your phone number"),
                          keyboardType: TextInputType.phone,
                          validator: (value) =>
                          value == null || value.trim().isEmpty
                              ? "Enter phone"
                              : null,
                        ),
                        heightSpace,

                        Align(
                          alignment: Alignment.centerLeft,
                          child:
                          Text("Description", style: medium14Black33),
                        ),
                        height5Space,
                        SizedBox(
                          height: 160,
                          child: TextFormField(
                            controller: _detailsController,
                            style: medium14Black,
                            maxLines: null,
                            expands: true,
                            decoration: _inputDecoration(
                                "Describe your request"),
                            validator: (value) =>
                            value == null || value.trim().isEmpty
                                ? "Enter description"
                                : null,
                          ),
                        ),
                        heightSpace,
                      ],
                    ),
                  ),
                ),
              ),

              /// SUBMIT BUTTON
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _isSubmitting ? null : _submitAsk,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: primaryColor,
                    padding:
                    const EdgeInsets.symmetric(vertical: 14),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    elevation: 3,
                    shadowColor: shadowColor.withOpacity(0.2),
                  ),
                  child: _isSubmitting
                      ? const SizedBox(
                    height: 20,
                    width: 20,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor:
                      AlwaysStoppedAnimation<Color>(whiteColor),
                    ),
                  )
                      : const Text(
                    "Submit",
                    style: semibold16White,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
