import axios, { AxiosError } from 'axios';
import type { Project, Template } from '../store/useStore';

const apiClient = axios.create({
  baseURL: 'http://192.168.3.11:8000',
  headers: {
    'Content-Type': 'application/json',
  },
  timeout: 30000,
});

// Request interceptor: attach token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Response interceptor: handle errors
apiClient.interceptors.response.use(
  (response) => response,
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      window.location.reload();
    }
    return Promise.reject(error);
  }
);

// Auth
export async function login(username: string, password: string): Promise<{ token: string }> {
  const response = await apiClient.post('/api/auth/login', { username, password });
  return response.data;
}

// Projects
export async function getProjects(): Promise<Project[]> {
  const response = await apiClient.get('/api/projects');
  return response.data;
}

export async function createProject(payload: {
  name: string;
  description?: string;
}): Promise<Project> {
  const response = await apiClient.post('/api/projects', payload);
  return response.data;
}

export async function updateProject(id: string, payload: Partial<Project>): Promise<Project> {
  const response = await apiClient.put(`/api/projects/${id}`, payload);
  return response.data;
}

export async function deleteProject(id: string): Promise<void> {
  await apiClient.delete(`/api/projects/${id}`);
}

// Templates
export async function getTemplates(): Promise<Template[]> {
  const response = await apiClient.get('/api/templates');
  return response.data;
}

export async function createTemplate(payload: {
  name: string;
  description?: string;
  classes?: { name: string; color: string; zIndex: number; category?: string }[];
}): Promise<Template> {
  const response = await apiClient.post('/api/templates', payload);
  return response.data;
}

export async function updateTemplate(id: string, payload: Partial<Template>): Promise<Template> {
  const response = await apiClient.put(`/api/templates/${id}`, payload);
  return response.data;
}

export async function deleteTemplate(id: string): Promise<void> {
  await apiClient.delete(`/api/templates/${id}`);
}

// Media
export async function uploadMedia(file: File, projectId?: string): Promise<{ url: string; id: string }> {
  const formData = new FormData();
  formData.append('file', file);
  if (projectId) {
    formData.append('project_id', projectId);
  }
  const response = await apiClient.post('/api/media/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
  const { file_url, object_name } = response.data;
  return { url: file_url, id: object_name };
}

// AI Prediction
export async function predictMask(payload: {
  imageUrl: string;
  points?: { x: number; y: number; type: 'pos' | 'neg' }[];
  box?: { x1: number; y1: number; x2: number; y2: number };
  text?: string;
  modelSize?: string;
}): Promise<{
  masks: Array<{
    id: string;
    pathData: string;
    label: string;
    color: string;
    segmentation: number[][];
    bbox: [number, number, number, number];
    area: number;
    confidence: number;
  }>;
}> {
  const response = await apiClient.post('/api/ai/predict', payload);
  return response.data;
}

// Export
export async function exportCoco(projectId: string): Promise<Blob> {
  const response = await apiClient.get(`/api/export/coco/${projectId}`, {
    responseType: 'blob',
  });
  return response.data;
}

export default apiClient;
