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

import '../../api_constants.dart';
import '../../theme/theme.dart';

/// =======================
/// MODEL
/// =======================
class InviteItem {
  final String ridNo;
  final String fullName;
  final String companyName;

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

  factory InviteItem.fromMap(Map<String, dynamic> m) {
    return InviteItem(
      ridNo: (m['rid_no'] ?? '').toString(),
      fullName: (m['full_name'] ?? '').toString(),
      companyName: (m['company_name'] ?? '').toString(),
    );
  }

  /// 👇 THIS controls dropdown display
  String get displayText =>
      companyName.isNotEmpty
          ? '$fullName ($companyName)'
          : fullName;
}

/// =======================
/// SCREEN
/// =======================
class AddReferralScreen extends StatefulWidget {
  const AddReferralScreen({super.key});

  @override
  State<AddReferralScreen> createState() => _AddReferralScreenState();
}

class _AddReferralScreenState extends State<AddReferralScreen> {
  final _formKey = GlobalKey<FormState>();

  final _nameController = TextEditingController();
  final _detailsController = TextEditingController();
  final _companyNameController = TextEditingController();
  final _mobileController = TextEditingController();
  final _emailController = TextEditingController();

  final String _invitesUrl =
      'https://rmbferodeunited.in/api/get_invite_by.php';

  List<InviteItem> _invites = [];
  InviteItem? _selectedInvite;

  String? _myRidNo;
  bool _loadingInvites = true;
  bool _submitting = false;
  String? _error;

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

  Future<void> _init() async {
    await _loadRid();
    await _fetchInvites();
  }

  /// =======================
  /// LOAD RID
  /// =======================
  Future<void> _loadRid() async {
    final prefs = await SharedPreferences.getInstance();
    _myRidNo = prefs.getString('rid_no');

    print('MY RID → $_myRidNo');

    setState(() {});
  }

  /// =======================
  /// FETCH INVITES (GET)
  /// =======================
  Future<void> _fetchInvites() async {
    setState(() {
      _loadingInvites = true;
      _error = null;
    });

    try {
      final uri = Uri.parse(_invitesUrl);

      print('-----------------------------');
      print('GET REQUEST → $uri');

      final res = await http.get(uri);

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

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

      _invites = list
          .map((e) => InviteItem.fromMap(Map<String, dynamic>.from(e)))
          .where((e) => e.fullName.isNotEmpty)
          .toList();

      if (_invites.isNotEmpty) {
        _selectedInvite = _invites.first;
      }
    } catch (e) {
      _error = 'Failed to load members';
      print('ERROR FETCH INVITES → $e');
    }

    setState(() => _loadingInvites = false);
  }

  /// =======================
  /// SUBMIT REFERRAL (POST)
  /// =======================
  Future<void> _submit() async {
    if (!_formKey.currentState!.validate()) return;
    if (_selectedInvite == null) return;

    setState(() => _submitting = true);

    final payload = {
      'to': _selectedInvite!.ridNo,
      'to_name': _selectedInvite!.fullName,
      'name': _nameController.text.trim(),
      'details': _detailsController.text.trim(),
      'company_name': _companyNameController.text.trim(),
      'mobileNo': _mobileController.text.trim(),
      'email': _emailController.text.trim(),
      'rid_no': _myRidNo,
    };

    final uri = Uri.parse('$apiBaseUrl/referral_add.php');

    print('-----------------------------');
    print('POST REQUEST → $uri');
    print('PAYLOAD → ${jsonEncode(payload)}');

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

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

      if (!mounted) return;

      final body = jsonDecode(res.body);

      if ((res.statusCode == 200 || res.statusCode == 201) &&
          body['success'] == true) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content:
            Text(body['message'] ?? 'Referral added successfully'),
          ),
        );
        Navigator.pop(context, true);
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content:
            Text(body['message'] ?? 'Failed to add referral'),
          ),
        );
      }
    } catch (e) {
      print('SUBMIT ERROR → $e');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Something went wrong')),
      );
    } finally {
      if (mounted) setState(() => _submitting = false);
    }
  }

  /// =======================
  /// UI
  /// =======================
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: whiteColor,
        elevation: 0,
        centerTitle: true,
        title: const Text('REFERRAL', style: semibold18Black33),
      ),
      body: _loadingInvites
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
        padding: const EdgeInsets.all(fixPadding * 2),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('To', style: semibold14Black33),
              const SizedBox(height: 8),

              DropdownButtonFormField<InviteItem>(
                value: _selectedInvite,
                isExpanded: true,
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
                items: _invites.map((i) {
                  return DropdownMenuItem(
                    value: i,
                    child: Text(
                      i.displayText,
                      overflow: TextOverflow.ellipsis,
                    ),
                  );
                }).toList(),
                onChanged: (v) =>
                    setState(() => _selectedInvite = v),
                validator: (v) =>
                v == null ? 'Please select' : null,
              ),

              const SizedBox(height: fixPadding * 2),

              _field(_nameController, 'Name', Icons.person),
              _field(_detailsController, 'Details', Icons.info,
                  lines: 3),
              _field(_companyNameController, 'Company Name',
                  Icons.business),
              _field(_mobileController, 'Mobile No', Icons.phone),
              _field(_emailController, 'Email', Icons.email),

              const SizedBox(height: fixPadding * 3),

              if (_myRidNo != null && _myRidNo!.isNotEmpty)
                Text('Your RID: $_myRidNo',
                    style: medium14Black33),

              const SizedBox(height: fixPadding * 2),

              SizedBox(
                width: size.width,
                height: 48,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: primaryColor,
                    elevation: 0,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                  ),
                  onPressed: _submitting ? null : _submit,
                  child: _submitting
                      ? const SizedBox(
                    height: 18,
                    width: 18,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      color: Colors.white,
                    ),
                  )
                      : const Text('Save',
                      style: semibold18White),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _field(
      TextEditingController controller,
      String label,
      IconData icon, {
        int lines = 1,
      }) {
    return Padding(
      padding: const EdgeInsets.only(bottom: fixPadding),
      child: TextFormField(
        controller: controller,
        maxLines: lines,
        decoration: InputDecoration(
          labelText: label,
          prefixIcon: Icon(icon),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(10),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _nameController.dispose();
    _detailsController.dispose();
    _companyNameController.dispose();
    _mobileController.dispose();
    _emailController.dispose();
    super.dispose();
  }
}
