import 'dart:convert';
// import 'dart:io' as html;
import 'dart:typed_data'; // Import for Uint8List
import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:nhance_partner/core/routing/routes.dart';
import 'package:nhance_partner/data/utils/toastNotification.dart';
import 'package:nhance_partner/presentation/themes/indicators/text_field_theme.dart';

import '../../../../core/config/env.dart';
import '../../../../core/services/api_service.dart';
import '../../../../data/services/auth_service.dart';
import '../../../../data/utils/validators.dart';
import '../../../layouts/main_layout.dart';
import '../../../layouts/responsive_layout.dart';
import '../../../providers/manager_provider.dart';

import 'package:universal_html/html.dart' as html;

import '../../../themes/indicators/input_field_decoration.dart';

class Payment extends ConsumerStatefulWidget {
  final String? id;
  final Map<String, dynamic>? data;
  final VoidCallback onSubmit;
  const Payment({super.key, this.id, this.data, required this.onSubmit});
  @override
  ConsumerState<Payment> createState() => PaymentState();
}

class PaymentState extends ConsumerState<Payment> {
  final _formKey = GlobalKey<FormState>();
  late ApiService apiService;

  final GlobalKey<DropdownSearchState<Map<String, dynamic>>> dropDownKey =
      GlobalKey<DropdownSearchState<Map<String, dynamic>>>();

  final GlobalKey<DropdownSearchState<Map<String, dynamic>>>
  dropDownKeyHandler = GlobalKey<DropdownSearchState<Map<String, dynamic>>>();

  List<String> tabHeader = ['value', 'email', 'mobile', 'code'];
  late String isActive = "1";
  html.File? passportFile;
  String? selectedFileNames;
  String? passportFileUrlFromApi;
  dynamic selectedId;
  String? _token;
  bool isLoading = false;
  bool showHandler = false;

  String? selectedRole;
  List<Map<String, dynamic>> filteredRolesData = [];
  List<Map<String, dynamic>> getRolesData = [];

  List<dynamic>? selectedHandlerIds = [];
  String? selectedHandler;
  List<Map<String, dynamic>> filteredHandlersData = [];
  List<Map<String, dynamic>> getHandlersData = [];

  Map<String, TextEditingController> controllers = {};

  dynamic userId;
  dynamic managerId;

  Map<String, dynamic> dataDetails() {
    final data = {"value": controllers["value"]?.text, "is_active": isActive};
    return data;
  }

  @override
  void initState() {
    super.initState();
    apiService = ApiService();
    for (String field in tabHeader) {
      controllers[field] = TextEditingController();
    }

    _initializeToken();
    updateData();

    Future.microtask(() {
      managerId = ref.watch(managerIdProvider);
      userId = ref.watch(userIdProvider);
      if (managerId != null) {
        print('hansles');
        // getHandlers(managerId);
      }
    });
  }

  Future<void> _initializeToken() async {
    _token = await AuthService.getToken();
    print("APISERTOKEN - $_token");
  }

  void updateData() async {
    if (widget.data != null) {
      dynamic id = widget.data?['id'];
      final data = widget.data;

      if (data == null) return;
      setState(() {
        selectedId = id;
        controllers['value']?.text = data['value'] ?? '';
        controllers["is_active"]?.text = data['is_active'].toString();
      });
    }
  }

  Future<void> handleSave() async {
    if (controllers['value'] == null ||
        controllers['value']!.text.trim().isEmpty) {
      ToastHelper.showWarningToast(context, "Payment Mode is required");
      return;
    }

    if (!_formKey.currentState!.validate()) return;
    setState(() {
      if (_formKey.currentState!.validate()) {
        dataDetails();
        final dataSet = dataDetails();
        print("dataSetAgent - $dataSet");

        print("TYPE of is_active → ${dataSet['is_active'].runtimeType}");
        print("TYPE of value → ${dataSet['value'].runtimeType}");
        createUserData(dataSet);
      } else {
        // isDisable = false;
      }
    });
  }

