/* eslint-disable @typescript-eslint/no-explicit-any */
import CryptoJS from "crypto-js";
import { getCustomerAddresses } from "../Api/CustomerApi";
import { OrderStatus, PackageStatus, SettlementStatus, ShipmentStatus, ShipmentTypeForCustomer, UserTypes, ShipmentMode, InvoicePaymentStatus } from "@/Constant/enums";
import moment from "moment-timezone";
import Swal from "sweetalert2";
import { toast } from "react-toastify";
import { markFuturePickup } from "../Api/OrderApi";
const SECRET_KEY = "9mqwkJRdZXWc2GGo8-aHpSPKs2WtoVov"; // Store in .env ideally
type Primitive = string | number | boolean | null | undefined;
type JSONObject = { [key: string]: JSONValue };
type JSONArray = JSONValue[];
type JSONValue = Primitive | JSONObject | JSONArray | File;

// FOR HANDLE LOCATION INPUT TYPES
export const locationModeInput = () => {
  return {
    block: false,
    road: false,
    building: true,
  };
};

/**
 * Converts camelCase keys to snake_case recursively
 */
export const convertKeysToSnakeCase = <T extends JSONValue>(obj: T): T => {
  if (obj === null || typeof obj !== "object" || obj instanceof File) {
    return obj;
  }

  if (Array.isArray(obj)) {
    return obj.map(convertKeysToSnakeCase) as T;
  }

  const result: { [key: string]: JSONValue } = {};

  for (const [key, value] of Object.entries(obj)) {
    const snakeKey = toSnakeCase(key);
    result[snakeKey] = convertKeysToSnakeCase(value);
  }

  return result as T;
};

/**
 * Helper to convert camelCase string to snake_case
 */
const toSnakeCase = (str: string): string =>
  str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
export const convertSnakeToCamelCase = (obj: any): any => {
  if (Array.isArray(obj)) {
    return obj.map((item) => convertSnakeToCamelCase(item)); // Handle arrays
  } else if (typeof obj === "object" && obj !== null) {
    const newObj: { [key: string]: any } = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        // Convert snake_case to camelCase
        const newKey = key.replace(/_([a-z])/g, (match, letter) =>
          letter.toUpperCase()
        );
        // Ensure first letter is lowercase for camelCase
        const camelCasedKey = newKey.charAt(0).toLowerCase() + newKey.slice(1);

        // Recursively convert values if they are objects or arrays
        newObj[camelCasedKey] = convertSnakeToCamelCase(obj[key]);
      }
    }
    return newObj;
  } else {
    return obj; // Return the value as is if it's a primitive type
  }
};

export const convertCamelToSnakeCase = (obj: any): any => {
  if (Array.isArray(obj)) {
    return obj.map(convertCamelToSnakeCase); // Handle arrays
  } else if (obj !== null && typeof obj === "object") {
    return Object.keys(obj).reduce(
      (newObj: { [key: string]: any }, key: string) => {
        const newKey = key.replace(
          /([A-Z])/g,
          (match, letter) => `_${letter.toLowerCase()}`
        );
        newObj[newKey] = convertCamelToSnakeCase(obj[key]);
        return newObj;
      },
      {}
    );
  } else {
    return obj; // Return the value as is if it's a primitive type
  }
};

export const camelToSnake = (obj: any): any => {
  if (Array.isArray(obj)) {
    return obj.map(camelToSnake);
  } else if (obj !== null && obj !== undefined && typeof obj === "object") {
    return Object.keys(obj).reduce((acc, key) => {
      const snakeKey = key.replace(
        /[A-Z]/g,
        (letter) => `_${letter.toLowerCase()}`
      );
      acc[snakeKey] = camelToSnake(obj[key]);
      return acc;
    }, {} as any);
  }
  return obj;
};

