import axios, { type AxiosError, type InternalAxiosRequestConfig } from 'axios';
import type {
  Category,
  Product,
  Order,
  Expense,
  DashboardStats,
  TopProduct,
  PeakHour,
  SalesByCategory,
  SalesByPayment,
  ReceiptData,
  CreateOrderPayload,
  CreateExpensePayload,
  HeldOrder,
  HoldOrderPayload,
  AuthResponse,
  User,
  Customer,
  AvailableDiscount,
  NotificationResponse,
  StoreSettings,
} from '@/types';
import { setStoredUser, clearAuth, setToken, getToken, removeToken } from './auth';

// ============================================================
// Axios Instance - Sanctum SPA (cookie + CSRF)
// ============================================================
/**
 * Prefer same-origin proxy `/backend` (see next.config rewrites) so
 * session + XSRF cookies are first-party. Fall back to absolute API URL.
 */
function resolveApiBase(): string {
  if (typeof window !== 'undefined') {
    // Browser: always use Next proxy when available
    return '/backend/api';
  }
  return process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8000/api';
}

function resolveBackendOrigin(): string {
  if (typeof window !== 'undefined') {
    return `${window.location.origin}/backend`;
  }
  const api = process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8000/api';
  return api.replace(/\/api\/?$/, '');
}

const api = axios.create({
  baseURL: resolveApiBase(),
  headers: {
    'Content-Type': 'application/json',
    Accept: 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
  },
  timeout: 30000,
  withCredentials: true,
});

function readCookie(name: string): string | null {
  if (typeof document === 'undefined') return null;
  const match = document.cookie.match(
    new RegExp('(?:^|; )' + name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1') + '=([^;]*)')
  );
  return match ? decodeURIComponent(match[1]) : null;
}

/** Ensure XSRF-TOKEN cookie exists (Sanctum CSRF handshake). */
export async function ensureCsrfCookie(): Promise<void> {
  await axios.get(`${resolveBackendOrigin()}/sanctum/csrf-cookie`, {
    withCredentials: true,
    headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
  });
}

// Request: baseURL + XSRF (SPA) + optional bearer fallback
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    config.baseURL = resolveApiBase();
    const xsrf = readCookie('XSRF-TOKEN');
    if (xsrf) {
      config.headers['X-XSRF-TOKEN'] = xsrf;
    }
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Response: clear UI auth cache on 401 (redirect handled by AuthContext / caller)
api.interceptors.response.use(
  (response) => response,
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      clearAuth();
      // Don't hard-redirect here — AuthContext logout / checkAuth owns navigation
      // to Filament /app/login so SSO and in-flight requests don't fight.
    }
    return Promise.reject(error);
  }
);

function unwrap<T>(promise: Promise<{ data: { success: boolean; data: T } }>): Promise<T> {
  return promise.then((res) => res.data.data);
}

// ============================================================
// Auth
// ============================================================
export const authApi = {
  login: async (email: string, password: string): Promise<AuthResponse> => {
    await ensureCsrfCookie();
    const response = await api.post('/auth/login', {
      email,
      password,
      device_name: 'pos-frontend',
    });
    const data = response.data.data as AuthResponse;
    setStoredUser(data.user);
    // Prefer session cookies. Memory-only bearer if backend returns token mode
    // (tests / non-SPA) — never persist to sessionStorage.
    if (data.auth_mode === 'token' && data.token) {
      setToken(data.token);
    } else {
      removeToken();
    }
    return data;
  },
  ssoLogin: async (ssoToken: string): Promise<AuthResponse> => {
    await ensureCsrfCookie();
    const response = await api.post('/auth/sso-login', {
      sso_token: ssoToken,
    });
    const data = response.data.data as AuthResponse;
    setStoredUser(data.user);
    if (data.auth_mode === 'token' && data.token) {
      setToken(data.token);
    } else {
      removeToken();
    }
    return data;
  },
  me: (): Promise<User> => unwrap(api.get('/auth/me')),
  logout: async (): Promise<void> => {
    try {
      await ensureCsrfCookie();
      await api.post('/auth/logout');
    } finally {
      clearAuth();
    }
  },
};

