import 'dart:convert';

import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;

import '../../config/apiUrl.dart';
import '../../services/apiService.dart';
import '../../utils/auth_utils.dart';
import '../../widgets/custom_text_forex.dart';
import 'forex_list.dart';

class ForexData extends StatefulWidget {
  final Future<List<dynamic>?> Function() fetchGetForex;
  final bool isDesktop;
  final Color? layoutColor;

  final int? forexId; // <-- Add this
  final Map<String, dynamic>? forexData;

  const ForexData({
    super.key,
    required this.isDesktop,
    this.layoutColor,
    required this.fetchGetForex,
    this.forexId,
    this.forexData,
  });

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

class ForexDataState extends State<ForexData> {
  final ApiService apiService = ApiService();
  Map<String, String> countryMap = {};
  late List<dynamic>? apiCountryData;
  late List<dynamic>? apiAirlineCountryData;
  Map<String, dynamic>? apiData;
  final Map<String, TextEditingController> controllers = {};
  Map<String, String> errorMessages = {};
  Map<String, FocusNode> focusNodes = {};
  Map<String, bool> focusStates = {};

  List<dynamic> countryList = [];
  String? selectedCountry;
  String? selectedCountryName;
  String? selectedCurrency;
  String? selectedDuration;
  String? selectedPerdiemAmount;
  String? userId;
  int? forexDataId;
  late String isActive = "1";
  bool isDisable = false;

  bool isCashEditing = false;
  bool isCardEditing = false;

  List<String> dataHeader = [
    "country_code",
    "country",
    "currency",
    "perdiemAmount",
    "cash",
    "card",
  ];

  Map<String, dynamic> forex_Detials() {
    final data = {
      // "forex_perdiem_id": int.parse(forexId),
      "country_code": selectedCountry,
      "country_name": selectedCountryName,
      "currency": controllers["currency"]?.text,
      "cash_percentage": controllers["cash"]?.text,
      "card_percentage": controllers["card"]?.text,
      "perdiem_amount": controllers["perdiemAmount"]?.text,
      "is_active": 1,
      "created_by": userId,
      "is_active": isActive,
    };
    return data;
  }

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

    apiCountryData = null;
    apiData = null;
    for (var field in dataHeader) {
      controllers[field] = TextEditingController();
      focusNodes["${field}FocusNode"] = FocusNode();
      focusStates["${field}Focused"] = false;
    }
    for (var key in focusNodes.keys) {
      _addFocusListener(focusNodes[key]!, (focus) {
        setState(() {
          focusStates[key.replaceFirst("FocusNode", "Focused")] = focus;
        });
      });
    }
    fetchCountries();

    controllers["cash"]?.addListener(_handleCashChange);
    controllers["card"]?.addListener(_handleCardChange);

    if (widget.forexId != null) {
      print('Editing Forex ID: ${widget.forexId}');
      updateForexDetails();
    }
    _clearError();
  }

  void _clearError() {
    setState(() {
      errorMessages.clear();
    });
  }

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

  void _addFocusListener(FocusNode node, Function(bool) updateState) {
    node.addListener(() {
      setState(() {
        updateState(node.hasFocus);
      });
    });
  }

  void updateForexDetails() {
    print("Updateeee - ${widget.forexData}");

    final data = widget.forexData;

    if (data == null) return;
    setState(() {
      selectedCountry = data['country_code']; // For dropdown
      selectedCountryName =
          data['country_name']; // For dropdown label or display
      selectedCurrency = data['currency']; // Optional if used elsewhere
      controllers['currency']?.text = data['currency'] ?? '';
      controllers['cash']?.text = data['cash_percentage'] ?? '';
      controllers['card']?.text = data['card_percentage'] ?? '';
      controllers['perdiemAmount']?.text = data['perdiem_amount'].toString();
      isActive = data["is_active"];
      final forexId = int.tryParse(data['forex_perdiem_id'].toString());
      forexDataId = forexId;
    });
  }

  Future<void> fetchCountries() async {
    try {
      List<dynamic> countries = await apiService.fetchCountryList(context);
      setState(() {
        apiCountryData = countries;
      });
    } catch (e) {
      print('Error fetching country list: $e');
    }
  }

  void toggleStatus() {
    setState(() {
      isActive = isActive == "1" ? "0" : "1";
    });
  }

