// API Response Types matching Laravel API
export interface ApiCategory {
  id: number;
  name: string;
  slug: string;
  description?: string;
  parent_id?: number;
  children?: ApiCategory[];
}

export interface ApiReview {
  id: number;
  product_id: number;
  rating: number;
  comment: string;
  is_verified_purchase: boolean;
  is_approved: boolean;
  created_at: string;
  updated_at: string;
  user: {
    id: number;
    name: string;
  };
}

export interface ApiReviewStats {
  average_rating: number;
  total_reviews: number;
  rating_distribution: {
    5: number;
    4: number;
    3: number;
    2: number;
    1: number;
  };
}

export interface ApiReviewsResponse {
  data: ApiReview[];
  meta: {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
  };
  stats: ApiReviewStats;
}

export interface ApiProductVariant {
  id: number;
  product_id: number;
  size: string;
  color: string;
  price: string | number;
  stock: number;
  sku: string;
}

export interface ApiProduct {
  id: number;
  name: string;
  description: string;
  category_id: number;
  brand: string;
  base_price: string | number;
  images: string[];
  slug: string;
  is_active: boolean;
  category?: {
    id: number;
    name: string;
    slug: string;
    parent_id?: number;
    description?: string;
    created_at?: string;
    updated_at?: string;
  };
  variants?: ApiProductVariant[];
}

export interface ApiProductsResponse {
  data: ApiProduct[];
  links?: {
    first: string;
    last: string;
    prev: string | null;
    next: string | null;
  };
  meta?: {
    current_page: number;
    from: number;
    last_page: number;
    per_page: number;
    to: number;
    total: number;
  };
}

// Existing frontend types (keep for compatibility)
export interface Product {
  id: string;
  slug?: string;
  title: string;
  price: string;
  oldPrice?: string;
  imageSrc: string;
  saleLabel?: string;
  rating: number;
  ratingCount: number;
}

export interface CategoryCount {
  name: string;
  count: number;
}

// Extended types for product detail functionality
export interface ProductDetailData {
  id: number;
  name: string;
  description: string;
  brand: string;
  base_price: number;
  images: string[];
  slug: string;
  is_active: boolean;
  category: {
    id: number;
    name: string;
    slug: string;
  };
  variants: ApiProductVariant[];
  
  // Computed properties for UI
  availableSizes: string[];
  availableColors: string[];
  priceRange: {
    min: number;
    max: number;
  };
}

export interface SelectedVariant {
  size?: string;
  color?: string;
  variant?: ApiProductVariant;
  price: number;
  stock: number;
}

export interface CartItem {
  id: string;
  productId: number;
  variantId?: number;
  name: string;
  price: number;
  quantity: number;
  image: string;
  size?: string;
  color?: string;
  maxStock: number;
}

// Helper function to convert API product to frontend Product
export function convertApiProductToProduct(apiProduct: ApiProduct): Product {
  const variant = apiProduct.variants?.[0];
  const price = variant ? parseFloat(variant.price.toString()) : parseFloat(apiProduct.base_price.toString());
  
  // Get image with fallback
  let imageSrc = '/assets/placeholder.png'; // Default fallback
  
  if (apiProduct.images && apiProduct.images.length > 0) {
    const firstImage = apiProduct.images[0];
    // Check if it's a valid URL or base64 image
    if (firstImage && (firstImage.startsWith('http') || firstImage.startsWith('/') || firstImage.startsWith('data:image'))) {
      imageSrc = firstImage;
    }
  }
  
  return {
    id: apiProduct.id.toString(),
    slug: apiProduct.slug,
    title: apiProduct.name,
    price: `$${price.toFixed(2)}`,
    imageSrc: imageSrc,
    rating: 4.5, // Default rating, can be dynamic later
    ratingCount: Math.floor(Math.random() * 200) + 50, // Mock for now
  };
}

// Helper function to convert API product to ProductDetailData
export function convertApiProductToDetailData(apiProduct: ApiProduct): ProductDetailData {
  console.log('Converting API product to detail data:', apiProduct);
  
  // Validate input
  if (!apiProduct) {
    throw new Error('API product data is null or undefined');
  }
  
  if (!apiProduct.id) {
    throw new Error('API product is missing required ID field');
  }
  
  const variants = apiProduct.variants || [];
  console.log('Product variants:', variants);
  
  const availableSizes = [...new Set(variants.map(v => v.size).filter(Boolean))];
  const availableColors = [...new Set(variants.map(v => v.color).filter(Boolean))];
  
  // Safely handle price conversion with detailed logging
  const prices: number[] = [];
  
  variants.forEach((variant, index) => {
    console.log(`Processing variant ${index}:`, variant);
    if (variant.price) {
      try {
        const price = parseFloat(variant.price.toString());
        if (!isNaN(price) && price > 0) {
          prices.push(price);
        }
      } catch (error) {
        console.error(`Error converting variant ${index} price:`, variant.price, error);
      }
    }
  });
  
  console.log('Processed variant prices:', prices);
  console.log('Base price from API:', apiProduct.base_price);
  
  let basePrice = 0;
  if (apiProduct.base_price) {
    try {
      basePrice = parseFloat(apiProduct.base_price.toString());
      if (isNaN(basePrice)) {
        console.warn('Base price conversion resulted in NaN:', apiProduct.base_price);
        basePrice = 0;
      }
    } catch (error) {
      console.error('Error converting base price:', apiProduct.base_price, error);
      basePrice = 0;
    }
  }
  
  if (prices.length === 0 && basePrice > 0) {
    prices.push(basePrice);
  }
  
  // Ensure we have at least one price
  if (prices.length === 0) {
    console.warn('No valid prices found, using default price of 0');
    prices.push(0);
  }
  
  const result = {
    id: apiProduct.id,
    name: apiProduct.name || 'Unknown Product',
    description: apiProduct.description || '',
    brand: apiProduct.brand || 'Unknown Brand',
    base_price: basePrice,
    images: apiProduct.images || [],
    slug: apiProduct.slug || '',
    is_active: apiProduct.is_active !== false,
    category: apiProduct.category ? {
      id: apiProduct.category.id,
      name: apiProduct.category.name,
      slug: apiProduct.category.slug
    } : { id: 0, name: 'Unknown', slug: 'unknown' },
    variants: variants,
    availableSizes,
    availableColors,
    priceRange: {
      min: Math.min(...prices),
      max: Math.max(...prices)
    }
  };
  
  console.log('Final converted product data:', result);
  return result;
}