  void refresh() {
    print('REfresj');
    widget.onSubmit();
    setState(() {
      // clear all text controllers
      for (var controller in controllers.values) {
        controller.clear();
      } // 👈 clear selected agent
      controllers['value']?.clear();
    });
  }

  Future<void> createUserData(data) async {
    final bool isUpdating = selectedId != null;
    final dynamic id = isUpdating ? int.tryParse(selectedId.toString()) : 0;
    final String apiUrldata;

    print("TYPE of id →  $id -  ${id.runtimeType}");
    print("TYPE of id →  $userId -  ${userId.runtimeType}");

    apiUrldata = isUpdating
        ? '${Env.apiUrl}/master/updatePaymentMode/$selectedId'
        : '${Env.apiUrl}/master/createPaymentMode';

    print('apiUrldata - $apiUrldata');
    // final token = await getToken(); // Fetch token

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

    if (isUpdating) {
      data['updated_by'] = userId.toString();
    } else {
      data['created_by'] = userId.toString();
    }

    // if (isUpdating) {
    //   data['updated_by'] = userId;
    //   // data.remove('id');
    // } else {
    //   data['created_by'] = userId;
    // }

    print("data-------  $data}");

    try {
      final response = await http.post(
        Uri.parse(apiUrldata),
        headers: {
          'Authorization': 'Bearer $_token',
          'Content-Type': 'application/json',
          'app-signature': Env.App_Signature,
        },
        body: jsonEncode(data), // Convert map to JSON
      );

      if (response.statusCode == 200) {
        final responseBody = jsonDecode(response.body);
        final message = responseBody['message'];
        print("Payment submitted successfully!");
        print("Response: ${response.body}");
        print(message);

        if (responseBody['status'] == 200) {
          refresh();
          isUpdating
              ? ToastHelper.showSuccessToast(context, message)
              : ToastHelper.showSuccessToast(context, message);
        } else {
          print("Failed to submit plan. Status: ${response.statusCode}");
          print("Error: ${response.body}");

          showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text("Payment Creation Failed"),
                content: Text(message),
                actions: [
                  TextButton(
                    child: Text("OK"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            },
          );
        }
      } else if (response.statusCode == 403) {
        await apiService.clearLocalStorageAndRedirect();
      }
    } catch (e) {
      print(" Error submitting Staff: $e");
    }
  }

  @override
  void dispose() {
    for (var controller in controllers.values) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return SelectionArea(
        child: Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          buildFormFields(),
          SizedBox(width: 5),
          InkWell(
            onTap: () {
              handleSave();
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 6),

              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8.0),
                color: Color(0xFF2E7D6E),
              ),
              child: Text(
                'Save',
                style: GoogleFonts.inter(color: Colors.white, fontSize: 10),
              ),
            ),
          ),
          SizedBox(width: 5),
          InkWell(
            onTap: () {
              refresh();
            },
            child: Container(
              padding: EdgeInsets.all(6.0),
              decoration: BoxDecoration(
                color: const Color(0xFF2E7D6E),
                borderRadius: BorderRadius.circular(5.0),
              ),
              child: Icon(Icons.refresh, size: 13, color: Colors.white),
            ),
          ),
        ],
      ),
    ) );
  }

  Widget buildFormFields() {
    return Form(
      key: _formKey,
      child: Column(children: [buildName()]),
    );
  }

  Widget buildName() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("Payment Mode *", style: _textStyle),
        SizedBox(width: 10),
        ThemedFormField(
          controller: controllers['value']!,
          // validator: (value) => Validators.requiredField(value, "value"),
          txtwidth: MediaQuery.of(context).size.width * 0.15,
          borderColor: Color(0xFFE2E8F0),
          highlightColor: Color(0xFF50A398),
          txtheight: 30,
          isdense: true,
          errFieldFont: 0,
        ),
      ],
    );
  }

  static final _textStyle = GoogleFonts.inter(
    fontSize: 11,
    fontWeight: FontWeight.w600,
  );
}
