import apiGlobal from '@/services/apiGlobal';
import axios, { AxiosError } from 'axios';

interface ICreateEvent {
  eventName: string;
  eventSummary: string;
  organizerImage: File;
  media: File[];
  price: string;
  numberOfSeats: string;
  organizerName: string;
  address: string;
  country: string;
  state: string;
  city: string;
  eventDate: string;
  startTime: string;
  endTime: string;
  latitude: string;
  longitude: string;
}

interface UserData {
  fullName?: string;
  emailAddress?: string;
  phoneNumber?: string;
}

interface CartItem {
  quantity?: number;
  color?: string;
  size?: string;
  product?: {
    productName?: string;
    productId?: string;
    productImage?: string;
    price?: number;
    color?: string;
    size?: string;
    description?: string;
    category?: string;
    brand?: string;
    sku?: string;
    weight?: string;
    dimensions?: string;
    material?: string;
    style?: string;
    gender?: string;
    ageGroup?: string;
  };
  productName?: string;
  productId?: string;
  productImage?: string;
  price?: number;
  amount?: number;
  description?: string;
  category?: string;
  brand?: string;
  sku?: string;
  weight?: string;
  dimensions?: string;
  material?: string;
  style?: string;
  gender?: string;
  ageGroup?: string;
}

interface CartData {
  cartRandomId?: string;
  cartItems?: CartItem[];
}

export const updateOrderStatus = async (
  id: string,
  data: { status: string; cancelReason?: string }
) => {
  console.log('Updating order status:', { id, data });
  // Format the request data to match backend expectations
  const requestData = {
    status: data.status.toLowerCase(), // Keep status as is
    cancelReason: data.cancelReason
  };
  console.log('Request data:', requestData);
  const response = await apiGlobal.put(`/changeOrderStatus/${id}`, requestData);
  console.log('Update response:', response?.data);
  return response;
};

export const getOrderDetails = async (id: string) => {
  try {
    const response = await apiGlobal.get(`/fetchSingleOrder/${id}`);
    return response;
  } catch (error) {
    console.error('Error fetching order details:', error);
    throw error;
  }
};

export const adminCancelOrder = async (
  id: string,
  data: { cancellationReason: string }
) => {
  console.log('Admin canceling order:', { id, data });
  const response = await apiGlobal.put(`/admin/cancelOrder/${id}`, data);
  console.log('Admin cancel response:', response?.data);
  return response;
};

export const adminFetchCancelledOrders = async (params: {
  skip?: number;
  limit?: number;
}) => {
  try {
    console.log('Admin fetching cancelled orders:', params);
    
    const queryParams = new URLSearchParams();
    queryParams.append('skip', (params.skip || 0).toString());
    queryParams.append('limit', (params.limit || 10).toString());

    const url = `/admin/fetchCancelledOrders?${queryParams.toString()}`;
    console.log('Admin cancelled orders URL:', url);

    const response = await apiGlobal.get(url);
    console.log('Admin cancelled orders response:', response?.data);
    return response;
  } catch (error) {
    console.error('Error fetching cancelled orders:', error);
    throw error;
  }
};

export const fetchOrdersByUser = async (userId: string, params: {
  offset: number;
  limit: number;
  search?: string;
  sort?: string;
  sortField?: string;
  status?: string;
}) => {
  try {
    console.log('fetchOrdersByUser params:', { userId, ...params });
    
    // Map the status to the correct value
    let statusValue = '';
    if (params.status) {
      switch (params.status.toLowerCase()) {
        case 'new':
          statusValue = 'processing';
          break;
        case 'delivered':
          statusValue = 'delivered';
          break;
        case 'canceled':
          statusValue = 'cancelled'; // Note: using 'cancelled' for backend consistency
          break;
        default:
          statusValue = params.status.toLowerCase();
      }
    }

    console.log('Using status value:', statusValue);

    // Construct the URL with all parameters
    const queryParams = new URLSearchParams();
    queryParams.append('skip', params.offset.toString());
    queryParams.append('limit', params.limit.toString());
    if (params.search) queryParams.append('search', params.search);
    if (params.sort) queryParams.append('sort', params.sort);
    if (params.sortField) queryParams.append('sortField', params.sortField);
    if (statusValue) queryParams.append('status', statusValue);

    const url = `/fetchOrdersByUser/${userId}?${queryParams.toString()}`;
    console.log('Request URL:', url);

    const response = await apiGlobal.get(url);
    console.log('Raw API Response:', response);
    console.log('Orders API Response Data:', response.data);

    // Normalize the response structure
    const normalizedResponse = {
      data: {
        data: response.data?.data?.orders || response.data?.data || [],
        total: response.data?.data?.total || response.data?.data?.count || 0
      }
    };

    console.log('Normalized Response:', normalizedResponse);
    return { data: normalizedResponse.data };
  } catch (error) {
    console.error('Error in fetchOrdersByUser:', error);
    throw error;
  }
};

