/* eslint-disable @typescript-eslint/no-explicit-any */
import { InvoicePaymentStatus, OrderFlowType, OrderStatus } from "@/Constant/enums";
import { camelToSnake } from "../lib/Helper";
import { api } from "./Api";
import { getTestGroupInvoices } from "./Testing/TestResponses";
import { toast } from "react-toastify";

export async function createOrder(
  data: any,
  id: number,
  step3: any,
  paramOrderId?: any,
  completeOrder?: any
) {
  const apiResponses = step3;
  const snakeCaseData = camelToSnake(data);
  const { step } = snakeCaseData;
  let apiPath = "/customer/order/draft/initiate";
  let payload: any = {};
  if (step === 1) {
    const {
      package_details,
      // total_weight,
      service_type,
      order_flow_type,
      cod_details,
    } = snakeCaseData;
    payload = {
      order_type: 1, // Domestic = 1, International = 2
      service_type_id: service_type?.id,
      order_flow_type: order_flow_type?.id || OrderFlowType?.Forward,
      package_details: package_details,
      is_cod: cod_details?.cod_enabled || false,
      cod_amount: cod_details?.cod_amount || 0,
    };
    if (paramOrderId) payload.draft_order_id = paramOrderId;
  } else if (step === 2) {
    const {
      order_id,
      delivery_mobile,
      alt_delivery_mobile,
      customer_name,
      block_no,
      road_no,
      building_no,
      flat_no,
      remarks,
      destination_address,
      sender_address,
    } = snakeCaseData;
    apiPath = "/customer/order/draft/preview";
    const allData = JSON.parse(localStorage.getItem("ALL_DATA") || "{}")?.data;
    const addresses = allData?.addresses || [];
    const selectedAddress =
      addresses.length === 1 ? addresses[0] : addresses.find((a: any) => a.isPrimary === 1) || null;

    payload = destination_address ? (completeOrder?.step1?.orderFlowType?.id === OrderFlowType?.Return ? {
      customer_input_order_id: order_id,
      draft_order_id: apiResponses?.orderId || apiResponses?.step1?.id || 0,
      pickup_customer_name: "",
      pickup_mobile_number: "",
      pickup_alternate_number: "",
      pickup_block_id: 0,
      pickup_road_id: 0,
      pickup_building_id: 0,
      pickup_flat_or_office_number: "",
      delivery_instructions: remarks,
      destination_customer_name: customer_name,
      destination_mobile_number: delivery_mobile,
      destination_alternate_number: alt_delivery_mobile,
      destination_block_id: selectedAddress?.blockId,
      destination_road_id: selectedAddress?.road?.code,
      destination_building_id: selectedAddress?.building?.code,
      destination_flat_or_office_number: selectedAddress?.addressLineOne,
      // destination_address: destination_address,
      sender_address: destination_address ?? allData?.addressLineOne,    
    }
    : {
      customer_input_order_id: order_id,
      draft_order_id: apiResponses?.orderId || apiResponses?.step1?.id || 0,
      pickup_customer_name: "",
      pickup_mobile_number: "",
      pickup_alternate_number: "",
      pickup_block_id: 0,
      pickup_road_id: 0,
      pickup_building_id: 0,
      pickup_flat_or_office_number: "",
      delivery_instructions: remarks,
      destination_customer_name: customer_name,
      destination_mobile_number: delivery_mobile,
      destination_alternate_number: alt_delivery_mobile,
      destination_block_id: 0,
      destination_road_id: 0,
      destination_building_id: 0,
      destination_flat_or_office_number: "",
      destination_address: destination_address,
      sender_address: sender_address,
    }): (completeOrder?.step1?.orderFlowType?.id === OrderFlowType?.Return ? {
      customer_input_order_id: order_id,
      draft_order_id: apiResponses?.orderId || apiResponses?.step1?.id || 0,
      pickup_customer_name: "",
      pickup_mobile_number: "",
      pickup_alternate_number: "",
      pickup_block_id: block_no?.id,
      pickup_road_id: road_no?.code || road_no?.id,
      pickup_building_id: building_no?.code || building_no?.id || 1,
      pickup_flat_or_office_number: flat_no,
      delivery_instructions: remarks,
      destination_customer_name: customer_name,
      destination_mobile_number: delivery_mobile,
      destination_alternate_number: alt_delivery_mobile,
      destination_block_id: selectedAddress?.blockId,
      destination_road_id: selectedAddress?.road?.code,
      destination_building_id: selectedAddress?.building?.code,
      destination_flat_or_office_number: selectedAddress?.addressLineOne,
      destination_address: destination_address,
      sender_address: sender_address,
    } : {
      customer_input_order_id: order_id,
      draft_order_id: apiResponses?.orderId || apiResponses?.step1?.id || 0,
      pickup_customer_name: "",
      pickup_mobile_number: "",
      pickup_alternate_number: "",
      pickup_block_id: 0,
      pickup_road_id: 0,
      pickup_building_id: 0,
      pickup_flat_or_office_number: "",
      delivery_instructions: remarks,
      destination_customer_name: customer_name,
      destination_mobile_number: delivery_mobile,
      destination_alternate_number: alt_delivery_mobile,
      destination_block_id: block_no?.id,
      destination_road_id: road_no?.code || road_no?.id,
      destination_building_id: building_no?.code || building_no?.id || 1,
      destination_flat_or_office_number: flat_no,
      destination_address: destination_address,
      sender_address: sender_address,
    });
  } else if (step === 3) {
    apiPath = "/customer/order/draft/accept";
    payload = {
      draft_order_id: apiResponses?.orderId || apiResponses?.step1?.id || 0,
      ref_order_id: apiResponses?.refOrderId || 0,
    };
  }
  const [, response] = await api.post(apiPath, payload, true);
  return response;
}
export async function makePayment({
  pickup_date = "",
  pickup_slot_type = null,
}) {
  const [, response] = await api.post(
    "/customer/order/place",
    { pickup_preference_date: pickup_date, pickup_slot_type: pickup_slot_type },
    true
  );
  return response;
}
export async function placeOrderPreview() {
  const [, response] = await api.get(
    "/customer/order/draft/place/preview",
    true
  );
  return response;
}
export async function getOrders(
  type: "draft" | "in_progress" | "completed" | "cancel" = "draft",
  filters?: any,
  returnAllDetails?: boolean
): Promise<any[]> {
  //   {

  //     "orderId": "#1101",
  //     "packageNumber": "11",
  //     "packageWeight": "22",
  //     "packageValue": "21",
  //     "deliveryMobile": "7777777777",
  //     "deliveryPerson": "22",
  //     "blockNumber": {
  //         "id": 1,
  //         "name": "B1-Block"
  //     },
  //     "roadNumber": {
  //         "id": 1,
  //         "name": "Road -1"
  //     },
  //     "buildingNumber": {
  //         "id": 2,
  //         "name": "B4"
  //     },
  //     "flatNumber": "sdfa"
  // }
  const queryParams: any = {};

  if (true) {
    const rawParams = {
      page: filters?.page,
      limit: filters?.limit || "",
      search: filters?.search || "",
      filter_by_order_place_date: filters?.filter_by_order_place_date || "",
      filter_by_pickup_date: filters?.filter_by_pickup_date,
      filter_by_service_type: filters?.service_type_id || filters?.serviceTypes?.id || "",
      filter_by_delivery_status: filters?.filter_by_delivery_status || "",
      filter_by_cod_status: filters?.filter_by_cod_status || "",
      filter_by_payment_status: filters?.filter_by_payment_status || "",
      // Order filters
      filter_by_order_id: filters?.order_id || filters?.orderId || "",
      filter_by_customer_order_id: filters?.customer_order_id || filters?.customerOrderId || "",
      filter_by_delivery_mobile: filters?.delivery_mobile || filters?.deliveryMobile || "",
      filter_by_order_flow_type_id: filters?.order_flow_type_id || filters?.orderFlowType?.id || "",
      filter_by_order_status_id: filters?.order_status_id || filters?.orderStatus?.id || "",
      // Package filters
      filter_by_package_id: filters?.package_id || filters?.packageId || "",
      filter_by_package_no: filters?.packageNumber || "",
      filter_by_no_of_packages: filters?.no_of_packages || filters?.noOfPackages || "",
      filter_by_package_weight: filters?.package_weight || filters?.packageWeight || "",
      filter_by_package_value: filters?.package_value || filters?.packageValue || "",
      filter_by_package_status_id: filters?.package_status_id || filters?.packageStatus?.id || "",
      // Address filters
      filter_by_block_no: filters?.block_id || filters?.blockNumber?.id || "",
      filter_by_road_no: filters?.road_id || filters?.roadNumber?.id || "",
      filter_by_building_no: filters?.building_id || filters?.buildingNumber?.id || "",
      filter_by_flat_no: filters?.flat_number || filters?.flatNumber || "",
      // Legacy fields for backward compatibility
      filter_by_delivery_person: filters?.deliveryPerson || "",
      
      sort_by_id: filters?.sort_by_id || "",
      sort_by_order_id: filters?.sort_by_order_id || "",
      sort_by_receiver_name: filters?.sort_by_receiver_name || "",
      sort_by_sender_name: filters?.sort_by_sender_name || "",
      sort_by_service_type: filters?.sort_by_service_type || "",
      sort_by_number_of_packages: filters?.sort_by_number_of_packages || "",
      sort_by_total_weight: filters?.sort_by_total_weight || "",
      sort_by_delivery_status: filters?.sort_by_delivery_status || "",
      sort_by_cod_type: filters?.sort_by_cod_type || "",
      sort_by_shipping_charge: filters?.sort_by_shipping_charge || "",
      sort_by_payment_status: filters?.sort_by_payment_status || "",
      sort_by_created_by: filters?.sort_by_created_by || "",
      sort_by_created_at: filters?.sort_by_created_at || "",
      sort_by_updated_at: filters?.sort_by_updated_at || "",
    };

    Object.entries(rawParams).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== "") {
        queryParams[key] = value;
      }
    });
  }

  const [, response] =
    type === "in_progress"
      ? await api.get("/customer/order/list", true, {}, queryParams)
      : type === "completed"
      ? await api.get(
          "/customer/order/list",
          true,
          {},
          { ...queryParams, filter_by_delivery_status: OrderStatus?.Delivered }
        )
      : type === "cancel"
      ? await api.get(
          "/customer/order/list",
          true,
          {},
          { ...queryParams, filter_by_delivery_status: OrderStatus?.Cancelled }
        )
      : await api.get("/customer/order/draft/list", true);
  return returnAllDetails
    ? response
    : response?.data?.data || response?.data || [];
}
export async function getOrderDetails(id = ""): Promise<any[]> {
  const [, response] = await api.get(`/customer/order/details/${id}`, true);
  return response?.data || [];
}
export async function getDraftOrderDetails(id = ""): Promise<any[]> {
  const [, response] = await api.get(
    `/customer/order/draft/details/${id}`,
    true
  );
  return response?.data || [];
}
export async function deleteDraft(id = ""): Promise<any[]> {
  const [, response] = await api.delete(
    `/customer/order/draft/delete/${id}`,
    {},
    true
  );
  return response?.data || [];
}

