import 'package:flutter/material.dart';
import 'package:frontend/services/apiService.dart';
import 'package:google_fonts/google_fonts.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';

import '../../config/apiUrl.dart';
import '../../utils/auth_utils.dart';

class TripInformation extends StatefulWidget {
  final String planId;
  final Color layoutColorForUser;

  const TripInformation({
    Key? key,
    required this.planId,
    required this.layoutColorForUser,
  }) : super(key: key);

  @override
  _TripInformationState createState() => _TripInformationState();
}

class _TripInformationState extends State<TripInformation> {
  final ApiService apiService = ApiService();
  late Future<Map<String, dynamic>> _tripInfoFuture;

  Future<Map<String, dynamic>> fetchComments() async {
    final String apiUrldata =
        '$apiUrl/api/plans/planInfo?plan_id=${widget.planId}';

    final token = await getToken();

    if (token == null) {
      throw Exception('Token not found. Please log in.');
    }

    final response = await http.get(
      Uri.parse(apiUrldata),
      headers: {
        'Authorization': 'Bearer $token',
        'app-signature': 'ts-traveltool-2025-signature-123456',
        'Content-Type': 'application/json',
      },
    );

    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body);
      final Map<String, dynamic> dataMap =
          jsonData['data'] as Map<String, dynamic>;
      return dataMap;
    } else if (response.statusCode == 403) {
      print("403-FORB");
      await apiService.logout(context);
      return {};
      // throw Exception('Failed to load users');
    } else {
      throw Exception('Failed to load comments');
    }
  }

  @override
  void initState() {
    super.initState();
    _tripInfoFuture = fetchComments();

    print('_tripInfoFuture : $_tripInfoFuture');
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      backgroundColor: Colors.white,
      title: Text(
        'Trip Information',
        style: GoogleFonts.poppins(color: Colors.black),
      ),
      content: ConstrainedBox(
        constraints: const BoxConstraints(
          maxWidth: 500, // ✅ You can adjust this width
          maxHeight:
              400, // ✅ Optional: limit height to make it scrollable vertically
        ),
        child: FutureBuilder<Map<String, dynamic>>(
          future: _tripInfoFuture,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(child: CircularProgressIndicator());
            }

            if (snapshot.hasError) {
              return Text(
                'Error: ${snapshot.error}',
                style: GoogleFonts.poppins(fontSize: 12, color: Colors.black),
              );
            }

            if (!snapshot.hasData) {
              return Text(
                'No data found.',
                style: GoogleFonts.poppins(fontSize: 12, color: Colors.black),
              );
            }

            final data = snapshot.data!;

            return SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  keyValueColumn("Traveller", data["traveller"] ?? ""),
                  keyValueColumn("Group Name", data["group_name"] ?? ""),
                  keyValueColumn(
                    "Allowed Plan Type",
                    data["allowed_plan_type"] ?? "",
                  ),
                  keyValueColumn(
                    "Policy Action Flow",
                    data["policy_action_flow"] ?? "",
                  ),
                  keyValueColumn("Policy Type", data["policy_type"] ?? ""),

                  const SizedBox(height: 12),
                  Text(
                    "Approval Criteria:",
                    style: GoogleFonts.poppins(
                      fontWeight: FontWeight.w600,
                      fontSize: 13,
                    ),
                  ),

                  ...List.generate((data["approval_criteria"] as List).length, (
                    index,
                  ) {
                    final item = data["approval_criteria"][index];
                    return Card(
                      elevation: 1,
                      color: Colors.white,
                      margin: const EdgeInsets.symmetric(vertical: 4),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            keyValueRow("Action", item["action"] ?? '-'),
                            keyValueRow("Approver", item["approver"] ?? '-'),
                            keyValueRow(
                              "Is Action Done",
                              item["is_action_done"] ?? '-',
                            ),
                            keyValueRow("Action On", item["action_on"] ?? '-'),
                            keyValueRow(
                              "Email Status",
                              item["email_status"] ?? '-',
                            ),
                          ],
                        ),
                      ),
                    );
                  }),
                ],
              ),
            );
          },
        ),
      ),
      actions: [],
    );
  }

  Widget keyValueColumn(String key, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "$key ",
            style: GoogleFonts.poppins(
              fontWeight: FontWeight.w600,
              fontSize: 13,
            ),
          ),
          SizedBox(height: 5),
          Text(value, style: GoogleFonts.poppins(fontSize: 13)),
          // Expanded(
          //   child: Text(value, style: GoogleFonts.poppins(fontSize: 13)),
          // ),
        ],
      ),
    );
  }

  Widget keyValueRow(String key, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2, horizontal: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Text(
              "$key ",
              style: GoogleFonts.poppins(
                fontWeight: FontWeight.w600,
                fontSize: 12,
              ),
            ),
          ),
          SizedBox(height: 5),
          Expanded(
            child: Text(value, style: GoogleFonts.poppins(fontSize: 12)),
          ),
        ],
      ),
    );
  }
}