export const cryptoHandler1 = (
  id: string | number,
  type: "encrypt" | "decrypt"
): string => {
  if (!id) {
    throw new Error("Invalid ID passed to cryptoHandler");
  }

  try {
    if (type === "encrypt") {
      // Convert to string and ensure consistent encoding
      const stringId = id.toString();
      const encrypted = CryptoJS.AES.encrypt(stringId, SECRET_KEY).toString();
      // URL-safe encoding to prevent issues with special characters
      return encodeURIComponent(encrypted);
    }

    if (type === "decrypt") {
      // URL-safe decoding first
      const decoded = decodeURIComponent(id.toString());
      const bytes = CryptoJS.AES.decrypt(decoded, SECRET_KEY);
      const decrypted = bytes.toString(CryptoJS.enc.Utf8);

      // Validate decrypted value
      if (!decrypted) {
        throw new Error("Decryption failed - invalid or corrupted data");
      }

      return decrypted;
    }

    throw new Error(
      'Invalid type passed to cryptoHandler. Use "encrypt" or "decrypt".'
    );
  } catch (error: any) {
    console.error("Encryption/Decryption error:", error);
    throw new Error(`Failed to ${type} ID: ${error.message}`);
  }
};

export const cryptoHandler = (
  id: string | number,
  type: "encrypt" | "decrypt"
): string => {
  console.error(type);
  return id?.toString();
};

export const updateAddressInSession = async () => {
  const response = await getCustomerAddresses({
    order_by: "is_primary",
    sort_by: "desc",
  });
  const existingAllData = JSON.parse(localStorage.getItem("ALL_DATA") || "{}");
  const primaryAddress = response?.data?.[0] || {};
  const latestPhone = primaryAddress?.phone || existingAllData?.data?.phone;
  const updatedAllData = {
    ...existingAllData,
    data: {
      ...existingAllData.data,
      phone: latestPhone,
      addresses: response?.data || [],
    },
  };
  // Update the full ALL_DATA blob
  localStorage.setItem("ALL_DATA", JSON.stringify(updatedAllData));
};

// Helper to format code and name as 'code - name' if both exist
function formatCodeName(obj?: { code?: string; name?: string }): string {
  if (!obj) return "";
  if (obj.code && obj.name) return `${obj.code} - ${obj.name}`;
  if (obj.code) return obj.code;
  if (obj.name) return obj.name;
  return "";
}

export const getFormattedAddress = (
  defaultData?: any,
  type?: string
): string => {
  const storedUser = localStorage.getItem("ALL_DATA");
  const allData = storedUser ? JSON.parse(storedUser)?.data : null;
  if (defaultData) {
    if (type === "order_summary") {
      if (allData?.addressFormatType?.name !== "Standard")
        return `${
          defaultData?.destinationAddress ??
          defaultData?.order?.destinationAddress
        }`;
      else
        return [
          defaultData?.destinationFlatOrOfficeNumber &&
            `${defaultData.destinationFlatOrOfficeNumber}`,
          defaultData?.destination_flat_or_office_number &&
            `${defaultData.destination_flat_or_office_number}`,
          formatCodeName(defaultData?.destination_building_details),
          formatCodeName(defaultData?.destination_road_details),
          formatCodeName(defaultData?.destination_block_details),
        ]
          .filter(Boolean)
          .join(", ");
    }
    else if (type === "order_summary_return") {
      if (allData?.addressFormatType?.name !== "Standard")
        return `${
          defaultData?.senderAddress ??
          defaultData?.order?.senderAddress
        }`;
      else
        return [
          defaultData?.pickupFlatOrOfficeNumber &&
            `${defaultData.pickupFlatOrOfficeNumber}`,
          defaultData?.pickup_flat_or_office_number &&
            `${defaultData.pickup_flat_or_office_number}`,
          formatCodeName(defaultData?.pickup_building_details),
          formatCodeName(defaultData?.pickup_road_details),
          formatCodeName(defaultData?.pickup_block_details),
        ]
          .filter(Boolean)
          .join(", ");
    }
    else if (type === "order_view")
      return [
        defaultData?.destinationFlatOrOfficeNumber &&
          `${defaultData.destinationFlatOrOfficeNumber}`,
        defaultData?.destination_flat_or_office_number &&
          `${defaultData.destination_flat_or_office_number}`,
        formatCodeName(defaultData?.destination_building_details),
        formatCodeName(defaultData?.destination_road_details),
        formatCodeName(defaultData?.destination_block_details),
      ]
        .filter(Boolean)
        .join(", ");
    else
      return [
        defaultData?.flatDetails ? defaultData?.flatDetails : "",
        formatCodeName(defaultData?.buildingDetails),
        formatCodeName(defaultData?.roadDetails),
        formatCodeName(defaultData?.blockDetails),
      ]
        .filter(Boolean)
        .join(", ");
  } else {
    const storedUser = localStorage.getItem("ALL_DATA");
    const allData = storedUser ? JSON.parse(storedUser)?.data : null;
    if (allData?.addresses?.length > 0) {
      const address = allData?.addresses?.length ? allData.addresses[0] : null;
      return [
        address?.addressLineOne || "",
        address?.addressLineTwo || "",
        formatCodeName(address?.building || allData?.buildingDetails),
        formatCodeName(address?.road || allData?.roadDetails),
        formatCodeName(address?.block || allData?.blockDetails),
      ]
        .filter(Boolean)
        .join(", ");
    } else
      return [
        allData?.addressLineOne || "",
        allData?.addressLineTwo || "",
        formatCodeName(allData?.buildingDetails),
        formatCodeName(allData?.roadDetails),
        formatCodeName(allData?.blockDetails),
      ]
        .filter(Boolean)
        .join(", ");
  }
};