// ============================================================
// Customers
// ============================================================
export const customerApi = {
  getAll: (params?: {
    search?: string;
    group_id?: number;
    page?: number;
    per_page?: number;
  }): Promise<{
    data: Customer[];
    total: number;
    current_page: number;
    last_page: number;
    per_page: number;
  }> => unwrap(api.get('/customers', { params })),
  getById: (id: number): Promise<Customer> => unwrap(api.get(`/customers/${id}`)),
  search: (query: string): Promise<Customer[]> =>
    unwrap(api.get('/customers/search', { params: { q: query } })),
  create: (data: {
    name: string;
    phone?: string;
    address?: string;
    notes?: string;
  }): Promise<Customer> => unwrap(api.post('/customers', data)),
};

// ============================================================
// Products / categories / transaksi init
// ============================================================
export const productApi = {
  getAll: (params?: {
    category_id?: number;
    search?: string;
    page?: number;
    per_page?: number;
  }): Promise<{
    data: Product[];
    total: number;
    current_page: number;
    last_page: number;
  }> => unwrap(api.get('/products', { params })),
};

export const categoryApi = {
  getAll: (): Promise<Category[]> => unwrap(api.get('/categories')),
};

export const transaksiApi = {
  getInitData: (): Promise<{
    products: Product[];
    categories: Category[];
    discounts: AvailableDiscount[];
    settings?: StoreSettings;
  }> => unwrap(api.get('/transaksi/init')),
};

// ============================================================
// Discounts
// ============================================================
export const discountApi = {
  available: (): Promise<AvailableDiscount[]> => unwrap(api.get('/discounts/available')),
  calculate: (
    discount_id: number,
    subtotal: number
  ): Promise<{ discount_amount: number; discount_label: string }> =>
    unwrap(api.post('/discounts/calculate', { discount_id, subtotal })),
};

// ============================================================
// Orders
// ============================================================
export const orderApi = {
  getAll: (
    params?: Record<string, unknown>
  ): Promise<{
    data: Order[];
    total: number;
    current_page: number;
    last_page: number;
    per_page: number;
  }> => unwrap(api.get('/orders', { params })),
  getById: (id: number): Promise<Order> => unwrap(api.get(`/orders/${id}`)),
  create: (data: CreateOrderPayload): Promise<Order> => unwrap(api.post('/orders', data)),
  getReceipt: (id: number): Promise<ReceiptData> => unwrap(api.get(`/orders/${id}/receipt`)),
  updateStatus: (id: number, status: string): Promise<Order> =>
    unwrap(api.patch(`/orders/${id}/status`, { status })),
  void: (id: number, reason: string): Promise<Order> =>
    unwrap(api.post(`/orders/${id}/void`, { reason })),
  refund: (id: number, reason: string, amount?: number): Promise<Order> =>
    unwrap(api.post(`/orders/${id}/refund`, { reason, amount })),
  addPayment: (
    id: number,
    amount: number,
    method: string,
    reference?: string
  ): Promise<Order> =>
    unwrap(
      api.post(`/orders/${id}/payment`, {
        amount,
        payment_method: method,
        reference: reference || undefined,
      })
    ),
};

// ============================================================
// Held orders (open bill)
// ============================================================
export const heldOrderApi = {
  getAll: (): Promise<HeldOrder[]> => unwrap(api.get('/held-orders')),
  getById: (id: number): Promise<HeldOrder> => unwrap(api.get(`/held-orders/${id}`)),
  create: (data: HoldOrderPayload): Promise<HeldOrder> => unwrap(api.post('/held-orders', data)),
  delete: (id: number): Promise<void> => unwrap(api.delete(`/held-orders/${id}`)),
};

