import 'dart:convert';

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

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

  @override
  State<FeedbackAppScreen> createState() => _FeedbackAppScreenState();
}

class _FeedbackAppScreenState extends State<FeedbackAppScreen> {
  final _formKey = GlobalKey<FormState>();

  // API URL
  final String _feedbackUrl = 'https://rmbferodeunited.in/api/feedback_app.php';

  String? _q1;
  String? _q2;
  String? _q3;
  String? _q4;

  final TextEditingController _descriptionController = TextEditingController();

  bool _isSubmitting = false;

  @override
  void dispose() {
    _descriptionController.dispose();
    super.dispose();
  }

  List<DropdownMenuItem<String>> _ratingItems() {
    return List.generate(
      5,
          (index) {
        final value = (index + 1).toString(); // 1..5
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      },
    );
  }

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

    setState(() {
      _isSubmitting = true;
    });

    try {
      final response = await http.post(
        Uri.parse(_feedbackUrl),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: {
          'q1': _q1!,
          'q2': _q2!,
          'q3': _q3!,
          'q4': _q4!,
          'description': _descriptionController.text.trim(),
        },
      );

      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['success'] == true) {
          _showSnackBar('Feedback submitted successfully', isError: false);
          _resetForm();
        } else {
          _showSnackBar(data['message'] ?? 'Failed to submit feedback');
        }
      } else {
        _showSnackBar('Server error: ${response.statusCode}');
      }
    } catch (e) {
      _showSnackBar('Error: $e');
    } finally {
      setState(() {
        _isSubmitting = false;
      });
    }
  }

  void _resetForm() {
    setState(() {
      _q1 = null;
      _q2 = null;
      _q3 = null;
      _q4 = null;
      _descriptionController.clear();
    });
  }

  void _showSnackBar(String message, {bool isError = true}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : Colors.green,
      ),
    );
  }

  Widget _buildQuestionField({
    required String label,
    required String? value,
    required void Function(String?) onChanged,
  }) {
    return DropdownButtonFormField<String>(
      decoration: InputDecoration(
        labelText: label,
        border: const OutlineInputBorder(),
      ),
      value: value,
      items: _ratingItems(),
      onChanged: onChanged,
      validator: (val) => val == null ? 'Please select rating' : null,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Feedback Form'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: [
              _buildQuestionField(
                label: 'Q1. Design & UI',
                value: _q1,
                onChanged: (val) => setState(() => _q1 = val),
              ),
              const SizedBox(height: 16),

              _buildQuestionField(
                label: 'Q2. Performance',
                value: _q2,
                onChanged: (val) => setState(() => _q2 = val),
              ),
              const SizedBox(height: 16),

              _buildQuestionField(
                label: 'Q3. Features & Usability',
                value: _q3,
                onChanged: (val) => setState(() => _q3 = val),
              ),
              const SizedBox(height: 16),

              _buildQuestionField(
                label: 'Q4. Overall Experience',
                value: _q4,
                onChanged: (val) => setState(() => _q4 = val),
              ),
              const SizedBox(height: 16),

              // Description
              TextFormField(
                controller: _descriptionController,
                maxLines: 4,
                decoration: const InputDecoration(
                  labelText: 'Description / Suggestions',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 24),

              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _isSubmitting ? null : _submitFeedback,
                  child: _isSubmitting
                      ? const SizedBox(
                    height: 20,
                    width: 20,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  )
                      : const Text('Submit Feedback'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
