// lib/screens/forms/ask_reply_screen.dart

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

class AskReplyScreen extends StatefulWidget {
  final String id;
  final String name;
  final String phone;
  final String details;

  const AskReplyScreen({
    Key? key,
    required this.id,
    required this.name,
    required this.phone,
    required this.details,
  }) : super(key: key);

  @override
  State<AskReplyScreen> createState() => _AskReplyScreenState();
}

class _AskReplyScreenState extends State<AskReplyScreen> {
  final _formKey = GlobalKey<FormState>();

  final TextEditingController _replierNameCtrl = TextEditingController();
  final TextEditingController _companyCtrl = TextEditingController();
  final TextEditingController _designationCtrl = TextEditingController();
  final TextEditingController _phoneCtrl = TextEditingController();
  final TextEditingController _replyCtrl = TextEditingController();

  bool _isSubmitting = false;

  static const String _replyAskUrl =
      'https://rmbferodeunited.in/api/reply_ask.php';

  @override
  void dispose() {
    _replierNameCtrl.dispose();
    _companyCtrl.dispose();
    _designationCtrl.dispose();
    _phoneCtrl.dispose();
    _replyCtrl.dispose();
    super.dispose();
  }

  /// =======================
  /// COMMON BOX DECORATION
  /// =======================
  InputDecoration _boxDecoration(String label) {
    return InputDecoration(
      labelText: label,
      labelStyle: medium14Grey,
      filled: true,
      fillColor: whiteColor,
      contentPadding:
      const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: const BorderSide(color: greyD9Color),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: const BorderSide(color: greyD9Color),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: const BorderSide(color: primaryColor),
      ),
    );
  }

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

    final payload = {
      'id': widget.id,
      'name': _replierNameCtrl.text.trim(),
      'company': _companyCtrl.text.trim(),
      'designation': _designationCtrl.text.trim(),
      'phone': _phoneCtrl.text.trim(),
      'reply_text': _replyCtrl.text.trim(),
    };

    print('-----------------------------');
    print('POST REQUEST URL → $_replyAskUrl');
    print('POST PAYLOAD → $payload');
    print('-----------------------------');

    setState(() => _isSubmitting = true);

    try {
      final response =
      await http.post(Uri.parse(_replyAskUrl), body: payload);

      print('RESPONSE STATUS → ${response.statusCode}');
      print('RESPONSE BODY → ${response.body}');
      print('-----------------------------');

      final decoded = jsonDecode(response.body);

      if (!mounted) return;

      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text(decoded['message'])));

      if (decoded['status'] == 'success') {
        Navigator.pop(context, true);
      }
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context)
          .showSnackBar(const SnackBar(content: Text('Reply failed')));
    } finally {
      if (mounted) setState(() => _isSubmitting = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: whiteF3Color,
      appBar: AppBar(
        backgroundColor: primaryColor,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: whiteColor),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          'Reply to Ask',
          style: TextStyle(
            color: whiteColor,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: false,
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(fixPadding),
          child: Column(
            children: [
              /// REQUEST DETAILS
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(fixPadding),
                decoration: BoxDecoration(
                  color: whiteColor,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(color: greyD9Color),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('Request Details',
                        style: semibold16Black33),
                    height5Space,
                    Text('Name: ${widget.name}', style: medium14Grey),
                    Text('Phone: ${widget.phone}', style: medium14Grey),
                    height5Space,
                    Text(widget.details, style: medium14Black33),
                  ],
                ),
              ),

              heightSpace,

              /// FORM
              Expanded(
                child: Form(
                  key: _formKey,
                  child: ListView(
                    children: [
                      TextFormField(
                        controller: _replierNameCtrl,
                        decoration: _boxDecoration('Name'),
                        style: medium14Black33,
                      ),
                      heightSpace,

                      TextFormField(
                        controller: _companyCtrl,
                        decoration: _boxDecoration('Company name'),
                        style: medium14Black33,
                      ),
                      heightSpace,

                      TextFormField(
                        controller: _designationCtrl,
                        decoration: _boxDecoration('Designation'),
                        style: medium14Black33,
                      ),
                      heightSpace,

                      TextFormField(
                        controller: _phoneCtrl,
                        decoration: _boxDecoration('Phone number'),
                        keyboardType: TextInputType.phone,
                        style: medium14Black33,
                      ),
                      heightSpace,

                      SizedBox(
                        height: 200,
                        child: TextFormField(
                          controller: _replyCtrl,
                          decoration:
                          _boxDecoration('Type your reply here'),
                          maxLines: null,
                          expands: true,
                          style: medium14Black33,
                          validator: (v) =>
                          v == null || v.isEmpty ? 'Required' : null,
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              /// SUBMIT BUTTON
              SizedBox(
                width: double.infinity,
                height: 48,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: primaryColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                  onPressed: _isSubmitting ? null : _submitReply,
                  child: _isSubmitting
                      ? const CircularProgressIndicator(color: whiteColor)
                      : const Text('Submit Reply', style: semibold16White),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
