import axios from 'axios';
import type {
  TBaseResponseAPI,
  TCancelRequest,
  TCancelResponse,
  TCountryResult,
  TDeleteRequest,
  TDetailUangMukaResult,
  TGetListDataTableFakturPKResult,
  TGoodsResult,
  TIdTambahanResult,
  TKeteranganTambahanResult,
  TPostFakturPKRequest,
  TSatuanResult,
  TServiceResult,
} from '../types/types';

import unifikasiClient from './unifikasiClient';
import { normalizePayloadCetakPdfDetail } from './normalizePayloadCetakPdf';

const fakturApi = () => {};

const axiosCetakPdf = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API_URL_CETAK,
  headers: {
    Authorization: `Basic ${window.btoa('admin:ortax123')}`,
    password: '',
  },
});

// API untuk get list table
fakturApi.getFakturPK = async (config: any) => {
  const {
    data: { message, metaPage, data },
    status: statusCode,
  } = await unifikasiClient.get<TBaseResponseAPI<TGetListDataTableFakturPKResult>>('/IF_TXR_001', {
    ...config,
  });

  if (statusCode !== 200) {
    throw new Error(message);
  }

  return { total: metaPage ? Number(metaPage.totalRow) : 0, data };
};

fakturApi.getCountry = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TCountryResult>>(
    '/sandbox/mst_negara',
    { params }
  );

  const body = response.data;

  if (response.status !== 200 || body.status !== 'success') {
    throw new Error(body.message);
  }

  return body;
};

fakturApi.getGoods = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TGoodsResult>>('/sandbox/mst_goods', {
    params,
  });

  const body = response.data;

  if (response.status !== 200 || body.status !== 'success') {
    throw new Error(body.message);
  }

  return body;
};

fakturApi.getServices = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TServiceResult>>(
    '/sandbox/mst_services',
    {
      params,
    }
  );

  const body = response.data;

  if (response.status !== 200 || body.status !== 'success') {
    throw new Error(body.message);
  }

  return body;
};

fakturApi.getSatuan = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TSatuanResult>>(
    '/sandbox/mst_satuan',
    {
      params,
    }
  );

  const body = response.data;

  if (response.status !== 200 || body.status !== 'success') {
    throw new Error(body.message);
  }

  return body;
};

fakturApi.getIdTambahan = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TIdTambahanResult>>(
    '/sandbox/mst_faktur_idtambahan',
    {
      params,
    }
  );

  const body = response.data;

  if (response.status !== 200 || body.status !== 'success') {
    throw new Error(body.message);
  }

  return body;
};

fakturApi.getKeteranganTambahan = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TKeteranganTambahanResult>>(
    '/sandbox/mst_faktur_keterangan',
    {
      params,
    }
  );

  const body = response.data;

  if (response.status !== 200 || body.status !== 'success') {
    throw new Error(body.message);
  }

  return body;
};

fakturApi.saveFakturPK = async (config: TPostFakturPKRequest) => {
  const {
    data: { message, data, code },
  } = await unifikasiClient.post<TBaseResponseAPI<TPostFakturPKRequest>>('/IF_TXR_001/create', {
    ...config,
  });
  if (code === 0) {
    throw new Error(message);
  }

  return data;
};

fakturApi.getFakturPKById = async (id: string) => {
  const res = await unifikasiClient.get('/IF_TXR_001', { params: { id } });

  const {
    data: { status, message, data },
    status: statusCode,
  } = res;

  if (statusCode !== 200 || status?.toLowerCase() !== 'success') {
    console.error('getFakturPK failed:', { statusCode, status, message });
    throw new Error(message || 'Gagal mengambil data FakturPK');
  }

  const dnData = Array.isArray(data) ? data[0] : data;

  return dnData;
};

fakturApi.getDetailUangMuka = async (nomorFaktur: string) => {
  const res = await unifikasiClient.get<TBaseResponseAPI<TDetailUangMukaResult>>(
    '/IF_TXR_001/uangmuka',
    { params: { nomorFaktur } }
  );

  const {
    data: { status, message, data },
    status: statusCode,
  } = res;

  if (statusCode !== 200 || status?.toLowerCase() !== 'success') {
    console.error('getFakturPK failed:', { statusCode, status, message });
    throw new Error(message || 'Gagal mengambil data FakturPK');
  }

  const dnData = Array.isArray(data) ? data[0] : data;

  return dnData;
};

fakturApi.upload = async ({ id }: { id: string | number }) => {
  const {
    data: { status, message, data, code },
    status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_001/upload', { id });

  return { status, message, data, code, statusCode };
};

fakturApi.deleteFakturPK = async (
  payload: TDeleteRequest,
  config?: Record<string, any>
): Promise<any> => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post<TBaseResponseAPI<any>>('/IF_TXR_001/delete', payload, {
    ...config,
  });

  if (statusCode !== 200 || status?.toLowerCase() === 'error') {
    throw new Error(message || 'Gagal menghapus data Faktur PK');
  }

  return data;
};

fakturApi.cetakPdfDetail = async (payload: { id: string }) => {
  // 1️⃣ Ambil data faktur dari Unifikasi
  const fakturRaw = await fakturApi.getFakturPKById(payload.id);

  console.log();

  // 2️⃣ Normalize agar sesuai format yang dibutuhkan API cetak PDF
  const payloadCetak = normalizePayloadCetakPdfDetail(fakturRaw);

  // 3️⃣ Call API PDF
  const response = await axiosCetakPdf.post('/report/ctas/faktur/pk', payloadCetak);
  const body = response.data;

  // 4️⃣ Validasi response
  if (
    !response ||
    response.status !== 200 ||
    body.status === 'fail' ||
    body.status === 'error' ||
    body.status === '0'
  ) {
    throw new Error(
      body.message || 'System tidak dapat memenuhi permintaan, coba beberapa saat lagi'
    );
  }

  return body;
};

fakturApi.cancel = async ({ id, revokeFlag }: TCancelRequest): Promise<TCancelResponse> => {
  const {
    data: { status, message, data, code, time, metaPage, total },
  } = await unifikasiClient.post('/IF_TXR_006', {
    id,
    revokeFlag,
  });

  console.log('Cancel Digunggung response:', { code, message, status });
  if (code === 0) {
    throw new Error(message || 'Gagal membatalkan data');
  }

  return {
    status,
    message,
    data,
    code,
    time,
    metaPage,
    total,
  };
};

export default fakturApi;
