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

class AddComplaintScreen extends StatefulWidget {
  const AddComplaintScreen({super.key});

  @override
  State<AddComplaintScreen> createState() => _AddComplaintScreenState();
}

class _AddComplaintScreenState extends State<AddComplaintScreen> {
  bool loadingMembers = false;
  bool submitting = false;

  int? fromMemberRid;

  ComplaintMember? selectedMember;
  List<ComplaintMember> members = [];

  final TextEditingController descriptionController =
  TextEditingController();

  final String getMembersUrl =
      'https://rmbferodeunited.in/api/get_members.php';
  final String postUrl =
      'https://rmbferodeunited.in/api/testimonials.php';

  @override
  void initState() {
    super.initState();
    _loadRidAndMembers();
  }

  /* ================= LOAD RID ================= */

  Future<void> _loadRidAndMembers() async {
    final prefs = await SharedPreferences.getInstance();
    final rid =
        prefs.getString('rid_no') ?? prefs.getString('from_member');

    if (rid == null || rid.isEmpty) {
      if (!mounted) return;
      Navigator.pushNamedAndRemoveUntil(
        context,
        '/login',
            (_) => false,
      );
      return;
    }

    fromMemberRid = int.tryParse(rid);
    if (fromMemberRid == null) {
      _showSnack('Invalid logged-in RID');
      return;
    }

    await fetchMembers();
  }

  /* ================= FETCH MEMBERS ================= */

  Future<void> fetchMembers() async {
    setState(() {
      loadingMembers = true;
      members.clear();
      selectedMember = null;
    });

    try {
      debugPrint('GET → $getMembersUrl');
      final res = await http.get(Uri.parse(getMembersUrl));

      debugPrint('STATUS → ${res.statusCode}');
      debugPrint('BODY → ${res.body}');

      if (res.statusCode != 200) {
        _showSnack('Failed to fetch members');
        return;
      }

      final decoded = jsonDecode(res.body);
      final List data =
      decoded is Map && decoded['data'] is List
          ? decoded['data']
          : (decoded is List ? decoded : []);

      members = data
          .map((e) => ComplaintMember.fromJson(e))
          .where((m) => m.ridNo.isNotEmpty)
          .toList()
        ..sort(
              (a, b) => a.displayName
              .toLowerCase()
              .compareTo(b.displayName.toLowerCase()),
        );

      debugPrint('PARSED MEMBERS → ${members.length}');
    } catch (e) {
      debugPrint('fetchMembers ERROR → $e');
      _showSnack('Error fetching members');
    } finally {
      setState(() => loadingMembers = false);
    }
  }

  /* ================= SUBMIT ================= */

  Future<void> submitData() async {
    final desc = descriptionController.text.trim();

    if (selectedMember == null) {
      _showSnack('Please select a member');
      return;
    }
    if (desc.isEmpty) {
      _showSnack('Please enter description');
      return;
    }
    if (fromMemberRid == null) {
      _showSnack('Invalid logged-in user');
      return;
    }

    final payload = {
      'from_member': fromMemberRid,
      'to_member': selectedMember!.ridNo,
      'description': desc,
      'status': 'sent',
    };

    setState(() => submitting = true);

    try {
      debugPrint('POST → $postUrl');
      debugPrint('PAYLOAD → ${jsonEncode(payload)}');

      final res = await http.post(
        Uri.parse(postUrl),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode(payload),
      );

      debugPrint('STATUS → ${res.statusCode}');
      debugPrint('BODY → ${res.body}');

      if (res.statusCode == 200 || res.statusCode == 201) {
        final body = jsonDecode(res.body);
        if (body is Map && body['success'] == true) {
          if (!mounted) return;
          showDialog(
            context: context,
            builder: (_) => AlertDialog(
              title: const Text('Success'),
              content:
              const Text('Testimonial submitted successfully.'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                    Navigator.pop(context);
                  },
                  child: const Text('OK'),
                )
              ],
            ),
          );
        } else {
          _showSnack(body['message'] ?? 'Submit failed');
        }
      } else {
        _showSnack('Server error ${res.statusCode}');
      }
    } catch (e) {
      debugPrint('submitData ERROR → $e');
      _showSnack('Error submitting data');
    } finally {
      setState(() => submitting = false);
    }
  }

  /* ================= UI ================= */

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(
          color: Colors.white,
        ),
        title: const Text(
          'Add Testimonial',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        centerTitle: false,
        actions: [
          IconButton(
            icon: const Icon(
              Icons.refresh,
              color: Colors.white,
            ),
            onPressed: loadingMembers ? null : fetchMembers,
          ),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'To Member',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 8),
            _memberDropdown(),
            const SizedBox(height: 20),
            const Text(
              'Description',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 8),
            TextField(
              controller: descriptionController,
              maxLines: 5,
              decoration: const InputDecoration(
                hintText: 'Enter your testimonial...',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 30),
            SizedBox(
              width: double.infinity,
              height: 50,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).primaryColor,
                ),
                onPressed: submitting ? null : submitData,
                child: submitting
                    ? const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    color: Colors.white,
                  ),
                )
                    : const Text(
                  'Submit',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _memberDropdown() {
    if (loadingMembers) {
      return const Center(child: CircularProgressIndicator());
    }

    if (members.isEmpty) {
      return Row(
        children: [
          const Expanded(child: Text('No members found')),
          TextButton(
            onPressed: fetchMembers,
            child: const Text('Retry'),
          ),
        ],
      );
    }

    return DropdownButtonFormField<ComplaintMember>(
      isExpanded: true,
      value: selectedMember,
      decoration: const InputDecoration(
        border: OutlineInputBorder(),
      ),
      hint: const Text('Select Member'),
      items: members.map((m) {
        return DropdownMenuItem(
          value: m,
          child: Text(
            m.displayName,
            overflow: TextOverflow.ellipsis,
          ),
        );
      }).toList(),
      selectedItemBuilder: (context) {
        return members.map((m) {
          return Align(
            alignment: Alignment.centerLeft,
            child: Text(
              m.displayName,
              overflow: TextOverflow.ellipsis,
            ),
          );
        }).toList();
      },
      onChanged: (val) => setState(() => selectedMember = val),
    );
  }

  void _showSnack(String msg) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(msg)),
    );
  }

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

/* ================= MODEL (NO CONFLICT) ================= */

class ComplaintMember {
  final String ridNo;
  final String fullName;
  final String companyName;

  ComplaintMember({
    required this.ridNo,
    required this.fullName,
    required this.companyName,
  });

  factory ComplaintMember.fromJson(Map<String, dynamic> j) {
    return ComplaintMember(
      ridNo: (j['rid_no'] ?? j['rid'] ?? '').toString(),
      fullName: (j['full_name'] ?? j['name'] ?? '').toString(),
      companyName: (j['company_name'] ?? '').toString(),
    );
  }

  String get displayName =>
      companyName.isNotEmpty
          ? '$fullName ($companyName)'
          : fullName;
}
