"use server";
import { BASE_API_URL } from "@/config/api";
// import { ServerFetchError, serverFetchJson, serverFetchWithNoContent } from "@/app/utils/fetchUtil";
import { revalidateTag } from "next/cache";
import { cache } from "react";
import { serverFetchJson, serverFetchWithNoContent } from "@/app/utils/fetchUtil";
import { QcItemResult } from "../settings/qcItem";
import { RecordsRes } from "../utils";
import { DoResult } from ".";
import { GridRowId, GridRowSelectionModel } from "@mui/x-data-grid";
import { GET } from "../auth/[...nextauth]/route";
import { stringify } from "querystring";

export interface CreateConsoDoInput {
  ids: GridRowSelectionModel;
}
export interface DoDetail {
  id: number;
  code: string;
  supplierCode: string;
  shopCode: string;
  shopName: string;
  currencyCode: string;
  orderDate: string;
  estimatedArrivalDate: string;
  completeDate: string;
  status: string;
  deliveryOrderLines: DoDetailLine[];
}

export interface DoDetailLine {
  id: number;
  itemNo: string;
  qty: number;
  price: number;
  status: string;
  itemName?: string;
  uomCode?: string;
  uom?: string;
  shortUom?: string;
}

export interface DoSearchAll {
  id: number;
  code: string;
  status: string;
  estimatedArrivalDate: string;
  orderDate: string;
  supplierName: string;
  shopName: string;
  deliveryOrderLines: DoDetailLine[];
}

export interface ReleaseDoRequest {
  id: number;
}

export interface ReleaseDoResponse {
  id: number;
  entity: { status: string }
}


export interface AssignByStoreRequest {
  storeId: string; // "2/F" or "4/F"
  assignTo: number;
}

export interface AssignByStoreResponse {
  id: number;
  code: string;
  name: string;
  type: string;
  message: string;
  errorPosition: string;
  entity: any;
}

export interface PrintDeliveryNoteRequest{
  deliveryOrderId: number;
  printerId: number;
  printQty: number;
  numOfCarton: number;
  isDraft: boolean;
  pickOrderId: number;
}

export interface PrintDeliveryNoteResponse{
  success: boolean;
  message?: string
}

export interface PrintDNLabelsRequest{
  deliveryOrderId: number,
  printerId: number,
  printQty: number,
  numOfCarton: number
}

export interface PrintDNLabelsRespone{
  success: boolean;
  message?: string
}

export const assignPickOrderByStore = cache(async (data: AssignByStoreRequest) => {
  return await serverFetchJson<AssignByStoreResponse>(`${BASE_API_URL}/doPickOrder/assign-by-store`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    })
})

export const releaseAssignedPickOrderByStore = cache(async (data: AssignByStoreRequest) => {
  return await serverFetchJson<AssignByStoreResponse>(`${BASE_API_URL}/doPickOrder/release-assigned-by-store`,
    {
      method: "POST",
      body: JSON.stringify(data),
      headers: { "Content-Type": "application/json" },
    })
})

export async function releaseDo(input: ReleaseDoRequest) {
  const response = await serverFetchJson<ReleaseDoResponse>(`${BASE_API_URL}/do/release`, {
      method: 'POST',
      body: JSON.stringify(input),
      headers: {
          'Content-Type': 'application/json',
      },
  });
  revalidateTag('do');
  return response;
}
export const preloadDo = () => {
  fetchDoList();
};

export const fetchDoList = cache(async () => {
  return serverFetchJson<DoResult[]>(`${BASE_API_URL}/do/list`, {
    next: { tags: ["doList"] },
  });
});

export const fetchDoDetail = cache(async (id: number) => {
  return serverFetchJson<DoDetail>(`${BASE_API_URL}/do/detail/${id}`, {
    method: "GET",
    headers: { "Content-Type": "application/json" },
    next: {
      tags: ["doDetail"]
    }
  });
});

export const fetchDoSearch = cache(async (code: string, shopName: string, status: string, orderStartDate: string, orderEndDate: string, estArrStartDate: string, estArrEndDate: string)=>{
  console.log(`${BASE_API_URL}/do/search-DO/${code}&${shopName}&${status}&${orderStartDate}&${orderEndDate}&${estArrStartDate}&${estArrEndDate}`);
  return serverFetchJson<DoSearchAll[]>(`${BASE_API_URL}/do/search-DO/${code}&${shopName}&${status}&${orderStartDate}&${orderEndDate}&${estArrStartDate}&${estArrEndDate}`,{
    method: "GET",
    next: { tags: ["doSearch"] }
  });
  
});

export async function printDN(request: PrintDeliveryNoteRequest){
  const params = new URLSearchParams();
  params.append('deliveryOrderId', request.deliveryOrderId.toString());
  params.append('printerId', request.printerId.toString());
  if (request.printQty !== null && request.printQty !== undefined) {
    params.append('printQty', request.printQty.toString());
  }
  params.append('numOfCarton', request.numOfCarton.toString());
  params.append('isDraft', request.isDraft.toString());
  params.append('pickOrderId', request.pickOrderId.toString());

  const response = await serverFetchWithNoContent(`${BASE_API_URL}/do/print-DN?${params.toString()}`,{
    method: "GET",
  });
  
  return { success: true, message: "Print job sent successfully (DN)" } as PrintDeliveryNoteResponse;
}

export async function printDNLabels(request: PrintDNLabelsRequest){
  const params = new URLSearchParams();
  params.append('deliveryOrderId', request.deliveryOrderId.toString());
  params.append('printerId', request.printerId.toString());
  if (request.printQty !== null && request.printQty !== undefined) {
    params.append('printQty', request.printQty.toString());
  }
  params.append('numOfCarton', request.numOfCarton.toString());

  const response = await serverFetchWithNoContent(`${BASE_API_URL}/do/print-DNLabels?${params.toString()}`,{
    method: "GET"
  });

  return { success: true, message: "Print job sent successfully (labels)"} as PrintDeliveryNoteResponse
}