  void _handleCashChange() {
    if (isCardEditing) return; // Prevent circular update

    isCashEditing = true;
    final cashText = controllers["cash"]?.text ?? '';
    final cash = int.tryParse(cashText) ?? 0;

    final card = 100 - cash;
    controllers["card"]?.text = card.toString();
    isCashEditing = false;
  }

  void _handleCardChange() {
    if (isCashEditing) return; // Prevent circular update

    final cash = int.tryParse(controllers["cash"]?.text ?? '') ?? 0;
    final card = int.tryParse(controllers["card"]?.text ?? '') ?? 0;

    if (cash + card != 100) {
      errorMessages["cash_percentage"] = "Cash and card must total 100%";
    } else {
      errorMessages.remove("cash_percentage");
    }
  }

  bool validateData() {
    errorMessages.clear();

    final data = {
      "country_code": selectedCountry,
      "country": selectedCountryName,
      "currency": controllers["currency"]?.text,
      "cash_percentage": controllers["cash"]?.text,
      "card_percentage": controllers["card"]?.text,
      "perdiemAmount": controllers["perdiemAmount"]?.text,
    };

    final requiredFields = [
      "country_code",
      "country",
      "currency",
      "perdiemAmount",
      "cash_percentage",
      "card_percentage",
    ];

    // Check validation for each field
    for (String field in requiredFields) {
      if (data[field] == null || data[field].toString().trim().isEmpty) {
        errorMessages[field] = "Required";
      }
    }

    final cash = int.tryParse(data["cash_percentage"] ?? '') ?? 0;
    final card = int.tryParse(data["card_percentage"] ?? '') ?? 0;

    if (cash + card != 100) {
      errorMessages["card_percentage"] = "Total must be 100%";
    }

    return errorMessages.isEmpty;
  }

  Future<void> handleSubmit() async {
    userId = await getUserId();

    setState(() {
      isDisable = true;
      // This triggers UI rebuild with error messages
      if (validateData()) {
        postForexData();
      } else {
        isDisable = false;
      }
    });

    final forexData1 = forex_Detials();
    print("ForexDAta - $forexData1");
  }

