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/localization/localization_const.dart';
import 'package:fl_sevengen_society_user_app/theme/theme.dart';

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

  @override
  State<HelpDeskScreen> createState() => _HelpDeskScreenState();
}

class _HelpDeskScreenState extends State<HelpDeskScreen> {
  int selectedTab = 0;

  bool _loading = false;
  String? _error;
  int? _ridNo;

  List<Complaint> _items = [];

  final String _baseUrl =
      'https://rmbferodeunited.in/api/testimonials.php';

  @override
  void initState() {
    super.initState();
    print('🔥 HelpDeskScreen initState called');
    _checkRIDAndLoad();
  }

  // ================= RID CHECK =================

  Future<void> _checkRIDAndLoad() async {
    print('📱 _checkRIDAndLoad started');

    final prefs = await SharedPreferences.getInstance();
    final fromMember = prefs.getString('from_member');
    final ridNo = prefs.getString('rid_no');

    print('💾 SharedPrefs - from_member: $fromMember, rid_no: $ridNo');

    final rid = fromMember ?? ridNo;

    if (rid == null || rid.isEmpty) {
      print('❌ No RID found, redirecting to login');
      if (!mounted) return;
      Navigator.pushNamedAndRemoveUntil(
        context,
        '/login',
            (_) => false,
      );
      return;
    }

    _ridNo = int.tryParse(rid);
    print('✅ RID parsed: $_ridNo');

    await _fetchForCurrentTab();
  }

  // ================= FETCH API =================

  Future<void> _fetchForCurrentTab() async {
    if (_ridNo == null) {
      print('⚠️ _ridNo is null, skipping fetch');
      return;
    }

    final status = selectedTab == 0 ? 'received' : 'sent';
    final uri =
    Uri.parse('$_baseUrl?rid_no=$_ridNo&status=$status');

    print('🌐 API Request: $uri');

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

    try {
      final response =
      await http.get(uri).timeout(const Duration(seconds: 15));

      print('📡 Response Status: ${response.statusCode}');
      print('📡 Response Headers: ${response.headers}');
      print('📡 Response Body: ${response.body}');

      final decoded = jsonDecode(response.body);
      print('🔍 Decoded Response: $decoded');

      if (decoded['success'] != true) {
        throw Exception(decoded['message']);
      }

      final dataList = decoded['data'] as List;
      print('📊 Raw data list length: ${dataList.length}');

      final list = dataList
          .map((e) {
        print('🔄 Parsing item: $e');
        return Complaint.fromJson(e);
      })
          .toList();

      print('✅ Parsed ${list.length} complaints');

      setState(() {
        _items = list;
        _loading = false;
      });

      print('✨ UI updated with ${_items.length} items');

    } catch (e) {
      print('💥 Error in _fetchForCurrentTab: $e');
      setState(() {
        _error = e.toString();
        _loading = false;
      });
    }
  }

  // ================= UI =================