export const checkAddressesAvailable = (): boolean => {
  try {
    const allData = localStorage.getItem("ALL_DATA");
    if (!allData) return false;

    const parsedData = JSON.parse(allData);
    return !!(
      parsedData?.data?.addresses && parsedData.data.addresses.length > 0
    );
  } catch (error) {
    console.error("Error checking addresses:", error);
    return false;
  }
};

// Returns true if there is at least one primary address in localStorage
export const checkPrimaryAddressAvailable = (): boolean => {
  try {
    const allData = localStorage.getItem("ALL_DATA");
    if (!allData) return false;

    const parsedData = JSON.parse(allData);
    const addresses = parsedData?.data?.addresses || [];
    return addresses.some((addr: any) => addr.isPrimary);
  } catch (error) {
    console.error("Error checking primary address:", error);
    return false;
  }
};

export const formatSpaceForText = (text: string) => {
  if (!text) return "";
  return text
    .replace(/([a-z])([A-Z])/g, "$1 $2") // Insert space before capitals
    .replace(/^./, (str) => str.toUpperCase()) // Capitalize first letter
    .trim();
};

export const getOrderStatusInfo = (statusId: number, order: any) => {
  switch (statusId) {
    case OrderStatus.Open:
      return {
        text: formatSpaceForText(order?.status?.name) || "Open",
        color: "open-status",
      };
    case OrderStatus.PendingPickup:
      return {
        text: formatSpaceForText(order?.status?.name) || "Pending Pickup",
        color: "pending-pkg",
      };
    case OrderStatus.PartiallyPickedUp:
      return {
        text: formatSpaceForText(order?.status?.name) || "Partially Pickup",
        color: "pending-pkg",
      };
    case OrderStatus.PickedUp:
      return {
        text: formatSpaceForText(order?.status?.name) || "Pickup",
        color: "picked-up",
      };
    case OrderStatus.PartiallyInStorage:
      return {
        text: formatSpaceForText(order?.status?.name) || "Partially In Storage",
        color: "in-storage",
      };
    case OrderStatus.InStorage:
      return {
        text: formatSpaceForText(order?.status?.name) || "In Storage",
        color: "in-storage",
      };
    case OrderStatus.PartiallyOutForDelivery:
      return {
        text:
          formatSpaceForText(order?.status?.name) ||
          "Partially Out For Delivery",
        color: "partially-delivered",
      };
    case OrderStatus.OutForDelivery:
      return {
        text: formatSpaceForText(order?.status?.name) || "Out For Delivery",
        color: "picked-up",
      };
    case OrderStatus.PartiallyDelivered:
      return {
        text: formatSpaceForText(order?.status?.name) || "Partially Delivered",
        color: "delivered",
      };
    case OrderStatus.Delivered:
      return {
        text: formatSpaceForText(order?.status?.name) || "Delivered",
        color: "delivered",
      };
    case OrderStatus.Exception:
      return {
        text: formatSpaceForText(order?.status?.name) || "Exception",
        color: "badge-red",
      };
    case OrderStatus.Cancelled:
      return {
        text: formatSpaceForText(order?.status?.name) || "Cancelled",
        color: "badge-info",
      };
    default:
      return {
        text: formatSpaceForText(order?.status?.name) || "Placed",
        color: "badge-info",
      };
  }
};

