import { apiClient } from './client';
import type {
  CasesFilterOptions,
  AssignableTaskStaff,
  LabCaseAttachmentMeta,
  LabCaseDetail,
  ListLabCasesParams,
  PaginatedLabCases,
} from '@/types/cases';
import type { LinkedOrganizationOption } from '@/types/treatment';

export interface LabInternalCaseLinePayload {
  clientId: string;
  id?: string;
  teeth: string[];
  toothSelectionGroups?: Array<{ groupId: string; kind: string; teeth: string[] }>;
  comment?: string;
  toothProsthesis?: Array<{
    tooth: string;
    prosthesisTypeCode: string;
    selectionGroupId?: string;
  }>;
  attachmentIds?: string[];
}

export interface LabInternalCasePayload {
  referringClinicName?: string | null;
  referringDentistName?: string | null;
  patientDisplayName?: string | null;
  patientDisplayMobile?: string | null;
  partnerClinicOrganizationId?: string | null;
  dueDate?: string | null;
  lines?: LabInternalCaseLinePayload[];
}

export const casesApi = {
  list: async (
    params: ListLabCasesParams = {},
  ): Promise<{ success: boolean; data: PaginatedLabCases }> => {
    const response = await apiClient.get('/cases', { params });
    return response.data;
  },

  create: async (
    payload: LabInternalCasePayload = {},
  ): Promise<{ success: boolean; data: LabCaseDetail }> => {
    const response = await apiClient.post('/cases', payload);
    return response.data;
  },

  update: async (
    id: string,
    payload: LabInternalCasePayload,
  ): Promise<{ success: boolean; data: LabCaseDetail }> => {
    const response = await apiClient.put(`/cases/${id}`, payload);
    return response.data;
  },

  start: async (id: string): Promise<{ success: boolean; data: LabCaseDetail }> => {
    const response = await apiClient.post(`/cases/${id}/start`);
    return response.data;
  },

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

  uploadLineAttachments: async (
    caseId: string,
    lineClientId: string,
    files: File[],
  ): Promise<{ success: boolean; data: LabCaseAttachmentMeta[] }> => {
    const form = new FormData();
    for (const file of files) {
      form.append('files', file);
    }
    const response = await apiClient.post(
      `/cases/${caseId}/lines/${encodeURIComponent(lineClientId)}/attachments`,
      form,
      { headers: { 'Content-Type': 'multipart/form-data' }, timeout: 120_000 },
    );
    return response.data;
  },

  listLinkedClinics: async (): Promise<{ success: boolean; data: LinkedOrganizationOption[] }> => {
    const response = await apiClient.get('/cases/linked-clinics');
    return response.data;
  },

  getOne: async (id: string): Promise<{ success: boolean; data: LabCaseDetail }> => {
    const response = await apiClient.get(`/cases/${id}`);
    return response.data;
  },

  listFilterOptions: async (): Promise<{ success: boolean; data: CasesFilterOptions }> => {
    const response = await apiClient.get('/cases/filter-options');
    return response.data;
  },

  listAssignableStaff: async (): Promise<{ success: boolean; data: AssignableTaskStaff[] }> => {
    const response = await apiClient.get('/cases/assignable-staff');
    return response.data;
  },

  assignTask: async (
    caseId: string,
    taskId: string,
    assigneeUserId: string | null,
  ): Promise<{ success: boolean; data: LabCaseDetail }> => {
    const response = await apiClient.patch(`/cases/${caseId}/tasks/${taskId}/assign`, {
      assigneeUserId,
    });
    return response.data;
  },

  setCaseImportant: async (
    caseId: string,
    isImportant: boolean,
  ): Promise<{ success: boolean; data: LabCaseDetail }> => {
    const response = await apiClient.patch(`/cases/${caseId}/important`, { isImportant });
    return response.data;
  },

  setCaseExternalCode: async (
    caseId: string,
    externalCode: string | null,
  ): Promise<{ success: boolean; data: LabCaseDetail }> => {
    const response = await apiClient.patch(`/cases/${caseId}/external-code`, { externalCode });
    return response.data;
  },

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