import axios from 'axios';
import { useAuthStore } from '../stores/authStore';

// Change this to your backend URL
// Android emulator: http://10.0.2.2:8000
// iOS simulator: http://localhost:8000
// Physical device: http://<your-machine-ip>:8000
export const API_BASE_URL = "https://contexta-production-672d.up.railway.app"; //'http://192.168.1.72:8000';

const api = axios.create({
  baseURL: `${API_BASE_URL}/api/v1`,
  timeout: 30000,
  headers: { 'Content-Type': 'application/json' },
});

api.interceptors.request.use(config => {
  const token = useAuthStore.getState().token;
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

api.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      useAuthStore.getState().logout();
    }
    return Promise.reject(error);
  },
);

// ─── Auth ────────────────────────────────────────────────────────────────────

export const authAPI = {
  login: (email: string, password: string) =>
    api.post('/auth/login', { email, password }).then(r => r.data),

  signup: (email: string, password: string, company_name: string) =>
    api.post('/auth/signup', { email, password, company_name }).then(r => r.data),

  me: () => api.get('/auth/me').then(r => r.data),

  logout: () => api.post('/auth/logout').then(r => r.data),

  forgotPassword: (email: string) =>
    api.post('/auth/forgot-password', { email }).then(r => r.data),

  resetPassword: (access_token: string, new_password: string) =>
    api.post('/auth/reset-password', { access_token, new_password }).then(r => r.data),

  updateProfile: (data: { company_name?: string; current_password?: string; new_password?: string }) =>
    api.patch('/auth/profile', data).then(r => r.data),

  deleteAccount: () => api.delete('/auth/account').then(r => r.data),
};

// ─── Chatbots ────────────────────────────────────────────────────────────────

export const chatbotsAPI = {
  list: () => api.get('/chatbots').then(r => r.data),

  get: (id: string) => api.get(`/chatbots/${id}`).then(r => r.data),

  create: (data: Partial<import('../types').Chatbot>) =>
    api.post('/chatbots', data).then(r => r.data),

  update: (id: string, data: Partial<import('../types').Chatbot>) =>
    api.put(`/chatbots/${id}`, data).then(r => r.data),

  delete: (id: string) => api.delete(`/chatbots/${id}`).then(r => r.data),

  publish: (id: string) => api.post(`/chatbots/${id}/publish`).then(r => r.data),

  unpublish: (id: string) => api.post(`/chatbots/${id}/unpublish`).then(r => r.data),

  getPublic: (id: string) => api.get(`/chatbots/${id}/public`).then(r => r.data),

  getEmbed: (id: string) => api.get(`/chatbots/${id}/embed`).then(r => r.data),
};

// ─── Documents ───────────────────────────────────────────────────────────────

export const documentsAPI = {
  list: (chatbotId: string) =>
    api.get(`/chatbots/${chatbotId}/documents`).then(r => r.data),

  upload: (chatbotId: string, formData: FormData) =>
    api.post(`/chatbots/${chatbotId}/documents`, formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }).then(r => r.data),

  delete: (chatbotId: string, docId: string) =>
    api.delete(`/chatbots/${chatbotId}/documents/${docId}`).then(r => r.data),

  retry: (chatbotId: string, docId: string) =>
    api.post(`/chatbots/${chatbotId}/documents/${docId}/retry`).then(r => r.data),
};

// ─── URL Sources ──────────────────────────────────────────────────────────────

export const urlSourcesAPI = {
  list: (chatbotId: string) =>
    api.get(`/chatbots/${chatbotId}/url-sources`).then(r => r.data),

  add: (chatbotId: string, url: string) =>
    api.post(`/chatbots/${chatbotId}/url-sources`, { url }).then(r => r.data),

  delete: (chatbotId: string, sourceId: string) =>
    api.delete(`/chatbots/${chatbotId}/url-sources/${sourceId}`).then(r => r.data),

  refresh: (chatbotId: string, sourceId: string) =>
    api.post(`/chatbots/${chatbotId}/url-sources/${sourceId}/refresh`).then(r => r.data),
};

// ─── Chat ─────────────────────────────────────────────────────────────────────

export const chatAPI = {
  sendMessage: (chatbotId: string, message: string, session_id?: string) =>
    api.post(`/chat/${chatbotId}`, { message, session_id }).then(r => r.data),

  getHistory: (chatbotId: string, sessionId: string) =>
    api.get(`/chat/${chatbotId}/history/${sessionId}`).then(r => r.data),

  sendFeedback: (chatbotId: string, message_id: string, feedback: 'positive' | 'negative') =>
    api.post(`/chat/${chatbotId}/feedback`, { message_id, feedback }).then(r => r.data),

  test: (chatbotId: string, questions: string[]) =>
    api.post(`/chat/${chatbotId}/test`, { questions }).then(r => r.data),
};

// ─── Marketplace ─────────────────────────────────────────────────────────────

