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

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

class AskViewReplyScreen extends StatefulWidget {
  final String phone;

  const AskViewReplyScreen({
    Key? key,
    required this.phone,
  }) : super(key: key);

  @override
  State<AskViewReplyScreen> createState() => _AskViewReplyScreenState();
}

class _AskViewReplyScreenState extends State<AskViewReplyScreen> {
  bool isLoading = true;
  bool isError = false;

  Map<String, dynamic>? ask;

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

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

  Future<void> _fetchAsk() async {
    print('-----------------------------');
    print('ASK VIEW REPLY SCREEN');
    print('PHONE RECEIVED → ${widget.phone}');
    print('API URL → $apiUrl');
    print('-----------------------------');

    try {
      print('Sending GET request...');
      final response = await http.get(Uri.parse(apiUrl));

      print('HTTP STATUS → ${response.statusCode}');
      print('RAW RESPONSE → ${response.body}');
      print('-----------------------------');

      final decoded = json.decode(response.body);

      if (decoded['status'] != 'success') {
        print('API STATUS NOT SUCCESS');
        throw Exception('API failed');
      }

      final List list = decoded['data'];
      print('TOTAL RECORDS RECEIVED → ${list.length}');

      for (final item in list) {
        print('CHECKING PHONE → ${item['phone']}');

        if (item['phone'] == widget.phone) {
          ask = Map<String, dynamic>.from(item);
          print('MATCH FOUND → $ask');
          break;
        }
      }

      if (ask == null) {
        print('NO MATCH FOUND FOR PHONE');
        isError = true;
      }
    } catch (e) {
      print('ERROR OCCURRED → $e');
      isError = true;
    } finally {
      if (mounted) {
        setState(() => isLoading = false);
      }
      print('-----------------------------');
    }
  }

  Widget _card(String title, List<Widget> children) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(fixPadding),
      margin: const EdgeInsets.only(bottom: fixPadding),
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: greyD9Color),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(title, style: semibold16Black33),
          height5Space,
          ...children,
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: whiteF3Color,
      appBar: AppBar(
        backgroundColor: primaryColor,
        title: const Text(
          'View Reply',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: false,
        elevation: 0,
        iconTheme: const IconThemeData(
          color: Colors.white, // Makes back arrow white with navigation working
        ),
      ),
      body: isLoading
          ? const Center(child: CircularProgressIndicator())
          : isError || ask == null
          ? const Center(child: Text('Reply not found'))
          : Padding(
        padding: const EdgeInsets.all(fixPadding),
        child: SingleChildScrollView(
          child: Column(
            children: [
              /// ASK DETAILS
              _card(
                'Request Details',
                [
                  Text(
                    'Name: ${ask!['name'] ?? '-'}',
                    style: medium14Grey,
                  ),
                  Text(
                    'Phone: ${ask!['phone'] ?? '-'}',
                    style: medium14Grey,
                  ),
                  height5Space,
                  Text(
                    ask!['details'] ?? '',
                    style: medium14Black33,
                  ),
                ],
              ),

              /// REPLY DETAILS
              _card(
                'Reply Details',
                [
                  Text(
                    'Name: ${ask!['name_replay'] ?? '-'}',
                    style: medium14Grey,
                  ),
                  Text(
                    'Company: ${ask!['company_replay'] ?? '-'}',
                    style: medium14Grey,
                  ),
                  Text(
                    'Designation: ${ask!['design_replay'] ?? '-'}',
                    style: medium14Grey,
                  ),
                  Text(
                    'Phone: ${ask!['phone_replay'] ?? '-'}',
                    style: medium14Grey,
                  ),
                  height5Space,
                  Text(
                    ask!['reply_text'] ?? '',
                    style: medium14Black33,
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
