import 'dart:convert';

import 'package:dotted_border/dotted_border.dart';
import 'package:fl_sevengen_society_user_app/localization/localization_const.dart';
import 'package:fl_sevengen_society_user_app/theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

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

  @override
  State<PaymentScreen> createState() => _PaymentScreenState();
}

class _PaymentScreenState extends State<PaymentScreen> {
  final String baseUrl = 'https://www.rmbferodeunited.in/api/payment.php';

  bool isLoading = false;
  String? ridNo;
  List<Map<String, dynamic>> paymentList = [];

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

  Future<void> _loadRidNoAndFetch() async {
    setState(() => isLoading = true);
    final prefs = await SharedPreferences.getInstance();
    ridNo = prefs.getString('rid_no');

    print('Loaded rid_no from SharedPreferences: $ridNo');

    if (ridNo == null || ridNo!.isEmpty) {
      print('rid_no is null/empty, cannot fetch payments');
      setState(() => isLoading = false);
      return;
    }

    await fetchPayments();
  }

  Future<void> fetchPayments() async {
    if (ridNo == null) return;

    final uri = Uri.parse('$baseUrl?rid_no=$ridNo');

    print('==== FETCH PAYMENTS ====');
    print('REQUEST METHOD: GET');
    print('REQUEST URL: $uri');

    try {
      final response = await http.get(uri);

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

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        print('DECODED DATA: $data');

        final List list = data is List ? data : (data['data'] ?? []);

        paymentList = list.map<Map<String, dynamic>>((e) {
          final status = _statusFromApi(e);
          final type = _typeFromApi(e);
          final amount = _amountFromApi(e);

          return {
            'rid_no': e['rid_no'],
            'name': e['name'] ?? '',
            'type': type,
            'price': '₹$amount',
            'date': e['created_at'] ?? '',
            'status': status,
            'color': _colorFromStatus(status),
          };
        }).toList();

        print('MAPPED paymentList: $paymentList');
      } else {
        print('ERROR: Unexpected status code ${response.statusCode}');
      }
    } catch (e) {
      print('EXCEPTION in fetchPayments: $e');
    } finally {
      if (mounted) {
        setState(() => isLoading = false);
      }
    }
  }

  String _statusFromApi(Map<String, dynamic> e) {
    final raw = (e['uniform_con_pay_status'] ?? '').toString();
    final status = raw.toLowerCase();
    if (status == 'paid') return 'Paid';
    if (status == 'pending') return 'Pending';
    if (status == 'failed') return 'Failed';
    return 'Pending';
  }

  String _typeFromApi(Map<String, dynamic> e) {
    final uniform = num.tryParse('${e['uniform_con_pay'] ?? 0}') ?? 0;
    final phone   = num.tryParse('${e['phone_con_pay'] ?? 0}') ?? 0;
    final speak   = num.tryParse('${e['speak_con_pay'] ?? 0}') ?? 0;

    if (uniform > 0 && phone == 0 && speak == 0) return 'Uniform';
    if (phone > 0 && uniform == 0 && speak == 0) return 'Phone';
    if (speak > 0 && uniform == 0 && phone == 0) return 'Speak';

    if (uniform > 0) return 'Uniform';
    if (phone > 0) return 'Phone';
    if (speak > 0) return 'Speak';
    return '';
  }

  num _amountFromApi(Map<String, dynamic> e) {
    final uniform = num.tryParse('${e['uniform_con_pay'] ?? 0}') ?? 0;
    final phone   = num.tryParse('${e['phone_con_pay'] ?? 0}') ?? 0;
    final speak   = num.tryParse('${e['speak_con_pay'] ?? 0}') ?? 0;

    if (uniform > 0 && phone == 0 && speak == 0) return uniform;
    if (phone > 0 && uniform == 0 && speak == 0) return phone;
    if (speak > 0 && uniform == 0 && phone == 0) return speak;

    return uniform + phone + speak;
  }

  Color _colorFromStatus(String status) {
    switch (status) {
      case 'Paid':
        return lightGreenColor;
      case 'Failed':
        return lightRedColor;
      default:
        return orangeColor;
    }
  }

  Future<void> _payNow(int index) async {
    final item = paymentList[index];

    final bodyMap = {
      'rid_no': item['rid_no'],
      'uniform_con_pay_status': 'paid',
    };

    final uri = Uri.parse(baseUrl);
    final body = jsonEncode(bodyMap);

    print('==== PAY NOW ====');
    print('REQUEST METHOD: POST');
    print('REQUEST URL: $uri');
    print('REQUEST HEADERS: ${{'Content-Type': 'application/json'} }');
    print('REQUEST BODY MAP: $bodyMap');
    print('REQUEST BODY JSON: $body');

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

      print('RESPONSE STATUS: ${res.statusCode}');
      print('RESPONSE BODY: ${res.body}');

      final json = jsonDecode(res.body);
      print('DECODED RESPONSE: $json');

      if (res.statusCode == 200 && json['success'] == true) {
        setState(() {
          paymentList[index]['status'] = 'Paid';
          paymentList[index]['color'] = _colorFromStatus('Paid');
        });
        print('UPDATE LOCAL ITEM: index=$index set to Paid');
      } else {
        print('ERROR IN PAYMENT: ${json['message']}');
      }
    } catch (e) {
      print('EXCEPTION in _payNow: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: primaryColor,
        elevation: 0.0,
        titleSpacing: 0.0,
        centerTitle: false,
        automaticallyImplyLeading: false,
        leading: IconButton(
          onPressed: () {
            Navigator.pop(context);
          },
          icon: const Icon(
            Icons.arrow_back,
            color: Colors.white,
          ),
        ),
        title: Text(
          getTranslate(context, 'payment.payment'),
          style: const TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
      body: isLoading
          ? const Center(child: CircularProgressIndicator())
          : paymentListContent(),
    );
  }

  Widget paymentListContent() {
    return ListView.builder(
      physics: const BouncingScrollPhysics(),
      padding: const EdgeInsets.only(bottom: fixPadding),
      itemCount: paymentList.length,
      itemBuilder: (context, index) {
        final item = paymentList[index];
        return Container(
          clipBehavior: Clip.hardEdge,
          margin: const EdgeInsets.symmetric(
              horizontal: fixPadding * 2.0, vertical: fixPadding),
          width: double.maxFinite,
          decoration: BoxDecoration(
            color: whiteColor,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: [
              BoxShadow(
                color: shadowColor.withOpacity(0.25),
                blurRadius: 6.0,
              )
            ],
          ),
          child: Column(
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(
                          horizontal: fixPadding * 1.5,
                          vertical: fixPadding * 1.4),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text(
                              item['name'].toString(),
                              style: semibold16Primary,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          if ((item['type'] ?? '').toString().isNotEmpty)
                            Text(
                              ' ${item['type']}',
                              style: medium14Black33,
                              overflow: TextOverflow.ellipsis,
                            ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              DottedBorder(
                padding: EdgeInsets.zero,
                color: greyColor,
                dashPattern: const [2.5, 4.5],
                child: Container(
                  width: double.maxFinite,
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(fixPadding * 1.5),
                child: Row(
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            item['price'].toString(),
                            style: medium16Black33,
                            overflow: TextOverflow.ellipsis,
                          ),
                          height5Space,
                          Text(
                            "${getTranslate(context, 'payment.due_date')} : ${item['date']}",
                            style: medium14Black33,
                            overflow: TextOverflow.ellipsis,
                          )
                        ],
                      ),
                    ),
                    item['status'] == "Paid"
                        ? Row(
                      children: [
                        const Icon(
                          Icons.list_alt,
                          color: primaryColor,
                          size: 16,
                        ),
                        width5Space,
                        Text(
                          getTranslate(context, 'payment.receipt'),
                          style: semibold14Primary,
                        )
                      ],
                    )
                        : const SizedBox(),
                  ],
                ),
              ),
              item['status'] == "Paid"
                  ? Container(
                padding: const EdgeInsets.all(fixPadding),
                decoration: BoxDecoration(
                  color: item['color'] as Color,
                ),
                alignment: Alignment.center,
                child: Text(
                  item['status'].toString(),
                  style: semibold16White,
                  overflow: TextOverflow.ellipsis,
                ),
              )
                  : Padding(
                padding: const EdgeInsets.only(
                    left: fixPadding * 1.5,
                    right: fixPadding * 1.5,
                    bottom: fixPadding * 1.5),
                child: SizedBox(
                  width: double.infinity,
                  height: 44,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: primaryColor,
                      foregroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                    ),
                    onPressed: () {
                      print(
                          'PAY NOW TAP: index=$index, status=${item['status']}');
                      _payNow(index);
                      Navigator.pushNamed(context, '/paymentMethods');
                    },
                    child: Text(
                      getTranslate(context, 'payment.pay_now'),
                      style: semibold16White,
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