// ============================================================
// Dashboard
// ============================================================
export const dashboardApi = {
  getStats: (): Promise<DashboardStats> => unwrap(api.get('/dashboard/stats')),
  getSalesChart: (params?: { days?: number }): Promise<{ date: string; revenue: number; orders: number }[]> =>
    unwrap(api.get('/dashboard/sales-chart', { params })),
  getTopProducts: (days = 30, limit = 8): Promise<TopProduct[]> =>
    unwrap(api.get('/dashboard/top-products', { params: { days, limit } })),
  getPeakHours: (days = 30): Promise<PeakHour[]> =>
    unwrap(api.get('/dashboard/peak-hours', { params: { days } })),
  getSalesByCategory: (days = 30): Promise<SalesByCategory[]> =>
    unwrap(api.get('/dashboard/sales-by-category', { params: { days } })),
  getSalesByPayment: (days = 30): Promise<SalesByPayment[]> =>
    unwrap(api.get('/dashboard/sales-by-payment', { params: { days } })),
};

// ============================================================
// Expenses / bookkeeping / reports
// ============================================================
export const expenseApi = {
  getAll: (
    params?: Record<string, unknown>
  ): Promise<{ data: Expense[]; total?: number; last_page?: number }> =>
    unwrap(api.get('/expenses', { params })),
  create: (data: CreateExpensePayload): Promise<Expense> => unwrap(api.post('/expenses', data)),
};

export const bookkeepingApi = {
  getSummary: (
    params?: Record<string, unknown>
  ): Promise<{ total_income: number; total_expenses: number; net_profit: number }> =>
    unwrap(api.get('/bookkeeping/summary', { params })),
};

export const reportApi = {
  salesSummary: (dateFrom: string, dateTo: string): Promise<unknown> =>
    unwrap(api.get('/reports/sales-summary', { params: { date_from: dateFrom, date_to: dateTo } })),
  dailyTrend: (dateFrom: string, dateTo: string): Promise<unknown> =>
    unwrap(api.get('/reports/daily-trend', { params: { date_from: dateFrom, date_to: dateTo } })),
  salesByProduct: (dateFrom: string, dateTo: string): Promise<unknown[]> =>
    unwrap(
      api.get('/reports/sales-by-product', { params: { date_from: dateFrom, date_to: dateTo } })
    ),
  salesByCategory: (dateFrom: string, dateTo: string): Promise<unknown[]> =>
    unwrap(
      api.get('/reports/sales-by-category', { params: { date_from: dateFrom, date_to: dateTo } })
    ),
  salesByCashier: (dateFrom: string, dateTo: string): Promise<unknown[]> =>
    unwrap(
      api.get('/reports/sales-by-cashier', { params: { date_from: dateFrom, date_to: dateTo } })
    ),
  salesByHour: (dateFrom: string, dateTo: string): Promise<unknown[]> =>
    unwrap(api.get('/reports/sales-by-hour', { params: { date_from: dateFrom, date_to: dateTo } })),
};

export const exportApi = {
  downloadReport: async (params: {
    type: string;
    format: 'xlsx' | 'pdf';
    date_from: string;
    date_to: string;
  }): Promise<Blob> => {
    const res = await api.get('/export/report', {
      params,
      responseType: 'blob',
    });
    return res.data as Blob;
  },
};

// ============================================================
// Settings / notifications
// ============================================================
export const settingsApi = {
  getAll: (): Promise<StoreSettings> => unwrap(api.get('/settings')),
  getGroup: (group: string): Promise<StoreSettings> => unwrap(api.get(`/settings/${group}`)),
};

export const notificationApi = {
  getAll: (): Promise<NotificationResponse> => unwrap(api.get('/notifications')),
  markAsRead: (id: number): Promise<void> => unwrap(api.post(`/notifications/${id}/read`)),
  markAllAsRead: (): Promise<void> => unwrap(api.post('/notifications/read-all')),
};

export default api;