export async function getPackages(params: any): Promise<any[]> {
  const [, response] = await api.get(
    "/customer/packages/list",
    true,
    {},
    params
  );
  return response?.data?.data || response?.data || [];
}

export async function getOrderHistroy(id = ""): Promise<any[]> {
  const [, response] = await api.get(`/customer/order/tracking/${id}`, true);
  return response?.data || [];
}

export async function getInvoices(params: any): Promise<any[]> {
  console.log(params,'sdf')
  const [, response] = await api.get(
    "/customer/invoice/list",
    true,
    {},
    params
  );
  return response?.data?.data || response?.data || [];
}

export async function getReceipts(params: {
  startDate: any;
  endDate: any;
  minAmount: any;
  maxAmount: any;
}): Promise<any[]> {
  const [, response] = await api.get(
    "/customer/receipt/list",
    true,
    {},
    params
  );
  return response?.data?.data || response?.data || [];
}

export async function getInvoiceDetails(id = ""): Promise<any[]> {
  const [, response] = await api.get(`/customer/invoice/details/${id}`, true);
  return response?.data || [];
}

export async function downloadInvoice(id = ""): Promise<any> {
  const [, response] = await api.get(
    `/customer/invoice/download/${id}`,
    true,
    {},
    {},
    "blob"
  );
  return response;
}

