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 EventDisplay extends StatefulWidget {
  const EventDisplay({super.key});

  @override
  State<EventDisplay> createState() => _EventDisplayState();
}

class _EventDisplayState extends State<EventDisplay> {
  bool _loading = true;
  String? _error;
  List<Map<String, dynamic>> eventList = [];

  final String apiUrl = 'https://rmbferodeunited.in/api/get_events.php';
  final String acceptApiUrl = 'https://rmbferodeunited.in/api/accept_events.php';

  String? _ridNo;

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

  Future<void> _initScreen() async {
    print('EVENT_DISPLAY: _initScreen started');

    final prefs = await SharedPreferences.getInstance();
    final savedRidNo = prefs.getString('rid_no');
    print('EVENT_DISPLAY: savedRidNo=$savedRidNo');

    if (savedRidNo == null || savedRidNo.trim().isEmpty) {
      print('EVENT_DISPLAY: No RID found, redirecting to login');
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!mounted) return;
        Navigator.pushNamedAndRemoveUntil(
          context,
          '/login',
              (route) => false,
        );
      });
      return;
    }

    setState(() {
      _ridNo = savedRidNo.trim();
    });

    print('EVENT_DISPLAY_INIT: rid_no=$_ridNo');

    await fetchEvents();
  }

  Future<void> fetchEvents() async {
    print('FETCH_EVENTS: Started with rid_no=$_ridNo');

    if (_ridNo == null || _ridNo!.trim().isEmpty) {
      print('FETCH_EVENTS: RID missing, setting error');
      setState(() {
        _loading = false;
        _error = 'RID number missing. Please login again.';
      });

      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!mounted) return;
        Navigator.pushNamedAndRemoveUntil(
          context,
          '/login',
              (route) => false,
        );
      });
      return;
    }

    setState(() {
      _loading = true;
      _error = null;
    });

    try {
      final uri = Uri.parse(apiUrl);
      print('FETCH_EVENTS: URL=$apiUrl');

      final requestBody = {
        'rid_no': _ridNo!,
      };

      print('GET_EVENTS_REQUEST: URL=$apiUrl');
      print('GET_EVENTS_REQUEST: Headers=${requestBody.keys.toList()}');
      print('GET_EVENTS_REQUEST: Body=${jsonEncode(requestBody)}');

      final res = await http
          .post(
        uri,
        body: requestBody,
      )
          .timeout(const Duration(seconds: 15));

      print('GET_EVENTS_RESPONSE: status=${res.statusCode}');
      print('GET_EVENTS_RESPONSE: headers=${res.headers}');
      print('GET_EVENTS_RESPONSE: body=${res.body}');

      if (res.statusCode != 200) {
        print('GET_EVENTS_RESPONSE: Non-200 status, setting error');
        setState(() {
          _error = 'Server returned ${res.statusCode}';
          _loading = false;
        });
        return;
      }

      final body = json.decode(res.body);
      print('GET_EVENTS_RESPONSE: parsed_body=${jsonEncode(body)}');

      if (body is Map && body['success'] == true && body['data'] is List) {
        final List data = body['data'];
        print('GET_EVENTS_RESPONSE: data_count=${data.length}');

        final filteredData = data.where((item) {
          final rawStatus = (item['status'] ?? '').toString().trim().toLowerCase();
          return rawStatus.isEmpty ||
              rawStatus == 'pending' ||
              rawStatus == 'scheduled' ||
              rawStatus == 'accepted';
        }).toList();

        print('GET_EVENTS_RESPONSE: filtered_count=${filteredData.length}');

        eventList = filteredData.map<Map<String, dynamic>>((item) {
          final eventId = (item['event_id'] ?? item['id'] ?? '').toString();
          final banner = (item['banner'] ?? '').toString();
          final eventName = (item['event_name'] ?? item['name'] ?? 'No title').toString();
          final startDate = (item['start_date'] ?? '').toString();
          final endDate = (item['end_date'] ?? '').toString();
          final startTime = (item['start_time'] ?? '').toString();
          final endTime = (item['end_time'] ?? '').toString();
          final venue = (item['venue'] ?? '').toString();
          final location = (item['location'] ?? '').toString();
          final chiefGuest = (item['chief_guest'] ?? '').toString();
          final companyName = (item['company_name'] ?? '').toString();
          final status = (item['status'] ?? '').toString();
          final notes = (item['notes'] ?? '').toString();

          final pollStatus = (item['poll_status'] ?? '').toString();
          final foodPref = (item['food_pref'] ?? '').toString();

          String type = 'Regular event';
          if (status.isNotEmpty) {
            type = status;
          } else if (companyName.isNotEmpty) {
            type = companyName;
          }

          final mappedItem = {
            'event_id': eventId,
            'image': banner,
            'name': eventName,
            'start_date': startDate,
            'end_date': endDate,
            'start_time': startTime,
            'end_time': endTime,
            'venue': venue,
            'location': location,
            'chief_guest': chiefGuest,
            'company_name': companyName,
            'status': status,
            'notes': notes,
            'type': type,
            'poll_status': pollStatus,
            'food_pref': foodPref,
          };

          print('FETCH_EVENTS: mapped_item=$eventId: ${jsonEncode(mappedItem)}');
          return mappedItem;
        }).toList();

        print('FETCH_EVENTS: Total processed=${eventList.length}');
        setState(() {
          _loading = false;
        });
      } else {
        print('FETCH_EVENTS: Invalid response format');
        setState(() {
          _error = body is Map
              ? (body['message'] ?? 'Unexpected response format')
              : 'Unexpected response format';
          _loading = false;
        });
      }
    } catch (e) {
      print('FETCH_EVENTS: Exception=$e');
      setState(() {
        _error = 'Failed to fetch: $e';
        _loading = false;
      });
    }
  }

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

    return Scaffold(
      backgroundColor: whiteColor,
      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, 'events.Event') ?? 'Event',
          style: const TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
      body: _buildEventsBody(size),
    );
  }

  Widget _buildEventsBody(Size size) {
    if (_loading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_error != null) {
      print('BUILD_EVENTS_BODY: Showing error=$_error');
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(fixPadding * 2.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                'Error: $_error',
                style: semibold16Black33,
                textAlign: TextAlign.center,
              ),
              heightSpace,
              ElevatedButton(
                onPressed: fetchEvents,
                child: Text(getTranslate(context, 'common.retry') ?? 'Retry'),
              )
            ],
          ),
        ),
      );
    }

    print('BUILD_EVENTS_BODY: eventList_count=${eventList.length}');
    return eventList.isEmpty
        ? emptyListContent()
        : eventsListContent(size);
  }

  Widget emptyListContent() {
    print('EMPTY_LIST_CONTENT: Showing empty state');
    return Center(
      child: ListView(
        shrinkWrap: true,
        physics: const BouncingScrollPhysics(),
        padding: const EdgeInsets.all(fixPadding * 2.0),
        children: [
          Image.asset(
            "assets/home/visitor.png",
            height: 70,
          ),
          heightSpace,
          Text(
            getTranslate(context, 'events.no_events_yet') ?? 'No events yet',
            style: semibold18Grey,
            textAlign: TextAlign.center,
          )
        ],
      ),
    );
  }

  Widget eventsListContent(Size size) {
    print('EVENTS_LIST_CONTENT: Building list with ${eventList.length} items');
    return RefreshIndicator(
      onRefresh: fetchEvents,
      child: ListView.builder(
        physics: const BouncingScrollPhysics(),
        padding: const EdgeInsets.fromLTRB(
            fixPadding * 2.0, 0.0, fixPadding * 2.0, fixPadding),
        itemCount: eventList.length,
        itemBuilder: (context, index) {
          print('EVENTS_LIST_CONTENT: Building item $index');
          return _buildEventCard(size, index);
        },
      ),
    );
  }

  Widget _buildEventCard(Size size, int index) {
    final item = eventList[index];
    print('BUILD_EVENT_CARD: index=$index, item=${jsonEncode(item)}');

    final imageUrl = (item['image'] ?? '').toString();
    final name = (item['name'] ?? '').toString();
    final startDate = (item['start_date'] ?? '').toString();
    final endDate = (item['end_date'] ?? '').toString();
    final startTime = (item['start_time'] ?? '').toString();
    final endTime = (item['end_time'] ?? '').toString();
    final type = (item['type'] ?? 'Regular event').toString();
    final venue = (item['venue'] ?? '').toString();
    final location = (item['location'] ?? '').toString();
    final chiefGuest = (item['chief_guest'] ?? '').toString();
    final companyName = (item['company_name'] ?? '').toString();

    final venueLocationText = _buildVenueLocationString(venue, location);
    final dateTimeText = _buildDateTimeRange(startDate, startTime, endDate, endTime);

    final rawPollStatus = (item['poll_status'] ?? '').toString().trim().toLowerCase();
    print('BUILD_EVENT_CARD: rawPollStatus=$rawPollStatus');

    final bool isAccepted = rawPollStatus == 'accepted';
    final bool isPending = !isAccepted && (rawPollStatus.isEmpty || rawPollStatus == 'pending');
    final bool isAttending = rawPollStatus == 'attending';
    final bool isNotAttending = rawPollStatus == 'not_attending';

    String buttonText;
    Color buttonColor;
    bool buttonEnabled;

    if (isAccepted) {
      buttonText = getTranslate(context, 'events.accepted') ?? 'Accepted';
      buttonColor = Colors.green;
      buttonEnabled = false;
    } else if (isPending) {
      buttonText = getTranslate(context, 'events.accept_event') ?? 'Respond / Accept';
      buttonColor = primaryColor;
      buttonEnabled = true;
    } else if (isAttending) {
      buttonText = getTranslate(context, 'events.attending') ?? 'Attending';
      buttonColor = Colors.green;
      buttonEnabled = false;
    } else if (isNotAttending) {
      buttonText = getTranslate(context, 'events.not_attending') ?? 'Not Attending';
      buttonColor = Colors.red;
      buttonEnabled = false;
    } else {
      buttonText = rawPollStatus.toUpperCase();
      buttonColor = Colors.grey;
      buttonEnabled = false;
    }

    print('BUILD_EVENT_CARD: buttonText=$buttonText, enabled=$buttonEnabled');

    return Container(
      margin: const EdgeInsets.symmetric(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: [
          Padding(
            padding: const EdgeInsets.all(fixPadding),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: size.height * 0.1,
                  width: size.height * 0.1,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5.0),
                    image: imageUrl.isNotEmpty
                        ? DecorationImage(
                      image: NetworkImage(imageUrl),
                      fit: BoxFit.cover,
                    )
                        : const DecorationImage(
                      image: AssetImage("assets/members/member12.png"),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                widthSpace,
                width5Space,
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        name,
                        style: medium16Black33,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      if (companyName.isNotEmpty || chiefGuest.isNotEmpty) ...[
                        height5Space,
                        Text(
                          _buildSubtitle(companyName, chiefGuest),
                          style: medium14Grey,
                          softWrap: true,
                        ),
                      ],
                      if (dateTimeText.isNotEmpty) ...[
                        height5Space,
                        Text(
                          dateTimeText,
                          style: medium14Grey,
                          softWrap: true,
                        ),
                      ],
                      height5Space,
                      Text(
                        type,
                        style: medium15White.copyWith(
                          decoration: TextDecoration.underline,
                          color: lightRedColor,
                        ),
                      ),
                      if (venueLocationText.isNotEmpty) ...[
                        height5Space,
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            const Icon(
                              Icons.place,
                              size: 16,
                              color: Colors.grey,
                            ),
                            width5Space,
                            Expanded(
                              child: Text(
                                venueLocationText,
                                style: medium14Grey,
                                softWrap: true,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ],
                  ),
                )
              ],
            ),
          ),
          DottedBorder(
            padding: EdgeInsets.zero,
            color: greyColor,
            dashPattern: const [2, 5],
            child: Container(),
          ),
          Padding(
            padding: const EdgeInsets.all(fixPadding),
            child: Row(
              children: [
                Expanded(
                  child: GestureDetector(
                    onTap: !buttonEnabled
                        ? null
                        : () {
                      print('BUTTON_TAP: acceptEvent called for index=$index');
                      acceptEvent(index);
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: fixPadding * 0.9),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8.0),
                        color: buttonColor,
                        boxShadow: [
                          if (buttonEnabled)
                            BoxShadow(
                              color: buttonColor.withOpacity(0.2),
                              blurRadius: 8.0,
                              offset: const Offset(0, 4),
                            )
                        ],
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        buttonText,
                        style: buttonEnabled ? semibold18White : semibold16White,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  String _buildVenueLocationString(String venue, String location) {
    final v = venue.trim();
    final l = location.trim();
    if (v.isEmpty && l.isEmpty) return '';
    if (v.isEmpty) return '($l)';
    if (l.isEmpty) return '($v)';
    return '($v, $l)';
  }

  String _buildDateTimeRange(String startDate, String startTime, String endDate, String endTime) {
    final sDate = startDate.trim();
    final eDate = endDate.trim();
    final sTime = startTime.trim();
    final eTime = endTime.trim();

    String start = '';
    String end = '';

    if (sDate.isNotEmpty && sTime.isNotEmpty) {
      start = '$sDate, $sTime';
    } else if (sDate.isNotEmpty) {
      start = sDate;
    } else if (sTime.isNotEmpty) {
      start = sTime;
    }

    if (eDate.isNotEmpty && eTime.isNotEmpty) {
      end = '$eDate, $eTime';
    } else if (eDate.isNotEmpty) {
      end = eDate;
    } else if (eTime.isNotEmpty) {
      end = eTime;
    }

    if (start.isEmpty && end.isEmpty) return '';
    if (start.isEmpty) return end;
    if (end.isEmpty) return start;
    if (start == end) return start;
    return '$start → $end';
  }

  String _buildSubtitle(String companyName, String chiefGuest) {
    if (companyName.isEmpty && chiefGuest.isEmpty) return '';
    if (companyName.isEmpty) return chiefGuest;
    if (chiefGuest.isEmpty) return companyName;
    return '$companyName • $chiefGuest';
  }

  void acceptEvent(int index) {
    print('ACCEPT_EVENT: Started for index=$index');
    final eventId = (eventList[index]['event_id'] ?? '').toString();
    print('ACCEPT_EVENT_OPEN: event_id=$eventId');

    String pollStatus = 'attending';
    String foodPref = 'veg';
    String nomem = '';

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (context) {
        return Padding(
          padding: MediaQuery.of(context).viewInsets,
          child: StatefulBuilder(
            builder: (context, setModalState) {
              return Padding(
                padding: const EdgeInsets.all(fixPadding * 2),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      getTranslate(context, 'events.confirm') ?? 'Confirm Response',
                      style: semibold18Black33,
                    ),
                    const SizedBox(height: 16),

                    // Acceptance
                    Text('Acceptance', style: semibold16Black33),
                    Row(
                      children: [
                        Radio<String>(
                          value: 'attending',
                          groupValue: pollStatus,
                          onChanged: (v) {
                            print('MODAL: Acceptance changed to $v');
                            setModalState(() => pollStatus = v!);
                          },
                        ),
                        const Text('Attending'),
                        const SizedBox(width: 16),
                        Radio<String>(
                          value: 'not_attending',
                          groupValue: pollStatus,
                          onChanged: (v) {
                            print('MODAL: Acceptance changed to $v');
                            setModalState(() => pollStatus = v!);
                          },
                        ),
                        const Text('Not Attending'),
                      ],
                    ),
                    const SizedBox(height: 8),

                    // Food preferred
                    Text('Food Preferred', style: semibold16Black33),
                    Row(
                      children: [
                        Radio<String>(
                          value: 'veg',
                          groupValue: foodPref,
                          onChanged: (v) {
                            print('MODAL: Food pref changed to $v');
                            setModalState(() => foodPref = v!);
                          },
                        ),
                        const Expanded(child: Text('Veg')),
                        const SizedBox(width: 16),
                        Radio<String>(
                          value: 'non_veg',
                          groupValue: foodPref,
                          onChanged: (v) {
                            print('MODAL: Food pref changed to $v');
                            setModalState(() => foodPref = v!);
                          },
                        ),
                        const Expanded(child: Text('Non-Veg')),
                      ],
                    ),
                    // Number of members textbox - ONLY for Veg
                    if (foodPref == 'veg') ...[
                      const SizedBox(height: 8),
                      Text('No. of People', style: semibold16Black33),
                      const SizedBox(height: 8),
                      TextField(
                        keyboardType: TextInputType.number,
                        decoration: InputDecoration(
                          hintText: 'Enter number of members',
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          contentPadding: const EdgeInsets.symmetric(
                            horizontal: 12,
                            vertical: 12,
                          ),
                        ),
                        onChanged: (value) {
                          print('MODAL: nomem changed to $value');
                          setModalState(() {
                            nomem = value.trim();
                          });
                        },
                      ),
                    ],
                    const SizedBox(height: 20),

                    // Submit button
                    SizedBox(
                      width: double.infinity,
                      child: GestureDetector(
                        onTap: () async {
                          print('MODAL_SUBMIT: Submitting with pollStatus=$pollStatus, foodPref=$foodPref, nomem=$nomem');
                          Navigator.pop(context);
                          await _submitEventResponse(
                            index: index,
                            eventId: eventId,
                            pollStatus: pollStatus,
                            foodPref: foodPref,
                            nomem: nomem,
                          );
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(vertical: fixPadding * 0.9),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8.0),
                            color: primaryColor,
                            boxShadow: [
                              BoxShadow(
                                color: primaryColor.withOpacity(0.1),
                                blurRadius: 8.0,
                                offset: const Offset(0, 4),
                              )
                            ],
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            getTranslate(context, 'events.accept_event') ?? 'Accept Event',
                            style: semibold18White,
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),
                  ],
                ),
              );
            },
          ),
        );
      },
    );
  }

  Future<void> _submitEventResponse({
    required int index,
    required String eventId,
    required String pollStatus,
    required String foodPref,
    required String nomem,
  }) async {
    print('SUBMIT_EVENT_RESPONSE: Started for event_id=$eventId');

    if (_ridNo == null || _ridNo!.isEmpty) {
      print('SUBMIT_EVENT_RESPONSE: RID missing');
      _showSnack('Please login again.', isError: true);
      if (!mounted) return;
      Navigator.pushNamedAndRemoveUntil(
        context,
        '/login',
            (route) => false,
      );
      return;
    }

    final requestBody = {
      'event_id': eventId,
      'rid_no': _ridNo!,
      'poll_status': pollStatus,
      'food_pref': foodPref,
      'nomem': nomem.isEmpty ? '' : nomem,
    };

    print('ACCEPT_EVENT_REQUEST: URL=$acceptApiUrl');
    print('ACCEPT_EVENT_REQUEST: Headers=${requestBody.keys.toList()}');
    print('ACCEPT_EVENT_REQUEST: Body=${jsonEncode(requestBody)}');

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => const Center(child: CircularProgressIndicator()),
    );

    try {
      final response = await http
          .post(
        Uri.parse(acceptApiUrl),
        body: requestBody,
      )
          .timeout(const Duration(seconds: 15));

      print('ACCEPT_EVENT_RESPONSE: status=${response.statusCode}');
      print('ACCEPT_EVENT_RESPONSE: headers=${response.headers}');
      print('ACCEPT_EVENT_RESPONSE: body=${response.body}');

      if (!mounted) {
        print('SUBMIT_EVENT_RESPONSE: Widget unmounted');
        return;
      }
      Navigator.pop(context);

      if (response.statusCode != 200) {
        print('SUBMIT_EVENT_RESPONSE: Non-200 status ${response.statusCode}');
        _showSnack('Failed: Server returned ${response.statusCode}', isError: true);
        return;
      }

      final body = json.decode(response.body);
      print('SUBMIT_EVENT_RESPONSE: parsed_body=${jsonEncode(body)}');

      if (body is Map && body['success'] == true) {
        print('SUBMIT_EVENT_RESPONSE: Success, updating local state');
        setState(() {
          eventList[index]['poll_status'] = 'accepted';
          eventList[index]['food_pref'] = foodPref;
          eventList[index]['nomem'] = nomem;
        });

        final successMsg = body['message'] ?? (getTranslate(context, 'events.event_accepted') ?? 'Event accepted');
        print('SUBMIT_EVENT_RESPONSE: Showing success: $successMsg');
        _showSnack(successMsg);
      } else {
        final errorMsg = body is Map ? (body['message'] ?? 'Failed to submit response') : 'Failed to submit response';
        print('SUBMIT_EVENT_RESPONSE: Failed: $errorMsg');
        _showSnack(errorMsg, isError: true);
      }
    } catch (e) {
      print('SUBMIT_EVENT_RESPONSE: Exception=$e');
      if (mounted) {
        Navigator.pop(context);
        _showSnack('Error: $e', isError: true);
      }
    }
  }

  void _showSnack(String msg, {bool isError = false}) {
    print('SHOW_SNACK: ${isError ? "ERROR" : "SUCCESS"} - $msg');
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        backgroundColor: isError ? Colors.red : blackColor,
        duration: const Duration(milliseconds: 1800),
        behavior: SnackBarBehavior.floating,
        content: Text(
          msg,
          style: semibold15White,
        ),
      ),
    );
  }
}
