import { withHeaders } from "@/record-management/services/api/withHeaders";
import {
  CreateLetterDto,
  CreateUserDto,
  DocumentPayloadDto,
  FayidaUserDto,
} from "@/shared/dto/External-Portal/External-PortalDto";
import axiosInstance from "@/shared/services/axiosInstance";
import recordAxiosInstance from "@/shared/services/recordAxiosInstance";
import { AxiosResponse } from "axios";
import { id } from "date-fns/locale";
import Cookies from "js-cookie";
import { Upload } from "../hooks/useMyUpload";
import { FileInfo } from "@/shared/services/complaintService";
import {
  registerWithFayda,
  registerWithEtrade,
  SetFayidaPasswordPayload,
  verifyEtradeOtp,
  type VerifyEtradeOtpPayload,
} from "@/shared/services/authService";
import { resolveEtradePhoneForSignup } from "@/complaints/services/etradeTinService";

export interface LatestUploadInfo {
  docId: string;
  uploadId: string | null;
  fileInfo: FileInfo;
  presigned: string;
}
export interface TradeLicensePayload {
  tin: string;
  licenseNo: string;
  phoneNumber?: string;
}

/** @deprecated Use TradeLicensePayload */
export interface TradeLicenseSigninPayload {
  mode: "signin";
  licenseNo: string;
}

/** @deprecated Use TradeLicensePayload */
export interface TradeLicenseSignupPayload {
  mode: "signup";
  tin: string;
  licenseNo: string;
}
export interface SetETradePasswordPayload {
  licenseNo: string;
  verificationCode: string;
  newPassword: string;
  confirmPassword: string;
}

export interface UploadDetails {
  presigned: string;
  // add other fields if needed
}

export interface externalParam {
  skip?: number;
  take?: number;
  order?: string;
  orderBy?: string;
}
export const createExternalLetterRecord = async (
  body: CreateLetterDto,
): Promise<any> => {
  return recordAxiosInstance.post("/records/self-non-smart-record-pdf", body, {
    headers: withHeaders(),
  });
};

export const registerExternalUser = async (
  body: CreateUserDto,
): Promise<AxiosResponse> => {
  return axiosInstance.post("/auth/signup", body, {
    headers: withHeaders(),
  });
};
export const registerFayidaUser = async (
  body: FayidaUserDto,
): Promise<AxiosResponse> => {
  return registerWithFayda(body);
};

export const signinFayidaUser = async (
  body: FayidaUserDto,
): Promise<AxiosResponse> => {
  return registerWithFayda(body);
};

export const signupFayidaUser = async (
  body: FayidaUserDto,
): Promise<AxiosResponse> => {
  return registerWithFayda(body);
};

export const getExternalLetterRecord = async (
  params?: externalParam,
): Promise<AxiosResponse> => {
  return recordAxiosInstance.get("/records/self-non-smart-records", {
    params,
    headers: withHeaders(),
  });
};

export const docuemntUpload = async (
  body: DocumentPayloadDto,
): Promise<AxiosResponse> => {
  return axiosInstance.post("/user-documents", body, {
    headers: withHeaders(),
  });
};

export const submitApplication = async (): Promise<any[]> => {
  const token = Cookies.get("auth-token");
  // get token from wherever you store it
  if (!token) return [];
  try {
    const response = await axiosInstance.patch("/users/submit-application", {
      headers: withHeaders(),
    });
    return response.data?.items ?? []; // assuming API returns { items: [...] }
  } catch (err) {
    console.error("Failed to fetch user uploads", err);
    return []; // fallback to empty array on error
  }
};

export const getMyUploads = async (): Promise<Upload[]> => {
  const token = Cookies.get("auth-token");
  // get token from wherever you store it
  if (!token) return []; // return empty if no token

  try {
    const response = await axiosInstance.get("/user-documents/mine/", {
      headers: withHeaders(),
    });
    return response.data?.items ?? []; // assuming API returns { items: [...] }
  } catch (err) {
    console.error("Failed to fetch user uploads", err);
    return []; // fallback to empty array on error
  }
};

export const getMyUploadedFiles = async (
  id: string,
): Promise<AxiosResponse> => {
  return axiosInstance.get(`/user-documents/list-with-presigned/${id}`, {
    headers: withHeaders(),
  });
};

export const getMineUploadedFiles = async (): Promise<AxiosResponse> => {
  return axiosInstance.get(`/user-documents/mine-with-presigned`, {
    headers: withHeaders(),
  });
};

export const getMyUploadById = async (id: string): Promise<UploadDetails> => {
  return axiosInstance.get(`/user-documents/${id}`, {
    headers: withHeaders(),
  });
};

export const UpdateMyUpload = async (
  id: string,
  body: DocumentPayloadDto,
): Promise<AxiosResponse> => {
  return axiosInstance.put(
    `/user-documents/${id}`,
    { body },
    {
      headers: withHeaders(),
    },
  );
};

export const UpdateMyUploadStatus = async (
  id: string,
  uploadedSuccessfully: boolean,
): Promise<AxiosResponse> => {
  return axiosInstance.patch(
    `/user-documents/${id}/upload-status`,
    { uploadedSuccessfully },
    {
      headers: withHeaders(),
    },
  );
};

export const registerTradeLicense = async (
  body: TradeLicensePayload,
): Promise<AxiosResponse> => {
  let phoneNumber = body.phoneNumber?.trim() || undefined;

  if (!phoneNumber && body.tin?.trim() && body.licenseNo?.trim()) {
    try {
      const resolved = await resolveEtradePhoneForSignup(
        body.licenseNo,
        body.tin,
        "en",
      );
      phoneNumber = resolved ?? undefined;
    } catch (error) {
      console.warn(
        "[eTrade] Failed to resolve phone from GetBusinessByLicenseNo",
        error,
      );
    }
  }

  return registerWithEtrade({
    tin: body.tin,
    licenseNumber: body.licenseNo,
    ...(phoneNumber ? { phoneNumber } : {}),
  });
};

export const signinTradeLicense = async (body: {
  licenseNo: string;
  tin?: string;
}): Promise<AxiosResponse> =>
  registerTradeLicense({
    tin: body.tin ?? "",
    licenseNo: body.licenseNo,
  });

export const signupTradeLicense = async (body: {
  tin: string;
  licenseNo: string;
}): Promise<AxiosResponse> =>
  registerTradeLicense({
    tin: body.tin,
    licenseNo: body.licenseNo,
  });

export const verifyEtradeOtpCode = async (
  body: VerifyEtradeOtpPayload,
): Promise<AxiosResponse> => verifyEtradeOtp(body);

export const setETradePassword = async (
  body: SetETradePasswordPayload,
): Promise<AxiosResponse> => {
  return axiosInstance.patch("/auth/set-etrade-password", body, {
    headers: withHeaders(),
  });
};