  Future<void> postForexData({int isActive = 1}) async {
    // final remarksData = getData();

    final forexData = forex_Detials();

    print("forexDataPOSDf - $forexData");

    final String apiUrldata;
    if (forexDataId != null) {
      print("feforexDataId - $forexDataId");

      apiUrldata = '$apiUrl/api/updateForexPerdiem/$forexDataId';
      forexData["id"] = forexDataId;
      forexData["updated_by"] = userId;
    } else {
      apiUrldata = '$apiUrl/api/createForexPerdiem';
      forexData["created_by"] = userId;
    }

    print("Remarks Data - remarksData");

    final token = await getToken(); // Fetch token

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

    // if (selectedPlanId != null && selectedPlanId!.isNotEmpty) {
    //   planData['plan_id'] = selectedPlanId; // Add plan_id for update
    // }

    try {
      final uri = Uri.parse(apiUrldata);
      final headers = {
        'Authorization': 'Bearer $token',
        'Content-Type': 'application/json',
        'app-signature': 'ts-traveltool-2025-signature-123456',
      };
      final body = jsonEncode(forexData);

      final response =
          forexDataId != null
              ? await http.put(uri, headers: headers, body: body)
              : await http.post(uri, headers: headers, body: body);

      // final response = await http.post(
      //   Uri.parse(apiUrldata),
      //   headers: {
      //     'Authorization': 'Bearer $token',
      //     'Content-Type': 'application/json',
      //   },
      //   body: jsonEncode(forexData), // Convert map to JSON
      // );

      if (response.statusCode == 200 || response.statusCode == 201) {
        print("Forex Details Created successfully!");
        print("Response: ${response.body}");
        // _clearError();
        _clearError();
        await widget.fetchGetForex();

        // dispose();
        if (context.mounted) {
          Navigator.of(context).pop(); // Close modal only if mounted
        }
        setState(() {
          isDisable = false;
        });
      } else if (response.statusCode == 403) {
        print("403-FORB");
        await apiService.logout(context);
        return null;
        // throw Exception('Failed to load users');
      } else if (response.statusCode == 404) {
        if (context.mounted) {
          Navigator.of(context).pop();
        }
        setState(() {
          isDisable = false;
        });
        final message = jsonDecode(response.body)['message'] ?? 'Unknown error';

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(message),
            backgroundColor: Colors.redAccent,
            behavior: SnackBarBehavior.floating,
          ),
        );
      } else {
        print("Failed to submit plan. Status: ${response.statusCode}");
        print("Error: ${response.body}");
        setState(() {
          isDisable = false;
        });
      }
    } catch (e) {
      print(" Error submitting plan: $e");
      setState(() {
        isDisable = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    late Map<String, String> countryMap; // Mapping country_code -> country_name
    late List<String> countryCodes; // List of country codes

    // countryList = [];
    countryList = apiCountryData ?? [];

    // Map country codes to country names
    // countryMap = {
    //   for (var item in countryList)
    //     item['country_code'] as String: item['country_name'] as String,
    // };

    countryMap = {
      for (var country in countryList)
        (country['country_code'] ?? ''):
            '${country['country_name'] ?? ''} (${country['country_code'] ?? ''})',
    };

    // Extract only country codes for processing
    countryCodes = countryMap.keys.toList();

    selectedCountry ??= null;

    void setCurrencyFromSelectedCountry(String selectedCountryCode) {
      final matchedCountry = countryList.firstWhere(
        (item) => item['country_code'] == selectedCountryCode,
        orElse: () => {},
      );

      final currency = matchedCountry['currency'] ?? '';
      controllers["currency"]?.text = currency;
    }

    return AlertDialog(
      backgroundColor: Colors.white,
      contentPadding: const EdgeInsets.fromLTRB(34, 30, 34, 30),
      // contentPadding: const EdgeInsets.fromLTRB(24, 20, 24, 10),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // Row 1: Title + Edit + Delete buttons
          Row(
            children: [
              Text(
                (forexDataId != null)
                    ? 'Update Perdiem Amount'
                    : 'Create Perdiem Amount',
                style: GoogleFonts.poppins(fontSize: 15, color: Colors.black),
              ),
              const Spacer(),
            ],
          ),
          const SizedBox(height: 2),
          Divider(thickness: 0.2, color: Colors.blueGrey.shade100),
          const SizedBox(height: 5),

          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "Country *",
                style: GoogleFonts.poppins(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF575A74),
                ),
              ),
              SizedBox(height: 5),
              CustomTextFieldForexWrapper(
                isFocused: false,
                padding: const EdgeInsets.symmetric(horizontal: 0),
                isDesktop: widget.isDesktop,
                child: SizedBox(
                  height: 40,
                  width: double.infinity,
                  child: Focus(
                    focusNode: focusNodes["country_codeFocusNode"],
                    onFocusChange: (hasFocus) {
                      setState(() {
                        focusStates["country_codeFocused"] = hasFocus;
                      });
                    },
                    child: GestureDetector(
                      onTap: () {
                        // Request focus when user taps
                        focusNodes["country_codeFocusNode"]?.requestFocus();
                      },
                      child: DropdownSearch<String>(
                        selectedItem: countryMap[selectedCountry],
                        popupProps: PopupProps.menu(
                          showSearchBox: true, // Enables search functionality
                          menuProps: const MenuProps(
                            backgroundColor: Colors.white,
                          ),
                          constraints: BoxConstraints(maxHeight: 200),
                          itemBuilder: (context, item, isSelected) {
                            print("contryItem - $item");
                            final match = RegExp(
                              r'^(.*)\s\((.*)\)$',
                            ).firstMatch(item);
                            final countryName = match?.group(1) ?? '';
                            final countryCode = match?.group(2) ?? '';
                            return Padding(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 8.0,
                                vertical: 0.02,
                              ),
                              child: Padding(
                                padding: const EdgeInsets.all(8.0),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      countryName,
                                      style: GoogleFonts.poppins(
                                        fontSize: 11.5,
                                      ),
                                    ),
                                    Text(
                                      countryCode,
                                      style: GoogleFonts.poppins(
                                        fontSize: 11.5,
                                        color: Colors.grey,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                          searchFieldProps: TextFieldProps(
                            decoration: InputDecoration(
                              hintText: "Search ...",
                              hintStyle: GoogleFonts.poppins(fontSize: 11),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 3,
                                vertical: 3,
                              ),
                            ),
                          ),
                        ),
                        items: countryMap.values.toList(),
                        filterFn: (item, filter) {
                          final lowerFilter = filter.toLowerCase();

                          final match = RegExp(
                            r'^(.*)\s\((.*)\)$',
                          ).firstMatch(item);
                          final countryName =
                              match?.group(1)?.toLowerCase() ?? '';
                          final countryCode =
                              match?.group(2)?.toLowerCase() ?? '';

                          // Prioritize country code match, fallback to country name
                          return countryCode.contains(lowerFilter) ||
                              countryName.contains(lowerFilter);
                        },
                        dropdownDecoratorProps: DropDownDecoratorProps(
                          dropdownSearchDecoration: InputDecoration(
                            // border: InputBorder.none,
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8),
                              borderSide: BorderSide(
                                color:
                                    (focusStates["country_codeFocused"] ??
                                            false)
                                        ? widget.layoutColor!
                                        : Colors.white,
                                // width: 0.5,
                              ),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                color:
                                    (focusStates["country_codeFocused"] ??
                                            false)
                                        ? widget.layoutColor!
                                        : Colors.white,
                                // : const Color(0xFFD6D5E6),
                                // width: 0.5,
                                // const Color(0xFFD6D5E6),
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                color: widget.layoutColor!,
                                width: 1,
                              ),
                            ),
                            contentPadding: EdgeInsets.symmetric(
                              horizontal: 10.0,
                              vertical: 8.0,
                            ),
                          ),
                        ),
                        dropdownBuilder:
                            (context, selectedItem) => Align(
                              // Center-align selected item
                              alignment: Alignment.centerLeft,
                              child: Text(
                                selectedItem ?? "Select ",
                                style: GoogleFonts.poppins(fontSize: 11),
                              ),
                            ),
                        onChanged: (String? newValue) {
                          setState(() {
                            // Find the country_code based on selected country_name
                            selectedCountry =
                                countryMap.entries
                                    .firstWhere(
                                      (entry) => entry.value == newValue,
                                    )
                                    .key;
                            final setMatch = RegExp(
                              r'^(.*)\s\((.*)\)$',
                            ).firstMatch(newValue!);
                            final setCountryName =
                                setMatch?.group(1)?.toLowerCase() ?? '';
                            selectedCountryName = setCountryName;
                            setCurrencyFromSelectedCountry(selectedCountry!);
                          });
                        },
                      ),
                      // child: DropdownSearch<String>(
                      //   selectedItem: countryMap[selectedCountry],
                      //   popupProps: PopupProps.menu(
                      //     showSearchBox: true, // Enables search functionality
                      //     menuProps: const MenuProps(backgroundColor: Colors.white),
                      //     constraints: BoxConstraints(maxHeight: 250),
                      //     itemBuilder:
                      //         (context, item, isSelected) => Padding(
                      //       padding: const EdgeInsets.symmetric(
                      //         horizontal: 10.0,
                      //         vertical: 8.0,
                      //       ),
                      //       child: Text(
                      //         item,
                      //         style: GoogleFonts.poppins(fontSize: 11.5),
                      //       ),
                      //     ),
                      //     searchFieldProps: TextFieldProps(
                      //       decoration: InputDecoration(
                      //         hintText: "Search ...",
                      //         hintStyle: GoogleFonts.poppins(fontSize: 11),
                      //         contentPadding: EdgeInsets.symmetric(horizontal: 4),
                      //       ),
                      //     ),
                      //   ),
                      //   items: countryMap.values.toList(),
                      //   dropdownDecoratorProps: DropDownDecoratorProps(
                      //     dropdownSearchDecoration: InputDecoration(
                      //       // border: InputBorder.none,
                      //       border: OutlineInputBorder(
                      //         borderRadius: BorderRadius.circular(8),
                      //         borderSide: BorderSide(
                      //           color:
                      //           (focusStates["country_codeFocused"] ?? false)
                      //               ? widget.layoutColor!
                      //               : Colors.white,
                      //           // width: 0.5,
                      //         ),
                      //       ),
                      //       enabledBorder: OutlineInputBorder(
                      //         borderSide: BorderSide(
                      //           color:
                      //           (focusStates["country_codeFocused"] ?? false)
                      //               ? widget.layoutColor!
                      //               : Colors.white,
                      //           // : const Color(0xFFD6D5E6),
                      //           // width: 0.5,
                      //           // const Color(0xFFD6D5E6),
                      //         ),
                      //       ),
                      //       focusedBorder: OutlineInputBorder(
                      //         borderSide: BorderSide(color: widget.layoutColor!, width: 1),
                      //       ),
                      //       contentPadding: EdgeInsets.symmetric(horizontal: 10.0,
                      //         vertical: 8.0,),
                      //     ),
                      //   ),
                      //   dropdownBuilder:
                      //       (context, selectedItem) => Align(
                      //     // Center-align selected item
                      //     alignment: Alignment.centerLeft,
                      //     child: Text(
                      //       selectedItem ?? "Select ",
                      //       style: GoogleFonts.poppins(fontSize: 11),
                      //     ),
                      //   ),
                      //   onChanged: (String? newValue) {
                      //     setState(() {
                      //       // Find the country_code based on selected country_name
                      //       selectedCountry =
                      //           countryMap.entries
                      //               .firstWhere((entry) => entry.value == newValue)
                      //               .key;
                      //       selectedCountryName = newValue;
                      //       setCurrencyFromSelectedCountry(selectedCountry!);
                      //     });
                      //   },
                      // ),
                    ),
                  ),
                ),
              ),
              if (errorMessages["country_code"] != null) ...[
                SizedBox(height: 5), // Space before error message
                Text(
                  errorMessages["country_code"]!,
                  style: TextStyle(color: Colors.red, fontSize: 12),
                ),
              ],
            ],
          ),
          const SizedBox(height: 10),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "Currency *",
                style: GoogleFonts.poppins(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF575A74),
                ),
              ),
              SizedBox(height: 5),
              CustomTextFieldForexWrapper(
                isFocused: focusStates["currencyFocused"] ?? false,
                isDesktop: widget.isDesktop,
                color: Colors.transparent,

                // width: isDesktop
                //     ? MediaQuery.of(context).size.width * 0.330
                //     : MediaQuery.of(context).size.width * 0.66,
                child: SizedBox(
                  height: 40,
                  child: TextField(
                    focusNode: focusNodes["currencyFocusNode"],
                    controller: controllers["currency"],
                    style: GoogleFonts.poppins(
                      fontSize: 11,
                      color: Colors.black,
                    ),
                    decoration: const InputDecoration(
                      labelText: "Currency",
                      enabled: false,
                      labelStyle: TextStyle(fontSize: 11, color: Colors.grey),
                      floatingLabelBehavior: FloatingLabelBehavior.never,
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 16),
                    ),
                  ),
                ),
              ),
              if (errorMessages["currency"] != null) ...[
                SizedBox(height: 5), // Space before error message
                Text(
                  errorMessages["currency"]!,
                  style: TextStyle(color: Colors.red, fontSize: 12),
                ),
              ],
            ],
          ),

          // if (isDesktop)SizedBox(width: 8,) else SizedBox(height: 8,),
          SizedBox(height: 10),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "Cash (%) *",
                    style: GoogleFonts.poppins(
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                      color: Color(0xFF575A74),
                    ),
                  ),
                  SizedBox(height: 5),
                  CustomTextFieldForexWrapper(
                    isFocused: focusStates["cashFocused"] ?? false,
                    isDesktop: widget.isDesktop,
                    color: Colors.transparent,
                    width:
                        widget.isDesktop
                            ? MediaQuery.of(context).size.width * 0.09
                            : MediaQuery.of(context).size.width * 0.66,
                    child: SizedBox(
                      height: 40,
                      child: TextField(
                        focusNode: focusNodes["cashFocusNode"],
                        controller: controllers["cash"],
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        style: const TextStyle(fontSize: 12),
                        decoration: const InputDecoration(
                          labelText: "Cash",
                          labelStyle: TextStyle(
                            fontSize: 11,
                            color: Colors.grey,
                          ),
                          floatingLabelBehavior: FloatingLabelBehavior.never,
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.symmetric(vertical: 16),
                        ),
                      ),
                    ),
                  ),
                  if (errorMessages["cash_percentage"] != null) ...[
                    SizedBox(height: 5), // Space before error message
                    Text(
                      errorMessages["cash_percentage"]!,
                      style: TextStyle(color: Colors.red, fontSize: 12),
                    ),
                  ],
                ],
              ),
              Spacer(),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    "Card (%) *",
                    style: GoogleFonts.poppins(
                      fontSize: 12,
                      fontWeight: FontWeight.w600,
                      color: Color(0xFF575A74),
                    ),
                  ),
                  SizedBox(height: 5),
                  CustomTextFieldForexWrapper(
                    isFocused: focusStates["cardFocused"] ?? false,
                    isDesktop: widget.isDesktop,
                    color: Colors.transparent,
                    width:
                        widget.isDesktop
                            ? MediaQuery.of(context).size.width * 0.09
                            : MediaQuery.of(context).size.width * 0.66,
                    child: SizedBox(
                      height: 40,
                      child: TextField(
                        focusNode: focusNodes["cardFocusNode"],
                        controller: controllers["card"],
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        style: const TextStyle(fontSize: 12),
                        decoration: const InputDecoration(
                          labelText: "Card",
                          labelStyle: TextStyle(
                            fontSize: 11,
                            color: Colors.grey,
                          ),
                          floatingLabelBehavior: FloatingLabelBehavior.never,
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.symmetric(vertical: 16),
                        ),
                      ),
                    ),
                  ),
                  if (errorMessages["card_percentage"] != null) ...[
                    SizedBox(height: 5), // Space before error message
                    Text(
                      errorMessages["card_percentage"]!,
                      style: TextStyle(color: Colors.red, fontSize: 12),
                    ),
                  ],
                ],
              ),
            ],
          ),
          SizedBox(height: 10),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "Perdiem Amount *",
                style: GoogleFonts.poppins(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF575A74),
                ),
              ),
              SizedBox(height: 5),
              CustomTextFieldForexWrapper(
                isFocused: focusStates["perdiemAmountFocused"] ?? false,
                isDesktop: widget.isDesktop,
                color: Colors.transparent,
                child: SizedBox(
                  height: 40,
                  child: TextField(
                    focusNode: focusNodes["perdiemAmountFocusNode"],
                    controller: controllers["perdiemAmount"],
                    style: const TextStyle(fontSize: 12),
                    inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                    decoration: const InputDecoration(
                      labelText: "Perdiem Amount",
                      labelStyle: TextStyle(fontSize: 11, color: Colors.grey),
                      floatingLabelBehavior: FloatingLabelBehavior.never,
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(vertical: 16),
                    ),
                  ),
                ),
              ),
              if (errorMessages["perdiemAmount"] != null) ...[
                SizedBox(height: 5), // Space before error message
                Text(
                  errorMessages["perdiemAmount"]!,
                  style: TextStyle(color: Colors.red, fontSize: 12),
                ),
              ],
            ],
          ),
          SizedBox(height: 15),

          if (forexDataId != null)
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  "Change Status  ",
                  style: GoogleFonts.poppins(
                    fontSize: 12,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF575A74),
                  ),
                ),
                Tooltip(
                  message:
                      isActive == "1" ? "Tap to deactivate" : "Tap to activate",
                  child: GestureDetector(
                    onTap: toggleStatus,
                    child: Text(
                      isActive == "1" ? "Active" : "Inactive",
                      style: TextStyle(
                        fontSize: 13,
                        fontFamily: "Inter",
                        color: isActive == "1" ? Colors.green : Colors.red,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          if (forexDataId != null) SizedBox(height: 15),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              // SizedBox(
              //   child: ElevatedButton(
              //     onPressed: () {
              //       // You can get text from commentController.text
              //       Navigator.of(context).pop(); // Close the modal
              //     },
              //     style: ElevatedButton.styleFrom(
              //       backgroundColor: widget.layoutColor,
              //       shape: RoundedRectangleBorder(
              //         borderRadius: BorderRadius.circular(8),
              //       ),
              //     ),
              //     child: Text('Cancel',
              //         style: GoogleFonts.poppins(
              //             fontSize: 13, color: Colors.white)),
              //   ),
              // ),
              // SizedBox(
              //   width: 10,
              // ),
              SizedBox(
                child: ElevatedButton(
                  // onPressed: () {
                  //   handleSubmit();
                  //   // You can get text from commentController.text
                  //   // Navigator.of(context).pop(); // Close the modal
                  // },
                  onPressed:
                      isDisable
                          ? null
                          : () async {
                            setState(() {
                              isDisable = true;
                            });

                            await handleSubmit();
                            // You can get text from commentController.text
                            // Navigator.of(context).pop(); // Close the modal

                            // Optional: re-enable only on error
                            // setState(() {
                            //   isDisable = false;
                            // });
                          },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: widget.layoutColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: Text(
                    'Save',
                    style: GoogleFonts.poppins(
                      fontSize: 11,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ],
          ),
          // : SizedBox.shrink(),
        ],
      ),
    );
  }
}
