// import { payloadSearcher } from 'recharts/types/chart/SunburstChart';
import { dashboardApi } from './client-dashboard';
import { UpdateClientDocumentPayload, UploadClientDocumentPayload } from '@/hooks/use-client-document';
import { GenerateLetterPayload } from '@/app/customer/profile/letters/page';

//month wise data
export const getMonthlyData = async (customerId: string | number, date?: string) => {
  const res = await dashboardApi.get(`/customer/get_month_score/${customerId}`, {
    params: { date }
  });
  return res.data;
};

// current score from bueros
export const getAllScore = async (
  customerId: string | number,
  date?: string
) => {
  try {
    const [tuRes, expRes, efxRes] = await Promise.all([
      dashboardApi.get(`/customer/client_tu_score/${customerId}`, {
        params: { date },
      }),
      dashboardApi.get(`/customer/client_exp_score/${customerId}`, {
        params: { date },
      }),
      dashboardApi.get(`/customer/client_efx_score/${customerId}`, {
        params: { date },
      }),
    ]);

    const tuData = tuRes?.data?.results || {};
    const expData = expRes?.data?.results || {};
    const efxData = efxRes?.data?.results || {};

    // Merge all responses
    return {
      transunion: tuData?.transunion ?? null,
      experian: expData?.experian ?? null,
      equifax: efxData?.equifax ?? null,
    };
  } catch (error: any) {
    console.error('Error fetching scores:', error);

    throw new Error(
      error?.response?.data?.message ||
      'Failed to fetch credit scores'
    );
  }
};
//transunion score(intitial-current)
export const tuScoreIniCurr = async (customerId: string | number) => {
  const res = await dashboardApi.get(`/customer/transunion_score/${customerId}`);
  return res.data;
};
//equifax score(intitial-current)
export const equScoreIniCurr = async (customerId: string | number) => {
  const res = await dashboardApi.get(`/customer/equifax_score/${customerId}`);
  return res.data;
};
//transunion score(intitial-current)
export const expScoreIniCurr = async (customerId: string | number) => {
  const res = await dashboardApi.get(`/customer/experian_score/${customerId}`);
  return res.data;
};
export const reportScore = async (customerId: string | number, type: string) => {
  const res = await dashboardApi.get(`customer/credit_report_score_factor/${customerId}/${type}`);
  return res.data;
}
//transunion item
export const tuItem = async (customerId: string | number) => {
  const res = await dashboardApi.get(`/customer/transunion_item/${customerId}`);
  return res.data;
};
//equifax item
export const equItem = async (customerId: string | number) => {
  const res = await dashboardApi.get(`/customer/equifax_item/${customerId}`);
  return res.data;
};
//transunion item
export const expItem = async (customerId: string | number) => {
  const res = await dashboardApi.get(`/customer/experian_item/${customerId}`);
  return res.data;
};
//collective total account details
export const totalAccount = async (customerId: string | number, date?: string) => {
  const res = await dashboardApi.get(`/customer/total_accounts/${customerId}`, {
    params: { date }
  });
  return res.data.results;
};
//bureau wise account details
export const accountDetails = async (customerId: string | number, type: string, selectedDate: string | null | undefined) => {
  const res = await dashboardApi.get(`/customer/account_details/${customerId}/${type}`, {
    params: { selectedDate }
  });
  return res.data.results;
}
//Dispute Items with Filtering
export const getDisputeItems = async (
  customerId: string | number,
  type: string,
  page: number = 1,
  itemType: number | string = 0,
  childTypeId: number | string = 0,
  search: string = ''

) => {
  let apiURL = ''
  if (itemType !== 0 && childTypeId !== 0) {
    apiURL = `/customer/items_by_client_bureau_item_child/${customerId}/${type}/${itemType}/${childTypeId}`
  } else if (itemType !== 0 && childTypeId === 0) {
    apiURL = `/customer/items_by_client_bureau_item/${customerId}/${type}/${itemType}`
  } else {
    apiURL = `/customer/items_by_client_bureau/${customerId}/${type}`
  }

  const res = await dashboardApi.get(
    apiURL,
    {
      params: { page, search },
    }
  );

  return res.data;
};
//Get All dispute activities
export const getDisputeActivites = async (
  customerId: string | number, itemID: string | number, page: number, search: string = '') => {
  const res = await dashboardApi.get(
    `/customer/client_item_activity/${customerId}/${itemID}`,
    {
      params: { search, page }
    }
  );

  return res.data;
};
//Close Dispute
export const closeDispite = async (
  payload: {
    status_id: string | number | null, client_id: string | number | null
  },
  itemID: string | number
) => {
  const res = await dashboardApi.post(
    `/customer/do_not_dispute_item/${itemID}`, payload
  );
  return res;
}
//Client Alearts
export const getClientAlearts = async (
  customerId: string | number,
  bureau: string,
  page: number = 1
) => {
  const res = await dashboardApi.get(
    `/customer/client_${bureau}_alerts/${customerId}`,
    {
      params: { page }
    }
  );
  return res.data;
}
//Get alearts details
export const getAleartsDetails = async (
  id: number,
  bureau: string
) => {
  const res = await dashboardApi.get(
    `/customer/${bureau}_alert_detail/${id}`
  );
  return res.data;
}

