// lib/screens/referral/referrals.dart

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

import 'package:fl_sevengen_society_user_app/theme/theme.dart';
import 'package:fl_sevengen_society_user_app/api_constants.dart';

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

  @override
  State<ReferralsScreen> createState() => _ReferralsScreenState();
}

class _ReferralsScreenState extends State<ReferralsScreen> {
  final List<String> statusTabs = ['Under Process', 'Closed', 'Cancelled'];
  final List<String> statusDisplayTabs = ['Open', 'Closed', 'Cancelled'];

  int selectedType = 0; // 0 = Received, 1 = Given
  int selectedTab = 0;

  bool isLoading = false;
  bool isError = false;
  String? errorMessage;

  List<Map<String, dynamic>> referrals = [];
  String? ridNo;

  @override
  void initState() {
    super.initState();
    print('[Referrals] initState()');
    _loadRid();
  }

  Future<void> _loadRid() async {
    print('[Referrals] _loadRid() called');
    final prefs = await SharedPreferences.getInstance();
    final stored = prefs.getString('rid_no');
    print('[Referrals] stored rid_no = $stored');

    if (stored == null || stored.isEmpty) {
      if (!mounted) return;
      print('[Referrals] rid_no missing → navigate /login');
      Navigator.pushNamedAndRemoveUntil(context, '/login', (_) => false);
      return;
    }

    ridNo = stored;
    print('[Referrals] ridNo set to $ridNo, fetching referrals...');
    fetchReferrals();
  }

  Future<void> fetchReferrals() async {
    print(
        '[Referrals] fetchReferrals() type=$selectedType, tab=$selectedTab (${statusTabs[selectedTab]})');

    setState(() {
      isLoading = true;
      isError = false;
      errorMessage = null;
    });

    try {
      final uri = Uri.parse('$apiBaseUrl/referrals.php').replace(
        queryParameters: {
          'status': statusTabs[selectedTab],
        },
      );

      print('[Referrals] GET $uri');
      final res = await http.get(uri);
      print('[Referrals] Response ${res.statusCode} -> ${res.body}');

      final data = jsonDecode(res.body);

      if (res.statusCode == 200 && data['success'] == true) {
        final List raw = data['data'] ?? [];
        print('[Referrals] Total from server = ${raw.length}');

        final filtered = raw.where((item) {
          final to = (item['to'] ?? '').toString();
          final ridFromJson = (item['ridNo'] ?? '').toString();

          final match = selectedType == 0 ? (to == ridNo) : (ridFromJson == ridNo);
          print(
              '[Referrals]   item id=${item['id']} → to=$to ridNoField=$ridFromJson match=$match');
          return match;
        }).toList();

        print('[Referrals] Filtered count = ${filtered.length}');

        setState(() {
          referrals = List<Map<String, dynamic>>.from(filtered);
        });
      } else {
        print('[Referrals] Error from server: $data');
        setState(() {
          isError = true;
          errorMessage = data['message']?.toString() ?? 'Unknown error';
        });
      }
    } catch (e, st) {
      print('[Referrals] Exception: $e\n$st');
      setState(() {
        isError = true;
        errorMessage = e.toString();
      });
    } finally {
      setState(() => isLoading = false);
      print('[Referrals] fetchReferrals() finished');
    }
  }