export const getPackageStatusInfo = (statusId: number, order: any) => {
  const OrderStatus = PackageStatus;
  switch (statusId) {
    case OrderStatus.Open:
      return {
        text: order?.status?.name || "Placed",
        color: "badge-info",
      };
    case OrderStatus.PendingPickup:
      return {
        text: order?.status?.name || "Pending Pickup",
        color: "badge-info",
      };
    case OrderStatus.PickedUp:
      return {
        text: order?.status?.name || "Pickup",
        color: "badge-purple2",
      };
    case OrderStatus.InStorage:
      return {
        text: order?.status?.name || "In Storage",
        color: "badge-purple2",
      };
    case OrderStatus.OutForDelivery:
      return {
        text: order?.status?.name || "Out For Delivery",
        color: "badge-skyblue",
      };
    case OrderStatus.Delivered:
      return {
        text: order?.status?.name || "Delivered",
        color: "badge-success",
      };
    case OrderStatus.Exception:
      return {
        text: order?.status?.name || "Exception",
        color: "badge-red",
      };
    default:
      return {
        text: order?.status?.name || "Placed",
        color: "badge-info",
      };
  }
};

export const getSettlementStatusInfo = (statusId: number, order: any) => {
  const OrderStatus = SettlementStatus;
  switch (statusId) {
    case OrderStatus.Pending:
      return {
        text: order?.status?.name || "",
        color: "badge-info",
      };
    case OrderStatus.Settled:
      return {
        text: order?.status?.name || "",
        color: "badge-success",
      };
    case OrderStatus.Cancelled:
      return {
        text: order?.status?.name || "",
        color: "badge-red",
      };
    default:
      return {
        text: order?.status?.name || "",
        color: "badge-info",
      };
  }
};

export const getGroupInvoiceStatusInfo = (statusId: number, order: any) => {
  const OrderStatus = InvoicePaymentStatus;
  switch (statusId) {
    case OrderStatus.Pending:
      return {
        text: order?.paymentStatus?.name || "",
        color: "badge-red",
      };
    case OrderStatus.PartiallyPaid:
      return {
        text: order?.paymentStatus?.name || "",
        color: "badge-info",
      };
    case OrderStatus.Success:
      return {
        text: order?.paymentStatus?.name || "",
        color: "badge-success",
      };
    default:
      return {
        text: order?.paymentStatus?.name || "",
        color: "badge-red",
      };
  }
};

export const getShipmentStatusInfo = (statusId: number, order: any) => {
  const ShipmentStaus = ShipmentStatus;
  switch (statusId) {
    case ShipmentStaus.Created:
      return {
        text: order?.status?.name || "",
        color: "badge-info",
      };
    case ShipmentStaus.Shipped:
      return {
        text: order?.status?.name || "",
        color: "badge-purple2",
      };
    case ShipmentStaus.Arrived:
      return {
        text: order?.status?.name || "",
        color: "badge-skyblue",
      };
    case ShipmentStaus.Collected:
        return {
          text: order?.status?.name || "",
          color: "badge-success",
        };
    default:
      return {
        text: order?.status?.name || "",
        color: "badge-info",
      };
  }
};