export const getAllOrders = async (params: {
  offset: number;
  limit: number;
  search?: string;
  sort?: string;
  sortField?: string;
  status?: string;
}) => {
  try {
    console.log('getAllOrders params:', params);
    
    // Map the status to the correct value
    let statusValue = '';
    if (params.status) {
      switch (params.status.toLowerCase()) {
        case 'new':
          statusValue = 'processing';
          break;
        case 'delivered':
          statusValue = 'delivered';
          break;
        case 'canceled':
          statusValue = 'canceled';
          break;
        default:
          statusValue = params.status.toLowerCase();
      }
    }

    console.log('Using status value:', statusValue);

    // Construct the URL with all parameters
    const queryParams = new URLSearchParams();
    queryParams.append('skip', params.offset.toString());
    queryParams.append('limit', params.limit.toString());
    if (params.search) queryParams.append('search', params.search);
    if (params.sort) queryParams.append('sort', params.sort);
    if (params.sortField) queryParams.append('sortField', params.sortField);
    if (statusValue) queryParams.append('status', statusValue);

    const url = `/fetchAllOrders?${queryParams.toString()}`;
    console.log('Request URL:', url);

    const response = await apiGlobal.get(url);
    console.log('Raw API Response:', response);
    console.log('Orders API Response Data:', response.data);

    // Normalize the response structure
    const normalizedResponse = {
      data: {
        data: response.data?.data?.orders || response.data?.data || [],
        total: response.data?.data?.total || response.data?.data?.count || 0
      }
    };

    console.log('Normalized Response:', normalizedResponse);
    return { data: normalizedResponse.data };
  } catch (error) {
    console.error('Error in getAllOrders:', error);
    throw error;
  }
};

// Export orders to CSV
export const exportOrdersToCSV = (orders: any[]) => {
  const headers = [
    'Order ID',
    'Customer Name',
    'Customer Email', 
    'Customer Phone',
    'Order Date',
    'Subtotal',
    'Shipping Cost',
    'Total Amount',
    'Status',
    'Shipping Address',
    'City',
    'State',
    'Country',
    'Zip Code',
    'Items Count',
    'Payment Method',
    'Shipping Method',
    'Notes',
  ];

  const csvData = orders.map(order => {
    const subtotal = order.subtotal || order.price || 0;
    const shippingCost = order.shippingCost || 0;
    const totalAmount = subtotal + shippingCost; // Always calculate total
    
    return [
      order.cartRandomId || order._id || '',
      order.userName || order.userData?.fullName || '',
      order.userData?.emailAddress || order.emailAddress || '',
      order.userData?.phoneNumber || order.phoneNumber || '',
      order.createdAt ? new Date(order.createdAt).toLocaleDateString() : '',
      subtotal.toFixed(2),
      shippingCost.toFixed(2),
      totalAmount.toFixed(2),
      order.status || '',
      order.address?.address || '',
      order.address?.city || '',
      order.address?.state || '',
      order.address?.country || '',
      order.address?.zipCode || '',
      order.cartItems?.length || 0,
      order.paymentMethod || '',
      order.shippingMethod || '',
      order.notes || '',
    ];
  });

  const csvContent = [
    headers.join(','),
    ...csvData.map(row => row.map(field => `"${field}"`).join(','))
  ].join('\n');

  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);
  link.setAttribute('href', url);
  link.setAttribute('download', `orders_${new Date().toISOString().split('T')[0]}.csv`);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
