import type { Product, Category, Coupon, Order, User, DashboardStats, FilterOptions, Tutorial } from '../types';

const API_BASE = '/api';

function getAuthHeaders(): HeadersInit {
  const token = localStorage.getItem('zanashop_token');
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
  };
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  return headers;
}

async function handleResponse<T>(res: Response): Promise<T> {
  const data = await res.json();
  if (!res.ok) {
    throw new Error(data.error || data.message || 'خطایی در ارتباط با سرور رخ داد');
  }
  return data as T;
}

export const api = {
  // Auth
  async register(name: string, email: string, mobile: string, password: string): Promise<{ user: User; token: string }> {
    const res = await fetch(`${API_BASE}/auth/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, email, mobile, password }),
    });
    return handleResponse<{ user: User; token: string }>(res);
  },

  async login(email: string, password: string): Promise<{ user: User; token: string }> {
    const res = await fetch(`${API_BASE}/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });
    return handleResponse<{ user: User; token: string }>(res);
  },

  async getMe(): Promise<{ user: User }> {
    const res = await fetch(`${API_BASE}/auth/me`, {
      headers: getAuthHeaders(),
    });
    return handleResponse<{ user: User }>(res);
  },

  // Categories
  async getCategories(all = false): Promise<Category[]> {
    const res = await fetch(`${API_BASE}/categories?all=${all}`, {
      headers: getAuthHeaders(),
    });
    return handleResponse<Category[]>(res);
  },

  async createCategory(data: Partial<Category>): Promise<Category> {
    const res = await fetch(`${API_BASE}/categories`, {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify(data),
    });
    return handleResponse<Category>(res);
  },

  async updateCategory(id: string, data: Partial<Category>): Promise<Category> {
    const res = await fetch(`${API_BASE}/categories/${id}`, {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: JSON.stringify(data),
    });
    return handleResponse<Category>(res);
  },

  async deleteCategory(id: string): Promise<{ message: string }> {
    const res = await fetch(`${API_BASE}/categories/${id}`, {
      method: 'DELETE',
      headers: getAuthHeaders(),
    });
    return handleResponse<{ message: string }>(res);
  },

  // Products
  async getProducts(filters?: FilterOptions & { all?: boolean }): Promise<Product[]> {
    const params = new URLSearchParams();
    if (filters?.categoryId) params.append('category', filters.categoryId);
    if (filters?.search) params.append('search', filters.search);
    if (filters?.sort) params.append('sort', filters.sort);
    if (filters?.isFeatured) params.append('isFeatured', 'true');
    if (filters?.minPrice) params.append('minPrice', filters.minPrice.toString());
    if (filters?.maxPrice) params.append('maxPrice', filters.maxPrice.toString());
    if (filters?.all) params.append('all', 'true');

    const res = await fetch(`${API_BASE}/products?${params.toString()}`, {
      headers: getAuthHeaders(),
    });
    return handleResponse<Product[]>(res);
  },

  async getProduct(idOrSlug: string): Promise<Product> {
    const res = await fetch(`${API_BASE}/products/${idOrSlug}`, {
      headers: getAuthHeaders(),
    });
    return handleResponse<Product>(res);
  },

  async createProduct(data: Partial<Product>): Promise<Product> {
    const res = await fetch(`${API_BASE}/products`, {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify(data),
    });
    return handleResponse<Product>(res);
  },

  async updateProduct(id: string, data: Partial<Product>): Promise<Product> {
    const res = await fetch(`${API_BASE}/products/${id}`, {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: JSON.stringify(data),
    });
    return handleResponse<Product>(res);
  },

  async deleteProduct(id: string): Promise<{ message: string }> {
    const res = await fetch(`${API_BASE}/products/${id}`, {
      method: 'DELETE',
      headers: getAuthHeaders(),
    });
    return handleResponse<{ message: string }>(res);
  },

  // Coupons
  async validateCoupon(code: string, subtotal: number): Promise<{ valid: boolean; discount: number; message: string; coupon?: Coupon }> {
    const res = await fetch(`${API_BASE}/coupons/validate`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ code, subtotal }),
    });
    return handleResponse<{ valid: boolean; discount: number; message: string; coupon?: Coupon }>(res);
  },

  async getCoupons(): Promise<Coupon[]> {
    const res = await fetch(`${API_BASE}/coupons`, {
      headers: getAuthHeaders(),
    });
    return handleResponse<Coupon[]>(res);
  },

  async createCoupon(data: Partial<Coupon>): Promise<Coupon> {
    const res = await fetch(`${API_BASE}/coupons`, {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify(data),
    });
    return handleResponse<Coupon>(res);
  },

  async updateCoupon(id: string, data: Partial<Coupon>): Promise<Coupon> {
    const res = await fetch(`${API_BASE}/coupons/${id}`, {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: JSON.stringify(data),
    });
    return handleResponse<Coupon>(res);
  },

  async deleteCoupon(id: string): Promise<{ message: string }> {
    const res = await fetch(`${API_BASE}/coupons/${id}`, {
      method: 'DELETE',
      headers: getAuthHeaders(),
    });
    return handleResponse<{ message: string }>(res);
  },

  // Orders
  async createOrder(payload: {
    guestInfo: { name: string; mobile: string; email: string; notes?: string };
    items: { productId: string; quantity: number; region?: string }[];
    couponCode?: string;
    paymentMethod: string;
  }): Promise<Order> {
    const res = await fetch(`${API_BASE}/orders`, {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify(payload),
    });
    return handleResponse<Order>(res);
  },

  async getOrders(status?: string): Promise<Order[]> {
    const query = status ? `?status=${status}` : '';
    const res = await fetch(`${API_BASE}/orders${query}`, {
      headers: getAuthHeaders(),
    });
    return handleResponse<Order[]>(res);
  },

  async getOrder(idOrNumber: string): Promise<Order> {
    const res = await fetch(`${API_BASE}/orders/${idOrNumber}`, {
      headers: getAuthHeaders(),
    });
    return handleResponse<Order>(res);
  },

  async updateOrderStatus(id: string, updates: {
    orderStatus?: Order['orderStatus'];
    paymentStatus?: Order['paymentStatus'];
    licenseKeys?: string[];
    deliveryInstructions?: string;
  }): Promise<Order> {
    const res = await fetch(`${API_BASE}/orders/${id}/status`, {
      method: 'PATCH',
      headers: getAuthHeaders(),
      body: JSON.stringify(updates),
    });
    return handleResponse<Order>(res);
  },


  // Tutorials
  async getTutorials(all = false): Promise<Tutorial[]> {
    const res = await fetch(`${API_BASE}/tutorials?all=${all}`, { headers: getAuthHeaders() });
    return handleResponse<Tutorial[]>(res);
  },

  async createTutorial(data: Partial<Tutorial>): Promise<Tutorial> {
    const res = await fetch(`${API_BASE}/tutorials`, {
      method: 'POST', headers: getAuthHeaders(), body: JSON.stringify(data),
    });
    return handleResponse<Tutorial>(res);
  },

  async updateTutorial(id: string, data: Partial<Tutorial>): Promise<Tutorial> {
    const res = await fetch(`${API_BASE}/tutorials/${id}`, {
      method: 'PUT', headers: getAuthHeaders(), body: JSON.stringify(data),
    });
    return handleResponse<Tutorial>(res);
  },

  async deleteTutorial(id: string): Promise<{ message: string }> {
    const res = await fetch(`${API_BASE}/tutorials/${id}`, {
      method: 'DELETE', headers: getAuthHeaders(),
    });
    return handleResponse<{ message: string }>(res);
  },

  // Admin
  async getDashboardStats(): Promise<DashboardStats> {
    const res = await fetch(`${API_BASE}/admin/stats`, {
      headers: getAuthHeaders(),
    });
    return handleResponse<DashboardStats>(res);
  },

  async getUsers(): Promise<User[]> {
    const res = await fetch(`${API_BASE}/admin/users`, {
      headers: getAuthHeaders(),
    });
    return handleResponse<User[]>(res);
  },

  async updateUser(id: string, updates: Partial<User>): Promise<User> {
    const res = await fetch(`${API_BASE}/admin/users/${id}`, {
      method: 'PATCH',
      headers: getAuthHeaders(),
      body: JSON.stringify(updates),
    });
    return handleResponse<User>(res);
  },
};