export const getSettlementServiceType = (statusId: number, details: any) => {
  const ShipmentType = ShipmentTypeForCustomer;
  switch (statusId) {
    case ShipmentType.Import:
      return {
        text: details?.shipmentTypeForCustomer?.name || "",
        color: "card-status",
      };
    case ShipmentType.Export:
      return {
        text: details?.shipmentTypeForCustomer?.name || "",
        color: "badge-domestic",
      };
    default:
      return {
        text: details?.shipmentTypeForCustomer?.name || "",
        color: "card-status",
      };
  }
};

export const shipmentModeOfTransportIconsById = (id: number) => {
  switch (id) {
    case ShipmentMode.Road:
      return (
        <i
          title="Road"
          className="ri icon-30 text-end ri-truck-line font-18 w-auto color-primary"
        />
      );
    case ShipmentMode.Sea:
      return (
        <i
          title="Sea"
          className="ri icon-30 text-end ri-ship-line font-18 w-auto color-primary"
        />
      );
    case ShipmentMode.Air:
      return (
        <i
          title="Air"
          className="ri icon-30 text-end ri-plane-line font-18 w-auto color-primary"
        />
      );
    default:
      return null; // No icon for unknown id
  }
};

export const stringFormatterQuoteStart = (string: string) => {
  if (typeof string == "string") {
    if (!string) return "";

    // Convert the entire string to lowercase
    string = string.toLowerCase();

    // Find the first alphabetical character and capitalize it
    return string.replace(/^[^a-zA-Z]*([a-zA-Z])/, (match, char) => {
      return match.replace(char, char.toUpperCase());
    });
  } else return string;
};

