import { ApiResponse, PaginatedResponse, Banner, Category, Product, Settings, PaymentMethod, DeliveryType, Order, Coupon, SupportTicket, SupportMessage } from "@/types";

const API_URL = process.env.NEXT_PUBLIC_API_URL || "https://your-admin-domain.com/api";
const BASE_URL = API_URL.replace(/\/api\/?$/, "");

if (!process.env.NEXT_PUBLIC_API_URL) {
  // console.warn("Missing NEXT_PUBLIC_API_URL, using default.");
}

export const getImageUrl = (path: any) => {
  if (!path || typeof path !== 'string') return "https://placehold.co/600x600/f8f9fa/adb5bd?text=No+Image";
  if (path.startsWith("http")) return path;
  
  const cleanPath = path.startsWith("/") ? path.slice(1) : path;
  
  // If the path already starts with storage/ or uploads/ or images/, just prepend BASE_URL
  if (
    cleanPath.startsWith("storage/") || 
    cleanPath.startsWith("uploads/") || 
    cleanPath.startsWith("images/") ||
    cleanPath.startsWith("assets/")
  ) {
    return `${BASE_URL}/${cleanPath}`;
  }
  
  // For Laravel, if it's a simple path, it's most likely in storage/
  return `${BASE_URL}/storage/${cleanPath}`;
};

async function fetchApi<T>(endpoint: string, options?: RequestInit): Promise<T> {
  let token = null;
  if (typeof window !== "undefined") {
    token = localStorage.getItem("auth_token");
  }

  const fetchOptions: RequestInit = {
    ...options,
    headers: {
      "Content-Type": "application/json",
      "Accept": "application/json",
      ...(token ? { "Authorization": `Bearer ${token}` } : {}),
      ...options?.headers,
    },
  };

  // No revalidate for static export to avoid build errors
  // if (typeof window === "undefined") {
  //   (fetchOptions as any).next = { revalidate: 60 };
  // }

  const isBrowser = typeof window !== "undefined";
  const url = isBrowser
    ? `/api/proxy?path=${encodeURIComponent(endpoint)}`
    : `${API_URL}${endpoint}`;

  try {
    const res = await fetch(url, fetchOptions);

    if (!res.ok) {
      const errorData = await res.json().catch(() => ({}));
      throw new Error(errorData.message || `Error ${res.status}: Failed to fetch ${endpoint}`);
    }

    return await res.json();
  } catch (error: any) {
    // Silent handling for connection errors to avoid Next.js error overlay in dev
    const message = String(error?.message || "");
    const isConnectionError =
      error.name === "TypeError" &&
      (message === "Failed to fetch" || message.includes("fetch"));

    // For 404-style errors (e.g. missing orders), avoid noisy console logs
    const isNotFoundError = message.startsWith("Error 404:");

    if (!isConnectionError && !isNotFoundError) {
      // console.error(`API Error (${endpoint}):`, message);
    }

    // Return mock-friendly empty response for connection errors or failures
    if (isConnectionError || message.includes("Failed to fetch")) {
      return { data: [] } as any;
    }

    throw error;
  }
}