//IDP Alearts
export const getIdpAlearts = async (
  customerId: string | number,
  page: number = 1
) => {
  const res = await dashboardApi.get(
    `/customer/client_idp_alerts/${customerId}`,
    { params: { page } }
  );
  return res.data;
}
//Get alearts details
export const getIdpAleartsDetails = async (
  id: number,
) => {
  const res = await dashboardApi.get(
    `/customer/idp_alert_detail/${id}`
  );
  return res.data;
}
//Get Documents API
export const getClientDocument = async (
  customerId: number | string,
  pageNum: number
) => {
  const res = await dashboardApi.get(
    `/customer/documents/${customerId}`,
    {
      params: { page: pageNum }
    }
  );
  return res.data.results || null;
}
//Delete Documents API
export const deleteClientDocument = async (
  id: number,
) => {
  const res = await dashboardApi.delete(
    `/customer/document/${id}`
  );
  return res.data || null;
}
// upload Documents API
export const uploadClientDoc = async (
  payload: UploadClientDocumentPayload
) => {
  const formData = new FormData();
  formData.append('file', payload.file);
  formData.append('client_id', String(payload.client_id));
  formData.append('type', payload.type);
  formData.append('upload_as', payload.upload_as);
  formData.append('catid', String(payload.catid));
  formData.append('is_active', String(payload.is_active ?? 1));
  formData.append('doc_type', String(payload.doc_type));
  formData.append('description', String(payload.description));
  const res = await dashboardApi.post(
    '/customer/document_upload',
    formData
  );

  return res.data;
};


export const updateClientDoc = async (
  payload: UpdateClientDocumentPayload
) => {
  const formData = new FormData();

  if (payload.file) {
    formData.append('file', payload.file);
  }

  formData.append('client_id', String(payload.client_id));
  formData.append('type', payload.type ?? '');
  formData.append('upload_as', payload.upload_as);
  formData.append('catid', String(payload.catid));
  formData.append('is_active', String(payload.is_active ?? 1));
  formData.append('doc_type', String(payload.doc_type));
  formData.append('description', String(payload.description));
  const res = await dashboardApi.post(
    `/customer/document_update/${payload.documentId}`,
    formData,
  );

  return res.data;
};

//Get Legacy contracts list API
export const getLegacyContracts = async (
) => {
  const res = await dashboardApi.get(
    `/customer/legal_contracts`
  );
  return res || null;
}

//Get Legacy contracts list API
export const getLegacyContractsItems = async (
  id: number,
  customerid: string | number
) => {
  const res = await dashboardApi.get(
    `/customer/legal_contracts/${id}/${customerid}`
  );
  return res || null;
}


//Get letters
export const getCustomerLetters = async (
  customerId: string | number,
  bureau: string,
  page: number = 1,
  search: string = '',
) => {
  const res = await dashboardApi.get(
    `/customer/letters/${bureau}/${customerId}`,
    { params: { page, search } }
  );
  return res || null;
}

//Get letter preview
export const getLetterPreview = async (
  customerId: string | number,
  letterId: number
) => {
  const res = await dashboardApi.get(
    `/customer/letter_preview/${customerId}/${letterId}`
  );
  return res || null;
}

//Get letter preview before letter generation
export const generateLetterPreview = async (
  customerId: string | number,
  payload: {
    items: string[];
  }
) => {
  const res = await dashboardApi.post(
    `/customer/letter_template_preview/${customerId}`, payload
  );
  return res || null;
}

//Get letter of refrence preview 
export const getLetterReferencePreview = async (
  customerId: string | number,
) => {
  const res = await dashboardApi.get(
    `/customer/get_letters_by_refrence/${customerId}`
  );
  return res || null;
}

//Get Negative items for letter generation
export const getNegativeItemsForLetter = async (
  customerId: string | number,
  bureau: string
) => {
  const res = await dashboardApi.get(
    `/customer/negative_items/${customerId}/${bureau}`
  );
  return res || null;
}

//Generate Letter
export const generateLetter = async (
  payload: GenerateLetterPayload
) => {
  const formData = new FormData();
  formData.append('bureau', payload.bureau);
  formData.append(
    'items',
    JSON.stringify(payload.items) // ["30","31"]
  );
  formData.append(
    'include_id_doc',
    payload.include_doc_id ? '1' : '0'
  );

  const res = await dashboardApi.post(
    `/customer/generate_letter/${payload.customerId}`,
    formData
  );

  return res.data;
};

//cancel payment
export const cancelPlan = async (
  customerId: string | number,
) => {
  const res = await dashboardApi.get(
    `/customer/${customerId}/subscription/cancel`
  );
  return res || null;
}

// payment History
export const paymentHistory = async (
  customerId: string | number,
) => {
  const res = await dashboardApi.get(
    `/customer/${customerId}/subscription/history`
  );
  return res || null;
}

// get report date for credit report
export const getReportDate = async (
  customerId: string | number,
  bureau: string
) => {
  const res = await dashboardApi.get(
    `/customer/report_date/${customerId}/${bureau}`
  );
  return res || null;
}