export async function downloadAddressPrint(id = ""): Promise<any> {
  const [, response] = await api.get(
    `/customer/order/address-print/${id}`,
    true,
    {},
    {},
    "blob"
  );
  return response;
}

export async function downloadBulkStickerPrint(
  size = "6*4",
  filters: any = {}
): Promise<any> {
  const params = new URLSearchParams({
    list_all: "true",
    size,
    ...filters, // spread filter parameters
  });

  const [, response] = await api.get(
    `/customer/order/sticker-print?${params.toString()}`,
    true,
    {},
    {},
    "blob"
  );
  return response;
}


export async function deletePackage(id = ""): Promise<any[]> {
  const [, response] = await api.delete(
    `/customer/order/package/delete/${id}`,
    {},
    true
  );
  return response?.data || [];
}

export async function getToSettlements(params: any): Promise<any[]> {
  const [, response] = await api.get(
    "/customer/settlements/to_settle/orders/list",
    true,
    {},
    params
  );
  return response?.data?.data || response?.data || [];
}

export async function getCompletedSettlements(params: {
  startDate: any;
  endDate: any;
  minAmount: any;
  maxAmount: any;
}): Promise<any[]> {
  const [, response] = await api.get(
    "/customer/settlements/completed/list",
    true,
    {},
    params
  );
  return response?.data?.data || response?.data || [];
}