  @override
  Widget build(BuildContext context) {
    print('🎨 HelpDeskScreen build called - tab: $selectedTab, items: ${_items.length}, loading: $_loading');

    return Scaffold(
      appBar: AppBar(
        title: Text(
          getTranslate(context, 'help_desk.help_desk'),
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        backgroundColor: primaryColor,
        elevation: 0,
        leading: BackButton(color: Colors.white),
        centerTitle: false, // Left align title
        toolbarHeight: 70,
      ),
      body: Column(
        children: [
          _tabBar(),
          Expanded(child: _buildBody()),
        ],
      ),
      bottomNavigationBar: _raiseComplaintButton(),
    );
  }

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

  Widget _buildBody() {
    print('📋 _buildBody - loading: $_loading, error: $_error, items: ${_items.length}');

    if (_loading) {
      print('⏳ Showing loading');
      return const Center(child: CircularProgressIndicator());
    }

    if (_error != null) {
      print('❌ Showing error: $_error');
      return Center(child: Text(_error!, style: medium14Grey));
    }

    if (_items.isEmpty) {
      print('📭 Showing no records');
      return Center(
        child: Text(
          getTranslate(context, 'help_desk.no_records'),
          style: medium14Grey,
        ),
      );
    }

    print('✅ Showing ${_items.length} items in ListView');
    return ListView.builder(
      padding: const EdgeInsets.fromLTRB(
        fixPadding,
        fixPadding,
        fixPadding,
        fixPadding * 4,
      ),
      itemCount: _items.length,
      itemBuilder: (context, index) {
        print('📄 Building item $index: ${_items[index].toString()}');
        return _complaintCard(_items[index]);
      },
    );
  }

  // ================= CARD DESIGN =================

  Widget _complaintCard(Complaint item) {
    print('🎴 _complaintCard - ID: ${item.id}, To: ${item.toMemberName}, From: ${item.fromMemberName}');

    return Container(
      margin: const EdgeInsets.only(bottom: fixPadding * 1.5),
      padding: const EdgeInsets.all(fixPadding * 1.5),
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(22),
        boxShadow: [
          BoxShadow(
            color: shadowColor.withOpacity(0.12),
            blurRadius: 12,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // TOP: to_member_name (Receiver)
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Text(
                  item.toMemberName,
                  style: semibold18Black33,
                ),
              ),
              Icon(
                Icons.format_quote,
                size: 32,
                color: black33Color.withOpacity(0.25),
              ),
            ],
          ),
          const SizedBox(height: 12),

          // MIDDLE: Description
          Text(
            item.description,
            style: medium16Grey,
          ),
          const SizedBox(height: 12),

          // BOTTOM: "Given by" from_member_name (Sender)
          Row(
            children: [
              Text(
                'Given by ',
                style: semibold14Black33.copyWith(
                  color: black33Color.withOpacity(0.7),
                ),
              ),
              Expanded(
                child: Text(
                  item.fromMemberName,
                  style: semibold14Black33,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // ================= TAB BAR =================

  Widget _tabBar() {
    print('🔘 _tabBar - selectedTab: $selectedTab');
    return Padding(
      padding: const EdgeInsets.all(fixPadding),
      child: Row(
        children: [
          _tab('Received', 0, Icons.south_west),
          _tab('Sent', 1, Icons.send),
        ],
      ),
    );
  }

  Widget _tab(String text, int index, IconData icon) {
    final selected = selectedTab == index;
    print('🔘 Tab clicked: $text (index: $index, selected: $selected)');

    return Expanded(
      child: GestureDetector(
        onTap: () async {
          print('👆 Tab tapped: $text');
          setState(() => selectedTab = index);
          await _fetchForCurrentTab();
        },
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 6),
          padding: const EdgeInsets.symmetric(vertical: 14),
          decoration: BoxDecoration(
            color: selected ? primaryColor : whiteColor,
            borderRadius: BorderRadius.circular(24),
            border: Border.all(
              color: selected ? primaryColor : shadowColor,
            ),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                icon,
                size: 18,
                color: selected ? whiteColor : black33Color,
              ),
              const SizedBox(width: 6),
              Text(
                text,
                style:
                selected ? semibold16White : semibold16Grey,
              ),
            ],
          ),
        ),
      ),
    );
  }

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

  Widget _raiseComplaintButton() {
    print('➕ _raiseComplaintButton rendered');
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.all(fixPadding * 2),
        child: ElevatedButton(
          onPressed: () {
            print('🚀 Raise complaint button pressed');
            Navigator.pushNamed(context, '/addComplaint');
          },
          style: ElevatedButton.styleFrom(
            backgroundColor: primaryColor,
            padding: const EdgeInsets.symmetric(vertical: 16),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(14),
            ),
          ),
          child: Text(
            getTranslate(
                context, 'help_desk.raise_new_complaint'),
            style: semibold18White,
          ),
        ),
      ),
    );
  }
}

// ================= MODEL =================

class Complaint {
  final int id;
  final String fromMemberName;
  final String toMemberName;
  final String description;
  final String fromFullNumber;
  final String toFullNumber;

  Complaint({
    required this.id,
    required this.fromMemberName,
    required this.toMemberName,
    required this.description,
    required this.fromFullNumber,
    required this.toFullNumber,
  });

  factory Complaint.fromJson(Map<String, dynamic> j) {
    print('🔧 Complaint.fromJson fields:');
    print('  - id: ${j['id']}');
    print('  - from_member_name: ${j['from_member_name']}');
    print('  - to_member_name: ${j['to_member_name']}');
    print('  - description: ${j['description'] ?? j['complaint']}');
    print('  - from_full_number: ${j['from_full_number']}');
    print('  - to_full_number: ${j['to_full_number']}');

    final complaint = Complaint(
      id: int.tryParse('${j['id']}') ?? 0,
      fromMemberName: j['from_member_name'] ?? '',
      toMemberName: j['to_member_name'] ?? '',
      description: j['description'] ?? j['complaint'] ?? '',
      fromFullNumber: j['from_full_number'] ?? '',
      toFullNumber: j['to_full_number'] ?? '',
    );

    print('✅ Complaint created: ${complaint.toString()}');
    return complaint;
  }

  @override
  String toString() {
    return 'Complaint(id: $id, from: $fromMemberName, to: $toMemberName, desc: ${description.substring(0, description.length > 50 ? 50 : description.length)}...)';
  }
}
