import { apiClient } from './client';
import type { LabCaseComment } from '@/types/cases';
import type {
  LabCaseResponse,
  LinkedOrganizationOption,
  PastTreatment,
  SaveLabCasePayload,
  SavedTreatmentDetailPayload,
} from '@/types/treatment';

export const treatmentsApi = {
  listLinkedOrganizations: async (): Promise<{ success: boolean; data: LinkedOrganizationOption[] }> => {
    const response = await apiClient.get('/treatments/linked-organizations');
    return response.data;
  },

  listPatientHistory: async (
    patientId: string,
    limit = 20,
  ): Promise<{ success: boolean; data: PastTreatment[] }> => {
    const response = await apiClient.get(`/treatments/patients/${patientId}/history`, {
      params: { limit },
    });
    return response.data;
  },

  listPatientLabCases: async (
    patientId: string,
  ): Promise<{ success: boolean; data: import('@/types/lab-case-activity').PatientLabCaseSummary[] }> => {
    const response = await apiClient.get(`/treatments/patients/${patientId}/lab-cases`);
    return response.data;
  },

  listUnreadLabCases: async (): Promise<{
    success: boolean;
    data: import('@/types/lab-case-activity').PatientLabCaseSummary[];
  }> => {
    const response = await apiClient.get('/treatments/lab-cases/unread');
    return response.data;
  },

  getDraft: async (
    appointmentId: string,
  ): Promise<{ success: boolean; data: PastTreatment | null }> => {
    const response = await apiClient.get(`/treatments/appointments/${appointmentId}/draft`);
    return response.data;
  },

  createStandalone: async (payload: {
    patientId?: string;
    walkIn?: boolean;
    treatmentAt: string;
  }): Promise<{ success: boolean; data: PastTreatment }> => {
    const response = await apiClient.post('/treatments', payload);
    return response.data;
  },

  deleteStandalone: async (treatmentId: string): Promise<{ success: boolean }> => {
    const response = await apiClient.delete(`/treatments/${treatmentId}`);
    return response.data;
  },

  listDayStandalone: async (params: {
    from: string;
    to: string;
  }): Promise<{ success: boolean; data: PastTreatment[] }> => {
    const response = await apiClient.get('/treatments/day', { params });
    return response.data;
  },

  getDraftByTreatment: async (
    treatmentId: string,
  ): Promise<{ success: boolean; data: PastTreatment | null }> => {
    const response = await apiClient.get(`/treatments/${treatmentId}/draft`);
    return response.data;
  },

  saveDraftByTreatment: async (
    treatmentId: string,
    payload: { details: SavedTreatmentDetailPayload[] },
  ): Promise<{ success: boolean; data: PastTreatment }> => {
    const response = await apiClient.put(`/treatments/${treatmentId}/draft`, payload);
    return response.data;
  },

  saveLabCasesByTreatment: async (
    treatmentId: string,
    payload: { labCases: SaveLabCasePayload[] },
  ): Promise<{ success: boolean; data: PastTreatment }> => {
    const response = await apiClient.put(`/treatments/${treatmentId}/lab-cases`, payload);
    return response.data;
  },

  uploadDetailAttachmentsByTreatment: async (
    treatmentId: string,
    detailClientId: string,
    files: File[],
    onUploadProgress?: (percent: number) => void,
  ): Promise<{ success: boolean; data: import('@/types/treatment').TreatmentAttachmentMeta[] }> => {
    const form = new FormData();
    for (const file of files) {
      form.append('files', file);
    }
    const response = await apiClient.post(
      `/treatments/${treatmentId}/details/${encodeURIComponent(detailClientId)}/attachments`,
      form,
      {
        headers: { 'Content-Type': 'multipart/form-data' },
        timeout: 120_000,
        onUploadProgress: onUploadProgress
          ? (event) => {
              if (!event.total) return;
              onUploadProgress(Math.round((event.loaded / event.total) * 100));
            }
          : undefined,
      },
    );
    return response.data;
  },

  saveDraft: async (
    appointmentId: string,
    payload: { details: SavedTreatmentDetailPayload[] },
  ): Promise<{ success: boolean; data: PastTreatment }> => {
    const response = await apiClient.put(`/treatments/appointments/${appointmentId}/draft`, payload);
    return response.data;
  },

  saveLabCases: async (
    appointmentId: string,
    payload: { labCases: SaveLabCasePayload[] },
  ): Promise<{ success: boolean; data: PastTreatment }> => {
    const response = await apiClient.put(
      `/treatments/appointments/${appointmentId}/lab-cases`,
      payload,
    );
    return response.data;
  },

  uploadDetailAttachments: async (
    appointmentId: string,
    detailClientId: string,
    files: File[],
    onUploadProgress?: (percent: number) => void,
  ): Promise<{ success: boolean; data: import('@/types/treatment').TreatmentAttachmentMeta[] }> => {
    const form = new FormData();
    for (const file of files) {
      form.append('files', file);
    }
    const response = await apiClient.post(
      `/treatments/appointments/${appointmentId}/details/${encodeURIComponent(detailClientId)}/attachments`,
      form,
      {
        headers: { 'Content-Type': 'multipart/form-data' },
        timeout: 120_000,
        onUploadProgress: onUploadProgress
          ? (event) => {
              if (!event.total) return;
              onUploadProgress(Math.round((event.loaded / event.total) * 100));
            }
          : undefined,
      },
    );
    return response.data;
  },

  /** @deprecated Use uploadDetailAttachments */
  uploadCaseAttachments: async (
    appointmentId: string,
    detailClientId: string,
    files: File[],
  ) => {
    return treatmentsApi.uploadDetailAttachments(appointmentId, detailClientId, files);
  },

  sendLabCase: async (
    labCaseId: string,
  ): Promise<{ success: boolean; data: LabCaseResponse }> => {
    const response = await apiClient.post(`/treatments/lab-cases/${labCaseId}/send`);
    return response.data;
  },

  updateLabCaseDueDate: async (
    labCaseId: string,
    dueDate: string | null,
  ): Promise<{ success: boolean; data: LabCaseResponse }> => {
    const response = await apiClient.patch(`/treatments/lab-cases/${labCaseId}/due-date`, {
      dueDate,
    });
    return response.data;
  },

  listLabCaseComments: async (
    labCaseId: string,
  ): Promise<{ success: boolean; data: LabCaseComment[] }> => {
    const response = await apiClient.get(`/treatments/lab-cases/${labCaseId}/comments`);
    return response.data;
  },

  addLabCaseComment: async (
    labCaseId: string,
    payload: { body: string },
  ): Promise<{ success: boolean; data: LabCaseComment }> => {
    const response = await apiClient.post(`/treatments/lab-cases/${labCaseId}/comments`, payload);
    return response.data;
  },

  getAttachmentFileBlob: async (attachmentId: string): Promise<Blob> => {
    const response = await apiClient.get(`/treatments/attachments/${attachmentId}/file`, {
      responseType: 'blob',
      timeout: 120_000,
    });
    return response.data;
  },
};