export const marketplaceAPI = {
  list: (params?: { search?: string; category?: string; industry?: string; page?: number; limit?: number }) =>
    api.get('/marketplace/chatbots', { params }).then(r => r.data),

  get: (id: string) => api.get(`/marketplace/chatbots/${id}`).then(r => r.data),

  categories: () => api.get('/marketplace/categories').then(r => r.data),

  rate: (id: string, rating: number, comment?: string) =>
    api.post(`/marketplace/chatbots/${id}/rate`, { rating, comment }).then(r => r.data),
};

// ─── Analytics ───────────────────────────────────────────────────────────────

export const analyticsAPI = {
  overview: () => api.get('/analytics/overview').then(r => r.data),

  chatbot: (id: string) => api.get(`/analytics/chatbot/${id}`).then(r => r.data),

  gaps: (id: string) => api.get(`/analytics/chatbot/${id}/gaps`).then(r => r.data),
};

// ─── Leads ───────────────────────────────────────────────────────────────────

export const leadsAPI = {
  list: (params?: { chatbot_id?: string; page?: number; limit?: number }) =>
    api.get('/leads', { params }).then(r => r.data),

  update: (id: string, data: Record<string, any>) =>
    api.patch(`/leads/${id}`, data).then(r => r.data),

  submit: (chatbotId: string, data: Record<string, any>) =>
    api.post(`/chatbots/${chatbotId}/leads`, data).then(r => r.data),
};

// ─── Inbox ───────────────────────────────────────────────────────────────────

export const inboxAPI = {
  listConversations: (params?: { chatbot_id?: string; page?: number; limit?: number }) =>
    api.get('/inbox/conversations', { params }).then(r => r.data),

  getConversation: (id: string) =>
    api.get(`/inbox/conversations/${id}`).then(r => r.data),

  updateStatus: (id: string, status: string) =>
    api.patch(`/inbox/conversations/${id}`, { status }).then(r => r.data),

  reply: (id: string, message: string) =>
    api.post(`/inbox/conversations/${id}/reply`, { message }).then(r => r.data),

  deleteConversation: (id: string) =>
    api.delete(`/inbox/conversations/${id}`).then(r => r.data),
};

// ─── Billing ─────────────────────────────────────────────────────────────────

export const billingAPI = {
  subscription: () => api.get('/billing/subscription').then(r => r.data),

  portal: (return_url?: string) =>
    api.post('/billing/portal', { return_url }).then(r => r.data),

  checkout: (plan: string, success_url: string, cancel_url: string) =>
    api.post('/billing/checkout', { plan, success_url, cancel_url }).then(r => r.data),
};

// ─── Models ──────────────────────────────────────────────────────────────────

export const modelsAPI = {
  available: () => api.get('/models/available').then(r => r.data),
};

// ─── Channels ────────────────────────────────────────────────────────────────

export const channelsAPI = {
  list: (chatbotId: string) =>
    api.get('/channels', { params: { chatbot_id: chatbotId } }).then(r => r.data),

  connectTelegram: (chatbot_id: string, bot_token: string) =>
    api.post('/channels/telegram', { chatbot_id, bot_token }).then(r => r.data),

  connectWhatsApp: (chatbot_id: string, wa_keyword?: string) =>
    api.post('/channels/whatsapp', { chatbot_id, wa_keyword }).then(r => r.data),

  disconnect: (connectionId: string) =>
    api.delete(`/channels/${connectionId}`).then(r => r.data),
};

// ─── Campaigns ───────────────────────────────────────────────────────────────

export const campaignsAPI = {
  list: (params?: { chatbot_id?: string; page?: number }) =>
    api.get('/campaigns', { params }).then(r => r.data),

  create: (data: { chatbot_id: string; title: string; message: string }) =>
    api.post('/campaigns', data).then(r => r.data),

  send: (id: string) =>
    api.post(`/campaigns/${id}/send`).then(r => r.data),

  delete: (id: string) =>
    api.delete(`/campaigns/${id}`).then(r => r.data),
};

// ─── Appointments ─────────────────────────────────────────────────────────────

export const appointmentsAPI = {
  list: (params?: { chatbot_id?: string; status?: string; page?: number }) =>
    api.get('/appointments', { params }).then(r => r.data),

  updateStatus: (id: string, status: string) =>
    api.patch(`/appointments/${id}`, { status }).then(r => r.data),

  getHours: (chatbotId: string) =>
    api.get(`/appointments/chatbot/${chatbotId}/hours`).then(r => r.data),

  saveHours: (chatbotId: string, hours: import('../types').BusinessHoursEntry[]) =>
    api.put(`/appointments/chatbot/${chatbotId}/hours`, { hours }).then(r => r.data),
};

// ─── Upload ──────────────────────────────────────────────────────────────────

export const uploadAPI = {
  logo: (formData: FormData) =>
    api.post('/upload/logo', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }).then(r => r.data),
};

export default api;
