import axios from 'axios';
import type {
  LoginRequest,
  LoginResponse,
  User,
  MatchResult,
  DashboardKPI,
  ParsedFile,
  ReviewAction,
  DitRecord,
  SampleRecord,
  OrderRecord,
  LabKPI,
  ScatterPoint,
  OrphanSample,
  ConversionRecord,
  NoDitSample,
  HighQtyNoOrderSample
} from '../types';

const api = axios.create({
  baseURL: '/api',
  timeout: 900000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 請求攔截器：加入 JWT Token
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// 響應攔截器：處理 401 錯誤
api.interceptors.response.use(
  (response) => response,
  (error) => {
    // 只有在非登入/驗證相關的 API 返回 401 時才跳轉
    const isAuthEndpoint = error.config?.url?.includes('/auth/');
    if (error.response?.status === 401 && !isAuthEndpoint) {
      localStorage.removeItem('token');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// Auth API
export const authApi = {
  login: async (data: LoginRequest): Promise<LoginResponse> => {
    const formData = new URLSearchParams();
    formData.append('username', data.email);
    formData.append('password', data.password);

    const response = await api.post<LoginResponse>('/auth/login', formData, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    });
    return response.data;
  },

  register: async (data: LoginRequest): Promise<User> => {
    const response = await api.post<User>('/auth/register', data);
    return response.data;
  },

  me: async (): Promise<User> => {
    const response = await api.get<User>('/auth/me');
    return response.data;
  },
};

// ETL API
export const etlApi = {
  upload: async (file: File, fileType: 'dit' | 'sample' | 'order'): Promise<ParsedFile> => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('file_type', fileType);
    const response = await api.post<ParsedFile>('/etl/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    return response.data;
  },

  preview: async (fileId: string): Promise<ParsedFile> => {
    const response = await api.get<ParsedFile>(`/etl/preview/${fileId}`);
    return response.data;
  },

  import: async (fileId: string): Promise<{ imported_count: number }> => {
    const response = await api.post<{ imported_count: number }>('/etl/import', { file_id: fileId });
    return response.data;
  },

  getData: async (type: 'dit' | 'sample' | 'order'): Promise<(DitRecord | SampleRecord | OrderRecord)[]> => {
    const response = await api.get(`/etl/data/${type}`);
    return response.data;
  },

  clearData: async (): Promise<void> => {
    await api.delete('/etl/data');
  },
};

// Match API
export const matchApi = {
  run: async (): Promise<{ match_count: number; auto_matched: number; pending_review: number }> => {
    const response = await api.post('/match/run');
    return response.data;
  },

  getResults: async (): Promise<MatchResult[]> => {
    const response = await api.get<MatchResult[]>('/match/results');
    return response.data;
  },

  review: async (id: number, action: ReviewAction): Promise<MatchResult> => {
    const response = await api.put<MatchResult>(`/match/${id}/review`, { action });
    return response.data;
  },
};

// Dashboard API
export const dashboardApi = {
  getKPI: async (): Promise<DashboardKPI> => {
    const response = await api.get<DashboardKPI>('/dashboard/kpi');
    return response.data;
  },

  getFunnel: async () => {
    const response = await api.get('/dashboard/funnel');
    return response.data;
  },

  getAttribution: async () => {
    const response = await api.get('/dashboard/attribution');
    return response.data;
  },
};

// Report API
export const reportApi = {
  exportExcel: async (): Promise<Blob> => {
    const response = await api.get('/report/export', {
      params: { format: 'xlsx' },
      responseType: 'blob',
    });
    return response.data;
  },

  exportPdf: async (): Promise<Blob> => {
    const response = await api.get('/report/export', {
      params: { format: 'pdf' },
      responseType: 'blob',
    });
    return response.data;
  },
};

// Lab API
export const labApi = {
  getKPI: async (params?: { start_date?: string; end_date?: string }): Promise<LabKPI> => {
    const response = await api.get<LabKPI>('/lab/kpi', { params });
    return response.data;
  },

  getScatter: async (params?: { start_date?: string; end_date?: string }): Promise<ScatterPoint[]> => {
    const response = await api.get<ScatterPoint[]>('/lab/scatter', { params });
    return response.data;
  },

  getOrphans: async (params?: { start_date?: string; end_date?: string }): Promise<OrphanSample[]> => {
    const response = await api.get<OrphanSample[]>('/lab/orphans', { params });
    return response.data;
  },

  getConversions: async (params?: { start_date?: string; end_date?: string }): Promise<ConversionRecord[]> => {
    const response = await api.get<ConversionRecord[]>('/lab/conversions', { params });
    return response.data;
  },

  getNoDitSamples: async (params?: { start_date?: string; end_date?: string }): Promise<NoDitSample[]> => {
    const response = await api.get<NoDitSample[]>('/lab/no_dit_samples', { params });
    return response.data;
  },

  getHighQtyNoOrderSamples: async (params?: { start_date?: string; end_date?: string }): Promise<HighQtyNoOrderSample[]> => {
    const response = await api.get<HighQtyNoOrderSample[]>('/lab/high_qty_no_order_samples', { params });
    return response.data;
  },
};

export default api;
