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';

/// =======================
/// MODEL
/// =======================
class Ask {
  final String id;
  final String name;
  final String phone;
  final String details;
  final String createdAt;
  final String? replyText;

  Ask({
    required this.id,
    required this.name,
    required this.phone,
    required this.details,
    required this.createdAt,
    required this.replyText,
  });

  factory Ask.fromJson(Map<String, dynamic> json) {
    return Ask(
      id: json['id'].toString(),
      name: json['name'] ?? '',
      phone: json['phone'] ?? '',
      details: json['details'] ?? '',
      createdAt: json['created_at'] ?? '',
      replyText: json['reply_text'],
    );
  }

  bool get isOpen => replyText == null || replyText!.isEmpty;
}

/// =======================
/// SCREEN
/// =======================
class AskListScreen extends StatefulWidget {
  const AskListScreen({Key? key}) : super(key: key);

  @override
  State<AskListScreen> createState() => _AskListScreenState();
}

class _AskListScreenState extends State<AskListScreen>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late Future<List<Ask>> _futureAsks;

  static const String apiUrl =
      'https://rmbferodeunited.in/api/get_asks.php';

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _futureAsks = _fetchAsks();
    _checkLogin();
  }

  Future<void> _checkLogin() async {
    final prefs = await SharedPreferences.getInstance();
    if ((prefs.getString('rid_no') ?? '').isEmpty && mounted) {
      Navigator.pushNamedAndRemoveUntil(context, '/login', (_) => false);
    }
  }

  /// =======================
  /// FETCH ASKS
  /// =======================
  Future<List<Ask>> _fetchAsks() async {
    print('-----------------------------');
    print('GET REQUEST URL → $apiUrl');

    final res = await http.get(Uri.parse(apiUrl));

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

    final body = jsonDecode(res.body);

    if (body['status'] != 'success') {
      throw Exception(body['message'] ?? 'Fetch failed');
    }

    return (body['data'] as List)
        .map((e) => Ask.fromJson(e))
        .toList();
  }

  Future<void> _refresh() async {
    setState(() => _futureAsks = _fetchAsks());
    await _futureAsks;
  }

  /// =======================
  /// ASK CARD
  /// =======================
  Widget _askCard({
    required Ask ask,
    required bool isOpenTab,
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: shadowColor.withOpacity(0.08),
            blurRadius: 6,
            offset: const Offset(0, 3),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(fixPadding),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(ask.name, style: semibold16Black33),
                Container(
                  padding:
                  const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: d9EAF4Color,
                    borderRadius: BorderRadius.circular(6),
                  ),
                  child: Text(ask.createdAt, style: medium12Grey),
                ),
              ],
            ),
            height5Space,
            Text('Phone: ${ask.phone}', style: medium14Grey),
            height5Space,
            const Text('Details:', style: semibold14Black33),
            height5Space,
            Text(ask.details, style: medium14Grey),
            heightSpace,

            /// ACTION BUTTON
            Align(
              alignment: Alignment.centerRight,
              child: TextButton(
                onPressed: () async {
                  if (isOpenTab) {
                    /// OPEN → REPLY
                    final result = await Navigator.pushNamed(
                      context,
                      '/SpecificAskReply',
                      arguments: {
                        'id': ask.id,
                        'name': ask.name,
                        'phone': ask.phone,
                        'details': ask.details,
                      },
                    );

                    if (result == true) {
                      _refresh();
                    }
                  } else {
                    /// CLOSED → VIEW REPLY
                    Navigator.pushNamed(
                      context,
                      '/viewreplayask',
                      arguments: {
                        'phone': ask.phone,
                      },
                    );
                  }
                },
                style: TextButton.styleFrom(
                  backgroundColor: primaryColor,
                  padding: const EdgeInsets.symmetric(
                      horizontal: 18, vertical: 10),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: Text(
                  isOpenTab ? 'Reply' : 'View Reply',
                  style: semibold14White,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// =======================
  /// UI
  /// =======================
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: whiteF3Color,
      appBar: AppBar(
        backgroundColor: primaryColor,
        elevation: 0,
        centerTitle: true,
        leading: const BackButton(color: whiteColor),
        title: const Text('Specific Ask List', style: semibold18White),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(48),
          child: Container(
            color: whiteColor,
            child: TabBar(
              controller: _tabController,
              labelColor: primaryColor,
              unselectedLabelColor: greyColor,
              indicatorColor: primaryColor,
              tabs: const [
                Tab(text: 'Open'),
                Tab(text: 'All Requests'),
              ],
            ),
          ),
        ),
      ),
      body: FutureBuilder<List<Ask>>(
        future: _futureAsks,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            return Center(child: Text(snapshot.error.toString()));
          }

          final asks = snapshot.data!;
          final openAsks = asks.where((a) => a.isOpen).toList();
          final repliedAsks = asks.where((a) => !a.isOpen).toList();

          return TabBarView(
            controller: _tabController,
            children: [
              RefreshIndicator(
                onRefresh: _refresh,
                child: ListView(
                  padding: const EdgeInsets.only(top: 8, bottom: 90),
                  children: openAsks
                      .map((a) =>
                      _askCard(ask: a, isOpenTab: true))
                      .toList(),
                ),
              ),
              RefreshIndicator(
                onRefresh: _refresh,
                child: ListView(
                  padding: const EdgeInsets.only(top: 8, bottom: 90),
                  children: repliedAsks
                      .map((a) =>
                      _askCard(ask: a, isOpenTab: false))
                      .toList(),
                ),
              ),
            ],
          );
        },
      ),

      /// CREATE BUTTON
      bottomNavigationBar: Padding(
        padding: const EdgeInsets.fromLTRB(
          fixPadding,
          fixPadding,
          fixPadding,
          50, // extra bottom space to move button up
        ),
        child: SizedBox(
          height: 52,
          child: ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: primaryColor,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
              ),
            ),
            onPressed: () {
              Navigator.pushNamed(context, '/SpecificAskForm');
            },
            child: const Text(
              'Create Specific Ask',
              style: semibold18White,
            ),
          ),
        ),
      ),
    );
  }
}
