import axios from 'axios';

const API_BASE_URL = 'http://localhost:8080/api/v1';

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

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

// Response interceptor to handle errors
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// Types
export interface User {
  id: number;
  email: string;
  first_name: string;
  last_name: string;
  avatar?: string;
  role: string;
  created_at: string;
  updated_at: string;
}

export interface Project {
  id: number;
  name: string;
  description: string;
  status: string;
  color: string;
  start_date?: string;
  end_date?: string;
  owner_id: number;
  owner: User;
  members: User[];
  tasks?: Task[];
  created_at: string;
  updated_at: string;
}

export interface Task {
  id: number;
  title: string;
  description: string;
  status: 'todo' | 'in_progress' | 'review' | 'done';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  due_date?: string;
  completed_at?: string;
  position: number;
  project_id: number;
  assigned_to_id?: number;
  created_by_id: number;
  assigned_to?: User;
  created_by: User;
  comments: Comment[];
  files: FileUpload[];
  subtasks: Subtask[];
  labels: Label[];
  created_at: string;
  updated_at: string;
}

export interface Subtask {
  id: number;
  title: string;
  description: string;
  status: 'todo' | 'in_progress' | 'done';
  position: number;
  completed_at?: string;
  parent_task_id: number;
  assigned_to_id?: number;
  assigned_to?: User;
  created_at: string;
  updated_at: string;
}

export interface Label {
  id: number;
  name: string;
  color: string;
  project_id: number;
  created_at: string;
  updated_at: string;
}

export interface Comment {
  id: number;
  content: string;
  task_id: number;
  user_id: number;
  user: User;
  created_at: string;
  updated_at: string;
}

export interface FileUpload {
  id: number;
  file_name: string;
  original_name: string;
  file_path: string;
  file_size: number;
  mime_type: string;
  description?: string;
  uploaded_by_id: number;
  project_id?: number;
  task_id?: number;
  uploaded_by: User;
  project?: Project;
  task?: Task;
  created_at: string;
  updated_at: string;
}

export interface AuthResponse {
  token: string;
  user: User;
}

export interface APIResponse<T = any> {
  success: boolean;
  message: string;
  data?: T;
  error?: string;
}

// Auth API
export const authAPI = {
  login: (email: string, password: string): Promise<APIResponse<AuthResponse>> =>
    api.post('/auth/login', { email, password }).then(res => res.data),
  
  register: (data: {
    email: string;
    password: string;
    first_name: string;
    last_name: string;
  }): Promise<APIResponse<AuthResponse>> =>
    api.post('/auth/register', data).then(res => res.data),
  
  getProfile: (): Promise<APIResponse<User>> =>
    api.get('/auth/profile').then(res => res.data),
  
  updateProfile: (data: {
    first_name?: string;
    last_name?: string;
    avatar?: string;
  }): Promise<APIResponse<User>> =>
    api.put('/auth/profile', data).then(res => res.data),
  
  changePassword: (data: {
    current_password: string;
    new_password: string;
  }): Promise<APIResponse> =>
    api.put('/auth/change-password', data).then(res => res.data),
};

// Projects API
export const projectsAPI = {
  getProjects: (): Promise<APIResponse<Project[]>> =>
    api.get('/projects').then(res => res.data),
  
  getProject: (id: number): Promise<APIResponse<Project>> =>
    api.get(`/projects/${id}`).then(res => res.data),
  
  createProject: (data: {
    name: string;
    description?: string;
    color?: string;
  }): Promise<APIResponse<Project>> =>
    api.post('/projects', data).then(res => res.data),
  
  updateProject: (id: number, data: {
    name?: string;
    description?: string;
    status?: string;
    color?: string;
  }): Promise<APIResponse<Project>> =>
    api.put(`/projects/${id}`, data).then(res => res.data),
  
  deleteProject: (id: number): Promise<APIResponse> =>
    api.delete(`/projects/${id}`).then(res => res.data),
  
  addMember: (id: number, data: {
    user_id: number;
    role?: string;
  }): Promise<APIResponse<Project>> =>
    api.post(`/projects/${id}/members`, data).then(res => res.data),
  
  removeMember: (projectId: number, userId: number): Promise<APIResponse<Project>> =>
    api.delete(`/projects/${projectId}/members/${userId}`).then(res => res.data),
};

// Tasks API
export const tasksAPI = {
  getTasks: (projectId: number): Promise<APIResponse<Task[]>> =>
    api.get(`/projects/${projectId}/tasks`).then(res => res.data),
  
  getTask: (projectId: number, taskId: number): Promise<APIResponse<Task>> =>
    api.get(`/projects/${projectId}/tasks/${taskId}`).then(res => res.data),
  
  createTask: (projectId: number, data: {
    title: string;
    description?: string;
    priority?: string;
    due_date?: string;
    assigned_to_id?: number;
  }): Promise<APIResponse<Task>> =>
    api.post(`/projects/${projectId}/tasks`, data).then(res => res.data),
  
  updateTask: (projectId: number, taskId: number, data: {
    title?: string;
    description?: string;
    status?: string;
    priority?: string;
    due_date?: string;
    assigned_to_id?: number;
    position?: number;
  }): Promise<APIResponse<Task>> =>
    api.put(`/projects/${projectId}/tasks/${taskId}`, data).then(res => res.data),
  
  deleteTask: (projectId: number, taskId: number): Promise<APIResponse> =>
    api.delete(`/projects/${projectId}/tasks/${taskId}`).then(res => res.data),
  
  addComment: (projectId: number, taskId: number, data: {
    content: string;
  }): Promise<APIResponse<Comment>> =>
    api.post(`/projects/${projectId}/tasks/${taskId}/comments`, data).then(res => res.data),
  
  createSubtask: (projectId: number, taskId: number, data: {
    title: string;
    description?: string;
    assigned_to_id?: number;
  }): Promise<APIResponse<Subtask>> =>
    api.post(`/projects/${projectId}/tasks/${taskId}/subtasks`, data).then(res => res.data),
};

// Files API
export const filesAPI = {
  getFiles: (projectId: number): Promise<APIResponse<FileUpload[]>> =>
    api.get(`/projects/${projectId}/files`).then(res => res.data),
  
  getTaskFiles: (projectId: number, taskId: number): Promise<APIResponse<FileUpload[]>> =>
    api.get(`/projects/${projectId}/tasks/${taskId}/files`).then(res => res.data),
  
  uploadFile: (projectId: number, file: File, taskId?: number): Promise<APIResponse<FileUpload>> => {
    const formData = new FormData();
    formData.append('file', file);
    if (taskId) {
      formData.append('task_id', taskId.toString());
    }
    
    return api.post(`/projects/${projectId}/files`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    }).then(res => res.data);
  },
  
  downloadFile: (projectId: number, fileId: number): Promise<Blob> =>
    api.get(`/projects/${projectId}/files/${fileId}`, {
      responseType: 'blob',
    }).then(res => res.data),
  
  deleteFile: (projectId: number, fileId: number): Promise<APIResponse> =>
    api.delete(`/projects/${projectId}/files/${fileId}`).then(res => res.data),
};

export default api;