export const amountFormat = (amount: string): string => {
  const num = parseFloat(amount);
  if (isNaN(num)) return "0.000";
  return num.toFixed(3).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

export const formatDate = (date: string | Date): string => {
  if (!date) return "";
  return moment(date).format("ddd, Do MMM 'YYYY");
};

export const formatTime = (dateString: string) => {
  return moment(dateString).format("h:mm A");
};

export const amountFormatWithCurrency = (amount: any) => {
  if (!amount) return "BHD 0.000";

  const num = parseFloat(amount);
  return `BHD ${num.toLocaleString("en-IN", {
    minimumFractionDigits: 3,
    maximumFractionDigits: 3,
  })}`;
};

export const amountInWordWithCurrency = (amount: any) => {
  if (amount === null || amount === undefined || isNaN(Number(amount)))
    return "BHD Zero Only";

  const num = parseFloat(amount);
  const integerPart = Math.floor(num);
  const decimalPart = Math.round((num - integerPart) * 1000); // 3 decimal places for fils

  // Helper arrays for number to words
  const ones = [
    "",
    "One",
    "Two",
    "Three",
    "Four",
    "Five",
    "Six",
    "Seven",
    "Eight",
    "Nine",
    "Ten",
    "Eleven",
    "Twelve",
    "Thirteen",
    "Fourteen",
    "Fifteen",
    "Sixteen",
    "Seventeen",
    "Eighteen",
    "Nineteen",
  ];
  const tens = [
    "",
    "",
    "Twenty",
    "Thirty",
    "Forty",
    "Fifty",
    "Sixty",
    "Seventy",
    "Eighty",
    "Ninety",
  ];
  const scales = ["", "Thousand", "Million", "Billion"];

  function numberToWords(n: number): string {
    if (n === 0) return "Zero";
    let word = "";
    let scale = 0;
    while (n > 0) {
      let chunk = n % 1000;
      if (chunk) {
        let chunkWord = "";
        if (chunk > 99) {
          chunkWord += ones[Math.floor(chunk / 100)] + " Hundred ";
          chunk = chunk % 100;
        }
        if (chunk > 19) {
          chunkWord += tens[Math.floor(chunk / 10)] + " ";
          chunkWord += ones[chunk % 10] + " ";
        } else if (chunk > 0) {
          chunkWord += ones[chunk] + " ";
        }
        word = chunkWord + (scales[scale] ? scales[scale] + " " : "") + word;
      }
      n = Math.floor(n / 1000);
      scale++;
    }
    return word.trim();
  }

  let result = `BHD ${numberToWords(integerPart)}`;
  if (decimalPart > 0) {
    result += ` and ${numberToWords(decimalPart)} Fils`;
  } else {
    result += " Only";
  }
  return result;
};

export const serviceTypeBasedDate = (data: any) => {
  if (!data?.name) return formatDate(moment().toDate());

  const today = moment();

  switch (data.name.toLowerCase()) {
    case "next day":
      return formatDate(today.add(1, "day").toDate());
    case "same day":
    case "express":
      return formatDate(today.toDate());
    default:
      return formatDate(today.toDate());
  }
};

/**
 * Country phone number length mapping (ISO2 code to length or [min, max])
 * Extend as needed. Use ISO2 (e.g. 'IN', 'BH', 'AE', 'US', etc.)
 */
export const COUNTRY_PHONE_LENGTHS: Record<string, number | [number, number]> =
  {
    BH: 8, // Bahrain
    IN: 10, // India
    AE: 9, // UAE
    US: 10, // USA
    PK: 10, // Pakistan
    SA: 9, // Saudi Arabia
    QA: 8, // Qatar
    KW: 8, // Kuwait
    OM: 8, // Oman
    // ...add more as needed
  };

/**
 * Validates a phone number's length for a given country.
 * @param phone The phone number (digits only or with country code)
 * @param countryIso2 The ISO2 country code (e.g. 'IN', 'BH', 'AE')
 * @returns { isValid: boolean, error?: string }
 */
// export function validatePhoneNumberByCountry(
//   phone: string,
//   countryIso2: string
// ): { isValid: boolean; error?: string } {
//   if (!phone) {
//     return { isValid: false, error: "Contact number is required" };
//   }
//   let digits = phone.replace(/\D/g, "");
//   // Special handling for Bahrain (BH): strip country code 973 if present
//   if (
//     countryIso2?.toUpperCase?.() === "BH" &&
//     digits.startsWith("973") &&
//     digits.length > 8
//   ) {
//     digits = digits.slice(3);
//   }
//   const rule = COUNTRY_PHONE_LENGTHS[countryIso2?.toUpperCase?.()];
//   if (!rule) {
//     // Fallback: require 6-15 digits if country not mapped
//     if (digits.length < 6 || digits.length > 15) {
//       return {
//         isValid: false,
//         error: "Contact number must be between 6 and 15 digits",
//       };
//     }
//     return { isValid: true };
//   }
//   if (typeof rule === "number") {
//     if (digits.length !== rule) {
//       return {
//         isValid: false,
//         error: `Contact number must be exactly ${rule} digits`,
//       };
//     }
//     return { isValid: true };
//   }
//   // rule is [min, max]
//   const [min, max] = rule;
//   if (digits.length < min || digits.length > max) {
//     return {
//       isValid: false,
//       error: `Contact number must be between ${min} and ${max} digits`,
//     };
//   }
//   return { isValid: true };
// }
export function validatePhoneNumberByCountry(
  phone: string,
  countryIso2: string
): { isValid: boolean; error?: string } {
  if (!phone) {
    return { isValid: false, error: "Contact number is required" };
  }

  // Keep only digits
  let digits = phone.replace(/\D/g, "");

  // Special handling for Bahrain (BH): strip leading country code (973 / 00973)
  if (countryIso2?.toUpperCase() === "BH") {
    if (digits.startsWith("00973")) {
      digits = digits.slice(5);
    } else if (digits.startsWith("973")) {
      digits = digits.slice(3);
    }
  }

  // Special handling for India (IN): strip leading 91 / 0091, must be 10 digits
  if (countryIso2?.toUpperCase() === "IN") {
    if (digits.startsWith("0091")) {
      digits = digits.slice(4);
    } else if (digits.startsWith("91") && digits.length > 10) {
      digits = digits.slice(2);
    }

    if (digits.length !== 10) {
      return {
        isValid: false,
        error: "Indian contact number must be exactly 10 digits",
      };
    }

    return { isValid: true };
  }

  // Lookup rule for other countries
  const rule = COUNTRY_PHONE_LENGTHS[countryIso2?.toUpperCase?.() ?? ""];

  if (!rule) {
    // Fallback: generic 6–15 digits
    if (digits.length < 6 || digits.length > 15) {
      return {
        isValid: false,
        error: "Contact number must be between 6 and 15 digits",
      };
    }
    return { isValid: true };
  }

  if (typeof rule === "number") {
    // Exact length rule
    if (digits.length !== rule) {
      return {
        isValid: false,
        error: `Contact number must be exactly ${rule} digits`,
      };
    }
    return { isValid: true };
  }

  // Rule is [min, max]
  const [min, max] = rule;
  if (digits.length < min || digits.length > max) {
    return {
      isValid: false,
      error: `Contact number must be between ${min} and ${max} digits`,
    };
  }

  return { isValid: true };
}


export const handleFuturePickup = async (orderId: number | undefined, orderDetail: any): Promise<boolean> => {
  if (!orderId) return false;

  const result = await Swal.fire({
    title: `${orderDetail?.isFuturePickup ? "Unmark ": "Mark "} as Future Pickup?`,
    text: `Are you sure you want to ${orderDetail?.isFuturePickup ? "unmark ": "mark "} this order for future pickup?`,
    icon: "question",
    showCancelButton: true,
    confirmButtonText: `Yes, ${orderDetail?.isFuturePickup ? "unmark ": "mark "} it`,
    customClass: {
      confirmButton: "delybell-primary px-4",
      cancelButton: "delybell-dark",
    },
    reverseButtons: true,
  });

  if (!result.isConfirmed) return false;

  try {
    const response = await markFuturePickup(orderId);
    if (response?.status) {
      toast.success(response?.message || "This order is marked for future pickup.");
      return true;
    } else {
      toast.error(response?.message || "Failed to mark order.");
      return false;
    }
  } catch (error: any) {
    toast.error(
      error?.response?.data?.message ||
      error?.message ||
      "Failed to mark order. Please try again."
    );
    return false;
  }
};

export const returnShipmentDetails = (details: any) => {

  const vesselName = details?.cargoName?.toLowerCase() || "";
  let logoPath = "/images/international/no-image.jpg"; // default fallback

  if (vesselName.includes("dhl")) {
    logoPath = "/images/app/dhl-express-logo.png";
  } else if (vesselName.includes("aramex")) {
    logoPath = "/images/app/aramex-logo.png";
  } else if (vesselName.includes("fedex")) {
    logoPath = "/images/app/fedex-logo.png";
  }
  return {
    _name: details?.shipmentTypeForCustomer?.id === ShipmentTypeForCustomer.Import 
    ? `${details?.shipped_by_warehouse_id_details?.code ?? ''} ${details?.shipped_by_warehouse_id_details?.name ? `-${details?.shipped_by_warehouse_id_details?.name ?? ''}` : ''}` 
    : `${details?.received_by_warehouse_id_details?.code ?? ''} ${details?.received_by_warehouse_id_details?.name ? `-${details?.received_by_warehouse_id_details?.name ?? ''}` : ''}`,
    _address: details?.shipmentTypeForCustomer?.id === ShipmentTypeForCustomer.Import 
    ? `${details?.shipped_by_warehouse_id_details?.addressLineOne ?? ''}` 
    : `${details?.received_by_warehouse_id_details?.addressLineOne ?? ''}`,
    _logo: logoPath
  }
}

export const truncateWithTooltip = (text: string, limit: number = 20) => {
  const isTruncated = text?.length > limit;
  return {
    text: isTruncated ? text.slice(0, limit) + '...' : text,
    tooltip: text ?? '',
  };
};

export const isServiceAvailable = (serviceName: string) => {
  const timezone = process.env.NEXT_PUBLIC_TZ || "Asia/Bahrain";
  const now = moment.tz(timezone);
  const hour = now.hour();
  switch (serviceName) {
    case "Same Day":
      return hour >= 0 && hour < 12;
    case "Express":
      return hour >= 0 && hour < 16;
    case "Next Day":
      return hour >= 0 && hour < 19;
    default:
      return false;
  }
};


export const BasicInfoFields = (userType: number) => {
  const baseFields = [
    {
      name: "company_name",
      label: "Organization Name",
      placeholder: "Enter Organization Name",
    },
    {
      name: "company_registration_number",
      label: "Organization Reg. No.",
      placeholder: "Enter Organization Reg. No.",
    },
    {
      name: "first_name",
      label: "First Name",
      placeholder: "Enter First Name",
    },
    {
      name: "last_name",
      label: "Last Name",
      placeholder: "Enter Last Name",
    },
    {
      name: "first_name_ar",
      label: "First Name (Arabic)",
      placeholder: "Enter First Name (Arabic)",
    },
    {
      name: "last_name_ar",
      label: "Last Name (Arabic)",
      placeholder: "Enter Last Name (Arabic)",
    },
    {
      name: "email",
      label: "Email Address",
      placeholder: "Enter Email Address",
      disabled: true,
    },
    {
      name: "phone",
      label: "Mobile Number",
      placeholder: "Enter Mobile Number",
      disabled: true,
    },
    {
      name: "vat_number",
      label: "VAT Number",
      placeholder: "Enter VAT Number",
    },
    {
      name: "nationality_id",
      label: "Nationality",
      placeholder: "Enter Nationality",
      select_box: true,
      optionsKey: "nationalities",
    },
    {
      name: "address_line_one",
      label: "Address",
      placeholder: "Enter Address",
      as: "textarea",
      col_lg: 6,
    },
  ];

  const internationalFields =
    userType === UserTypes.InternationalCustomer
      ? [
          {
            name: "designation",
            label: "Designation",
            placeholder: "Enter Designation",
          },
          {
            name: "contact_email",
            label: "Contact Email",
            placeholder: "Enter Contact Email",
          },
          // {
          //   name: "address_line_one",
          //   label: "Address",
          //   placeholder: "Enter Address",
          //   as: "textarea",
          //   col_lg: 6,
          // },
        ]
      : [];

  return [...baseFields, ...internationalFields];
};

export const alternativeInformationFields = (userType: number) => {
  if(userType === UserTypes.InternationalCustomer) 
    return [
      {
        name: "alt_first_name",
        label: "First Name",
        placeholder: "Enter First Name",
      },
      {
        name: "alt_first_name_ar",
        label: "First Name (Arabic)",
        placeholder: "Enter First Name (Arabic)",
      },
      {
        name: "alt_last_name",
        label: "Last Name",
        placeholder: "Enter Last Name",
      },
      {
        name: "alt_last_name_ar",
        label: "Last Name (Arabic)",
        placeholder: "Enter Last Name (Arabic)",
      },
      {
        name: "alt_designation",
        label: "Designation",
        placeholder: "Enter Designation",
      },
      {
        name: "alt_phone",
        label: "Phone",
        placeholder: "Enter Phone",
      },
      {
        name: "alt_email",
        label: "Email",
        placeholder: "Enter Email",
      },
    ];
  else return [];
}

export const toUpperCaseString = (str: string) => str?.toUpperCase();

export const dateFormat = (date: any) => {
  return moment(date).format("DD MMM YYYY");
};

export const dateFormaShipmentCard = (date: any) => {
  const timezone = process.env.NEXT_PUBLIC_TZ || "Asia/Bahrain";
  return date ? moment(date).tz(timezone).format("ddd, DD MMM YY") : 'Not Selected';
};