  @override
  Widget build(BuildContext context) {
    print('[Referrals] build() referrals=${referrals.length}');
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Referral',
          style: TextStyle(
            fontSize: 18,
            color: Colors.white,
            fontWeight: FontWeight.w600,
          ),
        ),
        backgroundColor: primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: Column(
        children: [
          _tabs(),
          Expanded(child: _body()),
        ],
      ),
      bottomNavigationBar: _bottomButton(),
    );
  }

  // ================= TABS =================

  Widget _tabs() {
    return Padding(
      padding: const EdgeInsets.all(fixPadding),
      child: Column(
        children: [
          Row(
            children: [
              _typeTab('Received', 0),
              _typeTab('Given', 1),
            ],
          ),
          const SizedBox(height: 12),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: List.generate(3, (i) {
              return GestureDetector(
                onTap: () {
                  print('[Referrals] status tab changed -> $i');
                  selectedTab = i;
                  fetchReferrals();
                  setState(() {});
                },
                child: Column(
                  children: [
                    Text(
                      statusDisplayTabs[i],
                      style:
                      selectedTab == i ? semibold16Black33 : semibold16Grey,
                    ),
                    if (selectedTab == i)
                      Container(
                        height: 2,
                        width: 30,
                        color: primaryColor,
                      ),
                  ],
                ),
              );
            }),
          ),
        ],
      ),
    );
  }

  Widget _typeTab(String text, int index) {
    final selected = selectedType == index;
    return Expanded(
      child: InkWell(
        onTap: () {
          print('[Referrals] type tab changed -> $index ($text)');
          selectedType = index;
          fetchReferrals();
          setState(() {});
        },
        child: Container(
          height: 44,
          margin: const EdgeInsets.symmetric(horizontal: 4),
          decoration: BoxDecoration(
            color: selected ? primaryColor : whiteColor,
            borderRadius: BorderRadius.circular(30),
            border: Border.all(color: primaryColor),
          ),
          alignment: Alignment.center,
          child: Text(
            text,
            style: selected ? semibold16White : semibold16Grey,
          ),
        ),
      ),
    );
  }

  // ================= BODY =================

  Widget _body() {
    if (isLoading) {
      return const Center(child: CircularProgressIndicator());
    }
    if (isError) {
      return Center(child: Text(errorMessage ?? 'Error'));
    }
    if (referrals.isEmpty) {
      return const Center(child: Text('No Referrals Found'));
    }

    return ListView.builder(
      itemCount: referrals.length,
      itemBuilder: (_, i) => _referralCard(referrals[i]),
    );
  }

  // ================= CARD =================

  Widget _referralCard(Map<String, dynamic> item) {
    final int id = int.parse(item['id'].toString());
    final String name = item['name'] ?? '';
    final String status = item['status'] ?? '';
    final String date = item['dateOfReferral'] ?? '';

    final String gridNoName = item['gridNoName']?.toString() ?? '';
    final String toMembersNames = item['toMembersNames']?.toString() ?? '';

    print('[Referrals] build card id=$id name=$name status=$status');

    return InkWell(
      onTap: () {
        print('[Referrals] card tapped id=$id');
        _showDetailsBottomSheet(item);
      },
      child: Container(
        margin: const EdgeInsets.all(12),
        child: Stack(
          children: [
            Container(
              constraints: const BoxConstraints(minHeight: 96),
              padding: const EdgeInsets.symmetric(
                horizontal: 16,
                vertical: 14,
              ),
              decoration: BoxDecoration(
                color: whiteColor,
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: shadowColor.withOpacity(0.15),
                    blurRadius: 8,
                  ),
                ],
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  CircleAvatar(
                    radius: 22,
                    child: Text(
                      (toMembersNames.isNotEmpty
                          ? toMembersNames[0]
                          : name.isNotEmpty
                          ? name[0]
                          : 'R')
                          .toUpperCase(),
                    ),
                  ),
                  const SizedBox(width: 14),
                  Expanded(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // TOP: to_members_names
                        Text(
                          toMembersNames.isNotEmpty
                              ? toMembersNames
                              : '(No receiver)',
                          style: semibold16Black33,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 4),
                        // MIDDLE: original name
                        Text(
                          name,
                          style: medium14Grey,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 4),
                        Text(
                          date,
                          style: medium14Grey,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        const SizedBox(height: 4),
                        // BOTTOM: given by grid_no_name (primary color, 16)
                        Text(
                          'Given by : ${gridNoName.isNotEmpty ? gridNoName : '-'}',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 16,
                            color: primaryColor,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                  ),
                  if (selectedType == 0 && status == 'Under Process')
                    PopupMenuButton<String>(
                      onSelected: (v) {
                        print('[Referrals] menu selected=$v id=$id');
                        if (v == 'close') {
                          _showCloseDialog(id);
                        } else if (v == 'cancel') {
                          _showCancelDialog(id);
                        }
                      },
                      itemBuilder: (_) => const [
                        PopupMenuItem(
                          value: 'close',
                          child: Text('Close'),
                        ),
                        PopupMenuItem(
                          value: 'cancel',
                          child: Text('Cancel'),
                        ),
                      ],
                    ),
                ],
              ),
            ),
            Positioned(
              top: 8,
              right: 8,
              child: _statusPill(status),
            ),
          ],
        ),
      ),
    );
  }

  // ================= STATUS PILL =================

  Widget _statusPill(String status) {
    Color bg;
    IconData icon;
    String text;

    switch (status) {
      case 'Closed':
        bg = green3EColor;
        icon = Icons.check;
        text = 'Closed';
        break;
      case 'Cancelled':
        bg = lightRedColor;
        icon = Icons.close;
        text = 'Cancelled';
        break;
      default:
        bg = const Color(0xFFFFC940);
        icon = Icons.auto_awesome;
        text = 'Open';
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      decoration: BoxDecoration(
        color: bg,
        borderRadius: BorderRadius.circular(20),
      ),
      child: Row(
        children: [
          Icon(icon, size: 14, color: whiteColor),
          const SizedBox(width: 4),
          Text(text, style: semibold14White),
        ],
      ),
    );
  }

  // ================= DETAILS (BOTTOM SHEET) =================

  Future<void> _showDetailsBottomSheet(Map<String, dynamic> item) async {
    print('[Referrals] show details bottom sheet for id=${item['id']}');

    final String gridNoName = item['gridNoName']?.toString() ?? '';
    final String toMembersNames = item['toMembersNames']?.toString() ?? '';

    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(30)),
      ),
      builder: (_) {
        return Padding(
          padding: const EdgeInsets.all(fixPadding * 2),
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _detailRow(Icons.person_outline, 'To Member', toMembersNames),
                _detailRow(Icons.person, 'Given By', gridNoName),
                _detailRow(
                    Icons.badge_outlined, 'Referral Name', item['name']),
                _detailRow(
                    Icons.info_outline, 'Details', item['details'] as String?),
                _detailRow(Icons.apartment_outlined, 'Business',
                    item['businessName'] as String?),
                _detailRow(Icons.phone_outlined, 'Mobile',
                    item['mobileNo'] as String?),
                _detailRow(
                    Icons.mail_outline, 'Email', item['email'] as String?),
                const SizedBox(height: 16),
                SizedBox(
                  width: double.infinity,
                  child: OutlinedButton(
                    onPressed: () {
                      print('[Referrals] bottom sheet close pressed');
                      Navigator.pop(context);
                    },
                    child: const Text('Close'),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _detailRow(IconData icon, String label, String? text) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, size: 20),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(label,
                    style: const TextStyle(
                        fontSize: 12, fontWeight: FontWeight.w600)),
                const SizedBox(height: 2),
                Text(
                  text?.isNotEmpty == true ? text! : '-',
                  style: const TextStyle(fontSize: 14),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ================= CLOSE =================

  Future<void> _showCloseDialog(int id) async {
    print('[Referrals] show close dialog id=$id');
    final controller = TextEditingController();

    await showDialog(
      context: context,
      builder: (_) => Dialog(
        shape:
        RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('Closing Referral', style: semibold18Black33),
              const SizedBox(height: 12),
              TextField(
                controller: controller,
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(hintText: 'Amount'),
              ),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  TextButton(
                    onPressed: () {
                      print('[Referrals] close dialog cancel');
                      Navigator.pop(context);
                    },
                    child: const Text('Cancel'),
                  ),
                  TextButton(
                    onPressed: () async {
                      print(
                          '[Referrals] close dialog save, amount=${controller.text}');
                      await _closeReferralApi(id, controller.text);
                      Navigator.pop(context);
                      fetchReferrals();
                    },
                    child: const Text('Save'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // ================= CANCEL =================

  Future<void> _showCancelDialog(int id) async {
    print('[Referrals] show cancel dialog id=$id');
    final controller = TextEditingController();

    await showDialog(
      context: context,
      builder: (_) => Dialog(
        shape:
        RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('Cancelling Referral', style: semibold18Black33),
              const SizedBox(height: 12),
              TextField(
                controller: controller,
                maxLines: 4,
                decoration: const InputDecoration(hintText: 'Reason'),
              ),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  TextButton(
                    onPressed: () {
                      print('[Referrals] cancel dialog cancel');
                      Navigator.pop(context);
                    },
                    child: const Text('Cancel'),
                  ),
                  TextButton(
                    onPressed: () async {
                      print(
                          '[Referrals] cancel dialog save, reason=${controller.text}');
                      await _cancelReferralApi(id, controller.text);
                      Navigator.pop(context);
                      fetchReferrals();
                    },
                    child: const Text('Save'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // ================= API =================

  Future<void> _closeReferralApi(int id, String amount) async {
    final uri = Uri.parse('$apiBaseUrl/referral_close.php');
    print('[Referrals] POST $uri id=$id amount=$amount');
    final res = await http.post(
      uri,
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({'id': id, 'amount': amount}),
    );
    print('[Referrals] closeReferralApi response ${res.statusCode} -> ${res.body}');
  }

  Future<void> _cancelReferralApi(int id, String reason) async {
    final uri = Uri.parse('$apiBaseUrl/referral_cancel.php');
    print('[Referrals] POST $uri id=$id reason=$reason');
    final res = await http.post(
      uri,
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({'id': id, 'reason': reason}),
    );
    print(
        '[Referrals] cancelReferralApi response ${res.statusCode} -> ${res.body}');
  }

  // ================= BOTTOM BUTTON =================

  Widget _bottomButton() {
    return SafeArea(
      child: InkWell(
        borderRadius: BorderRadius.circular(10),
        onTap: () async {
          print('[Referrals] Add Referral button tapped');
          final result = await Navigator.pushNamed(
            context,
            '/addReferral',
            arguments: {'rid_no': ridNo},
          );
          print('[Referrals] Add Referral result = $result');
          if (result == true) fetchReferrals();
        },
        child: Container(
          margin: const EdgeInsets.all(16),
          height: 48,
          decoration: BoxDecoration(
            color: primaryColor,
            borderRadius: BorderRadius.circular(10),
          ),
          alignment: Alignment.center,
          child: const Text(
            'Add Referral',
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
      ),
    );
  }
}