export const api = {
  getBanners: () => fetchApi<ApiResponse<Banner[]>>("/banners"),
  getSpecialOfferBanners: () => fetchApi<ApiResponse<Banner[]>>("/special-offers/banners"),
  getCategories: () => fetchApi<ApiResponse<Category[]>>("/categories"),
  getProducts: (params?: { 
    page?: number; 
    limit?: number; 
    category_id?: string | number; 
    is_featured?: boolean; 
    is_special_offer?: boolean;
    is_premium?: boolean;
    is_flash_sale?: boolean;
    search?: string;
  }) => {
    const query = new URLSearchParams();
    if (params?.page) query.append("page", params.page.toString());
    if (params?.limit) query.append("limit", params.limit.toString());
    if (params?.category_id) query.append("category_id", params.category_id.toString());
    if (params?.is_featured) query.append("is_featured", "1");
    if (params?.is_special_offer) query.append("is_special_offer", "1");
    if (params?.is_premium) query.append("is_premium", "1");
    if (params?.is_flash_sale) query.append("is_flash_sale", "1");
    if (params?.search) query.append("search", params.search);
    return fetchApi<PaginatedResponse<Product>>(`/products?${query.toString()}`);
  },

  getPaymentMethods: () => fetchApi<ApiResponse<PaymentMethod[]>>("/payment-methods"),
  getDeliveryTypes: () => fetchApi<ApiResponse<DeliveryType[]>>("/delivery-types"),
  applyCoupon: (code: string, subtotal: number) => fetchApi<ApiResponse<Coupon>>("/coupons/apply", {
    method: "POST",
    body: JSON.stringify({ code, subtotal }),
  }),
  createReview: (data: { product_id: number | string; order_item_id: number; rating: number; comment?: string }) =>
    fetchApi<ApiResponse<any>>("/reviews", {
      method: "POST",
      body: JSON.stringify(data),
    }),
  updateReview: (id: number, data: { rating: number; comment?: string }) =>
    fetchApi<ApiResponse<any>>(`/reviews/${id}`, {
      method: "PUT",
      body: JSON.stringify(data),
    }),
  getMyReviews: (orderId: string | number) =>
    fetchApi<ApiResponse<Array<{ id: number; order_item_id: number; product_id: number; rating: number; comment?: string }>>>(`/reviews/my?order_id=${orderId}`),
  createOrder: (order: Order) => fetchApi<ApiResponse<{ id: number }>>("/orders", {
    method: "POST",
    body: JSON.stringify(order),
  }),
  initiatePayment: (data: { payment_method_id: number; amount: number; currency: string; callback_url?: string }) => 
    fetchApi<any>("/payments/initiate", {
      method: "POST",
      body: JSON.stringify(data),
    }),

  getPage: (slug: string) => fetchApi<ApiResponse<any>>(`/pages/${slug}`),
  getPopularProducts: () => fetchApi<ApiResponse<Product[]>>("/products/popular"),
  getProductById: (id: string) => fetchApi<ApiResponse<Product>>(`/products/${id}`),
  getSettings: () => fetchApi<ApiResponse<Settings>>("/settings"),
  getOrders: () => fetchApi<ApiResponse<Order[]>>("/orders"),
  getOrderById: (id: string | number) => fetchApi<ApiResponse<Order>>(`/orders/${id}`),
  getOrderByNumber: (orderNumber: string) =>
    fetchApi<ApiResponse<Order>>(`/orders/by-number/${encodeURIComponent(orderNumber)}`),
  getCoupons: () => fetchApi<ApiResponse<Coupon[]>>("/coupons"),
  getReviews: (productId?: string | number) => {
    const q = productId ? `?product_id=${productId}` : "";
    return fetchApi<ApiResponse<any[]>>(`/reviews${q}`);
  },
  getSelectedReviews: (ids: Array<number | string>) => {
    const list = ids.map((v) => Number(v)).filter((n) => !isNaN(n) && n > 0);
    const q = list.length ? `?ids=${list.join(",")}` : "";
    return fetchApi<ApiResponse<any[]>>(`/reviews${q}`);
  },
  getFlashSale: () => fetchApi<ApiResponse<any>>("/flash-sale"),

  newsletterSubscribe: (email: string) =>
    fetchApi<ApiResponse<any>>("/newsletter-subscriptions", {
      method: "POST",
      body: JSON.stringify({ email }),
    }),

  // Notifications
  getNotifications: (limit: number = 20) =>
    fetchApi<ApiResponse<any[]>>(`/notifications?limit=${limit}`),

  // Support
  getSupportTickets: () =>
    fetchApi<ApiResponse<SupportTicket[]>>("/support/tickets"),
  getSupportTicketById: (id: number | string) =>
    fetchApi<ApiResponse<SupportTicket & { messages: SupportMessage[] }>>(
      `/support/tickets/${id}`
    ),
  createSupportTicket: (data: {
    subject: string;
    message: string;
    order_id?: number | null;
  }) =>
    fetchApi<ApiResponse<SupportTicket>>("/support/tickets", {
      method: "POST",
      body: JSON.stringify(data),
    }),
  replySupportTicket: (id: number | string, message: string) =>
    fetchApi<ApiResponse<SupportMessage>>(`/support/tickets/${id}/reply`, {
      method: "POST",
      body: JSON.stringify({ message }),
    }),

  // Auth
  login: (credentials: any) => fetchApi<ApiResponse<{ user: any; access_token: string }>>("/login", {
    method: "POST",
    body: JSON.stringify(credentials),
  }),
  register: (data: any) => fetchApi<ApiResponse<{ user: any; access_token: string }>>("/register", {
    method: "POST",
    body: JSON.stringify(data),
  }),
  logout: (token: string) => fetchApi<ApiResponse<any>>("/logout", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${token}`,
    },
  }),
  getUser: (token: string) => fetchApi<ApiResponse<any>>("/user", {
    headers: {
      "Authorization": `Bearer ${token}`,
    },
  }),
  updateProfile: (data: any) => fetchApi<ApiResponse<any>>("/user/update", {
    method: "POST",
    body: JSON.stringify(data),
  }),

  // Wallet
  getWallet: () => fetchApi<ApiResponse<{ balance: string; transactions: any[] }>>("/wallet"),
  depositWallet: (data: { amount: number; payment_method: string; transaction_id: string }) => 
    fetchApi<ApiResponse<any>>("/wallet/deposit", {
      method: "POST",
      body: JSON.stringify(data),
    }),

  // Analytics / Tracking
  trackVisit: (path: string) =>
    fetchApi<any>("/visits", {
      method: "POST",
      body: JSON.stringify({ path }),
    }),
  getVisitStats: (days: number = 7) =>
    fetchApi<ApiResponse<{ labels: string[]; visits: number[]; today: number; total: number }>>(`/visits/stats?days=${days}`),
};