export async function createReturnOrder({ id = "" }) {
  const [, response] = await api.post(`/customer/order/${id}/return`, {}, true);
  return response;
}

export async function markFuturePickup(id: number) {
  const [, response] = await api.put(`/customer/order/draft/future_pickup/${id}`, {}, true);
  return response;
}

export async function getGroupInvoices(params: any): Promise<any[]> {
  //page limit payment status     Pending = 1, Success = 2, PartiallyPaid = 3
  const TESTING = false;
  const [, response] = TESTING ? [null, getTestGroupInvoices]  : await api.get(
    "/customer/group_invoice/list",
    true,
    {},
    {...params, payment_status: params?.status ?? InvoicePaymentStatus?.Pending}
  );
  return response?.data?.data || response?.data || [];
}

export async function downloadGroupInvoice1(id: number): Promise<void> {
  try {
    const [, response] = await api.get(
      `/customer/group_invoice/download/${id}`,
      true,
      {},
      {},
      { responseType: "blob" } // 👈 force binary (important!)
    );

    if (!response) {
      toast.error("Download failed. No file received.");
      return;
    }

    const blob = new Blob([response], { type: "application/pdf" }); // adjust type if needed
    const url = window.URL.createObjectURL(blob);

    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", `invoice_${id}.pdf`);
    document.body.appendChild(link);
    link.click();
    link.remove();

    window.URL.revokeObjectURL(url);
    toast.success("Invoice downloaded successfully!");
  } catch (error: any) {
    console.error(error);
    toast.error("Failed to download invoice.");
  }
}

export async function getBulkOrders(
  filters?: any,
  returnAllDetails?: boolean
): Promise<any[]> {

  const [, response] = await api.get("/customer/order/bulk/list", true);
  return returnAllDetails
    ? response
    : response?.data?.data || response?.data || [];
}

export async function getBulkOrderDetails(id = ""): Promise<any[]> {
  const [, response] = await api.get(`/customer/order/bulk/details/${id}`, true);
  return response?.data || [];
}

export async function downloadSampleBulkOrder(): Promise<Blob | null> {
  const [, response] = await api.get(
    `/customer/order/bulk/sample/download`,
    true,
    {},
    {},
    'blob' // important: request as blob
  );
  return response || null;
  
  // const blob = await downloadSampleBulkOrder();
  // if (blob) {
  //   const url = window.URL.createObjectURL(blob);
  //   const link = document.createElement("a");
  //   link.href = url;
  //   link.setAttribute("download", "bulk_order_sample.xlsx"); // filename
  //   document.body.appendChild(link);
  //   link.click();
  //   link.remove();
  //   window.URL.revokeObjectURL(url);
  // }
}

export async function initiateBulkOrder(
  payload: any,
) {
//   {
//     "service_type_id": 1,
//     "pickup_date": "2025-08-30",
//     "pickup_time_slot_id": 1,
//     "pickup_customer_name": "Ajith",
//     "pickup_mobile_number": "85254525452",
//     "pickup_alternate_number": "365254253625", // optional
//     "pickup_block_id": 1,
//     "pickup_road_id": 1,
//     "pickup_building_id": 1,
//     "pickup_flat_or_office_number": "my office",// optional
//     "pickup_address_id": 1 
// }
  const [, response] = await api.post('/customer/order/bulk/initiate', payload, true);
  return response;
}

export async function bulkOrderFileUpload(payload: FormData) {
  const [, response] = await api.post(
    "/customer/order/bulk/upload",
    payload,
    true,
    { "Content-Type": "multipart/form-data" }
  );
  return response;
}


export async function placeBulkOrder(
  payload: any,
) {
//   {
//     "bulk_id": 1
// }
  const [, response] = await api.post('/customer/order/bulk/place', payload, true);
  return response;
}
