import { MOCK_WC_CATEGORIES, MOCK_ALL_PRODUCTS } from '../data/mockWooCommerceData';

export function getCategoryImageUrl(category?: WCCategory | null | { name?: string; slug?: string; image?: { src?: string } | null }): string {
  if (category?.image?.src && category.image.src.trim().length > 0) {
    return category.image.src;
  }
  const slug = (category?.slug || category?.name || '').toLowerCase();

  if (slug.includes('apparel') || slug.includes('clothing') || slug.includes('kameez') || slug.includes('suit') || slug.includes('lawn')) {
    return 'https://images.unsplash.com/photo-1584917865442-de89df76afd3?auto=format&fit=crop&w=800&q=80';
  }
  if (slug.includes('women') || slug.includes('female')) {
    return 'https://images.unsplash.com/photo-1610030469983-98e550d6193c?auto=format&fit=crop&w=800&q=80';
  }
  if (slug.includes('men') || slug.includes('male')) {
    return 'https://images.unsplash.com/photo-1617137984095-74e4e5e3613f?auto=format&fit=crop&w=800&q=80';
  }
  if (slug.includes('health') || slug.includes('beauty') || slug.includes('cosmetic') || slug.includes('care') || slug.includes('shaving') || slug.includes('trimmer') || slug.includes('personal')) {
    return 'https://images.unsplash.com/photo-1522337360788-8b13dee7a37e?auto=format&fit=crop&w=800&q=80';
  }
  if (slug.includes('home') || slug.includes('garden') || slug.includes('kitchen') || slug.includes('decor')) {
    return 'https://images.unsplash.com/photo-1513694203232-719a280e022f?auto=format&fit=crop&w=800&q=80';
  }
  if (slug.includes('electronic') || slug.includes('audio') || slug.includes('power') || slug.includes('gadget')) {
    return 'https://images.unsplash.com/photo-1508685096489-7aacd43bd3b1?auto=format&fit=crop&w=800&q=80';
  }
  if (slug.includes('hardware') || slug.includes('tool')) {
    return 'https://images.unsplash.com/photo-1581092160607-ee22621dd758?auto=format&fit=crop&w=800&q=80';
  }
  if (slug.includes('vehicle') || slug.includes('car') || slug.includes('part')) {
    return 'https://images.unsplash.com/photo-1486006920555-c77dce18193b?auto=format&fit=crop&w=800&q=80';
  }
  if (slug.includes('food') || slug.includes('beverage') || slug.includes('snack') || slug.includes('honey')) {
    return 'https://images.unsplash.com/photo-1587049352847-81a56d773cae?auto=format&fit=crop&w=800&q=80';
  }
  if (slug.includes('stationery') || slug.includes('craft') || slug.includes('office')) {
    return 'https://images.unsplash.com/photo-1456735190827-d1262f71b8a3?auto=format&fit=crop&w=800&q=80';
  }
  if (slug.includes('jewelry') || slug.includes('watch') || slug.includes('ring')) {
    return 'https://images.unsplash.com/photo-1535632066927-ab7c9ab60908?auto=format&fit=crop&w=800&q=80';
  }
  if (slug.includes('bag') || slug.includes('wallet') || slug.includes('case') || slug.includes('purse')) {
    return 'https://images.unsplash.com/photo-1590874103328-eac38a683ce7?auto=format&fit=crop&w=800&q=80';
  }
  return 'https://images.unsplash.com/photo-1472851294608-062f824d29cc?auto=format&fit=crop&w=800&q=80';
}

export function decodeHtmlEntities(str: string): string {
  if (!str) return '';
  let result = str;
  if (typeof window !== 'undefined' && typeof document !== 'undefined') {
    try {
      const txt = document.createElement('textarea');
      txt.innerHTML = str;
      result = txt.value;
      if (result.includes('&amp;') || result.includes('&AMP;') || result.includes('&lt;') || result.includes('&LT;') || result.includes('&#')) {
        txt.innerHTML = result;
        result = txt.value;
      }
    } catch {
      // fallback
    }
  }
  return result
    .replace(/&amp;/gi, '&')
    .replace(/&lt;/gi, '<')
    .replace(/&gt;/gi, '>')
    .replace(/&quot;/gi, '"')
    .replace(/&#039;/g, "'")
    .replace(/&#8217;/g, "'")
    .replace(/&#8216;/g, "'")
    .replace(/&#8220;/g, '"')
    .replace(/&#8221;/g, '"')
    .replace(/&nbsp;/gi, ' ');
}

export function stripHtmlTags(str: string): string {
  if (!str) return '';
  const decoded = decodeHtmlEntities(str);
  return decoded.replace(/<[^>]*>?/gm, '').trim();
}

export interface WCCategory {
  id: number;
  name: string;
  slug: string;
  parent: number;
  description: string;
  image?: { src: string; alt?: string } | null;
  count: number;
}

export interface WCProduct {
  id: number;
  name: string;
  slug: string;
  price: string;
  regular_price: string;
  sale_price: string;
  on_sale: boolean;
  stock_status?: string;
  rating_count?: number;
  average_rating?: string;
  short_description?: string;
  description?: string;
  sku?: string;
  shipping_class?: string;
  shipping_class_id?: number;
  shipping_cost?: string | number;
  weight?: string;
  meta_data?: Array<{ key: string; value: any }>;
  images: Array<{ id?: number; src: string; alt?: string }>;
  categories: Array<{ id: number; name: string; slug?: string }>;
  permalink: string;
  store_index?: number;
  store_url?: string;
  attributes?: Array<{ name: string; options: string[] }>;
  date_created?: string;
}

export interface APIStatus {
  connected: boolean;
  siteUrl: string;
  error?: string;
}

export async function checkWooCommerceStatus(): Promise<APIStatus> {
  try {
    const res = await fetch('/api/wc/status');
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } catch (err: any) {
    return {
      connected: false,
      siteUrl: 'https://timenlife.shop',
      error: err.message || 'Server unreachable',
    };
  }
}

export async function getWCCategories(): Promise<WCCategory[]> {
  try {
    const res = await fetch('/api/wc/categories?per_page=100');
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    const rawCategories: WCCategory[] = data.categories || [];
    if (rawCategories.length > 0) {
      return rawCategories
        .map((cat) => ({
          ...cat,
          name: decodeHtmlEntities(cat.name),
          description: decodeHtmlEntities(cat.description || ''),
        }))
        .sort((a, b) => b.count - a.count); // Sort by highest product count first
    }
    return MOCK_WC_CATEGORIES;
  } catch (err) {
    console.warn('WooCommerce categories fetch failed, using fallback:', err);
    return MOCK_WC_CATEGORIES;
  }
}

export interface WCProductFetchResponse {
  products: WCProduct[];
  totalProducts: number;
  totalPages: number;
  currentPage: number;
}

export async function getWCProducts(
  categoryId?: number | string,
  perPage = 50,
  page = 1,
  search = ''
): Promise<WCProductFetchResponse> {
  try {
    const queryParams = new URLSearchParams();
    queryParams.append('per_page', String(perPage));
    queryParams.append('page', String(page));
    if (categoryId) queryParams.append('category', String(categoryId));
    if (search) queryParams.append('search', search);

    const res = await fetch(`/api/wc/products?${queryParams.toString()}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    const cleanProducts: WCProduct[] = (data.products || []).map((p: WCProduct) => {
      const rawImages = Array.isArray(p.images) && p.images.length > 0 ? p.images : [];
      const sanitizedImages = rawImages.map((img) => {
        const srcStr = typeof img === 'string' ? img : img?.src || '';
        const cleanSrc = srcStr.trim().startsWith('http://')
          ? srcStr.trim().replace('http://', 'https://')
          : srcStr.trim();
        return {
          id: typeof img === 'object' ? img?.id : undefined,
          src: cleanSrc || 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?auto=format&fit=crop&w=800&q=80',
          alt: typeof img === 'object' ? img?.alt || p.name : p.name,
        };
      });

      if (sanitizedImages.length === 0) {
        sanitizedImages.push({
          id: 0,
          src: 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?auto=format&fit=crop&w=800&q=80',
          alt: p.name,
        });
      }

      return {
        ...p,
        name: decodeHtmlEntities(p.name),
        short_description: decodeHtmlEntities(p.short_description || ''),
        description: decodeHtmlEntities(p.description || ''),
        images: sanitizedImages,
        categories: (p.categories || []).map((c) => ({
          ...c,
          name: decodeHtmlEntities(c.name),
        })),
      };
    });

    if (cleanProducts.length > 0) {
      return {
        products: cleanProducts,
        totalProducts: data.totalProducts || cleanProducts.length,
        totalPages: data.totalPages || Math.ceil((data.totalProducts || cleanProducts.length) / perPage),
        currentPage: data.currentPage || page,
      };
    }

    // Fallback to mock products filtering
    return filterMockProducts(categoryId, perPage, page, search);
  } catch (err) {
    console.warn('WooCommerce products fetch failed, using mock fallback:', err);
    return filterMockProducts(categoryId, perPage, page, search);
  }
}

function filterMockProducts(
  categoryId?: number | string,
  perPage = 50,
  page = 1,
  search = ''
): WCProductFetchResponse {
  let filtered = [...MOCK_ALL_PRODUCTS];

  if (categoryId && categoryId !== 'all') {
    const catIdNum = Number(categoryId);
    filtered = filtered.filter((p) =>
      p.categories?.some((c) => c.id === catIdNum || c.slug === categoryId)
    );
  }

  if (search && search.trim()) {
    const q = search.toLowerCase().trim();
    filtered = filtered.filter(
      (p) =>
        p.name.toLowerCase().includes(q) ||
        (p.short_description && p.short_description.toLowerCase().includes(q))
    );
  }

  const totalProducts = filtered.length;
  const totalPages = Math.ceil(totalProducts / perPage) || 1;
  const startIndex = (page - 1) * perPage;
  const paginatedProducts = filtered.slice(startIndex, startIndex + perPage);

  return {
    products: paginatedProducts,
    totalProducts,
    totalPages,
    currentPage: page,
  };
}

export async function getWCProductById(idOrSlug: number | string): Promise<WCProduct | null> {
  try {
    const res = await fetch(`/api/wc/products/${encodeURIComponent(idOrSlug)}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    if (data.product) return data.product;
  } catch (err) {
    console.warn(`WooCommerce product ${idOrSlug} fetch failed, checking mock fallback:`, err);
  }

  const target = String(idOrSlug).toLowerCase().trim();
  return (
    MOCK_ALL_PRODUCTS.find((p) => {
      const pSlug = p.slug?.toLowerCase() || '';
      const pNameSlug = p.name ? p.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') : '';
      return p.id.toString() === target || pSlug === target || pNameSlug === target;
    }) || null
  );
}

export interface WCVariation {
  id: number;
  price: string;
  regular_price: string;
  sale_price: string;
  on_sale: boolean;
  stock_status: string;
  stock_quantity?: number | null;
  sku: string;
  image?: { id?: number; src: string; alt?: string };
  attributes: Array<{ id?: number; name: string; option: string }>;
}

export async function getWCProductVariations(idOrSlug: number | string): Promise<WCVariation[]> {
  try {
    const res = await fetch(`/api/wc/products/${encodeURIComponent(idOrSlug)}/variations`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    return (data.variations || []).map((v: any) => ({
      ...v,
      attributes: (v.attributes || []).map((a: any) => ({
        ...a,
        option: decodeHtmlEntities(a.option || ''),
      })),
    }));
  } catch (err) {
    console.warn(`WooCommerce product ${idOrSlug} variations fetch failed:`, err);
    return [];
  }
}

export interface WCOrderPayload {
  status?: string;
  target_store?: number;
  store_url?: string;
  payment_method: string;
  payment_method_title: string;
  set_paid: boolean;
  billing: {
    first_name: string;
    last_name: string;
    address_1: string;
    city: string;
    state?: string;
    postcode?: string;
    country: string;
    email: string;
    phone: string;
  };
  shipping: {
    first_name: string;
    last_name: string;
    address_1: string;
    city: string;
    country: string;
  };
  line_items: Array<{
    product_id: number;
    quantity: number;
  }>;
  coupon_lines?: Array<{
    code: string;
    discount?: string;
    discount_tax?: string;
  }>;
  fee_lines?: Array<{
    name: string;
    total: string;
  }>;
  discount_total?: string;
  shipping_lines?: Array<{
    method_id: string;
    method_title: string;
    total: string;
  }>;
  customer_note?: string;
  total?: string;
}

export interface WCOrderResponse {
  id: number;
  status: string;
  currency: string;
  total: string;
  leopards_cn?: string;
  date_created?: string;
}

export async function createWCOrder(payload: WCOrderPayload): Promise<WCOrderResponse | null> {
  try {
    const res = await fetch('/api/wc/orders', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    return data.order || null;
  } catch (err) {
    console.error('Failed to create order:', err);
    return null;
  }
}

export async function updateWCOrderStatus(params: {
  wcOrderId?: number;
  orderId?: string;
  status: string;
  customerEmail?: string;
  courierInfo?: any;
  storeIndex?: number;
}): Promise<boolean> {
  try {
    const res = await fetch('/api/wc/orders/update-status', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(params),
    });
    if (!res.ok) return false;
    const data = await res.json();
    return !!data.success;
  } catch (err) {
    console.warn('Failed to update WooCommerce order status:', err);
    return false;
  }
}

export interface OrderTrackingInfo {
  orderId: string;
  courier: string;
  cnNumber: string;
  status: string;
  origin: string;
  destination: string;
  bookedDate: string;
  estimatedDelivery: string;
  history: Array<{
    status: string;
    location: string;
    time: string;
  }>;
}

export async function trackWCOrder(idOrCn: string): Promise<OrderTrackingInfo | null> {
  try {
    const res = await fetch(`/api/wc/tracking/${encodeURIComponent(idOrCn)}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const data = await res.json();
    return data.tracking || null;
  } catch (err) {
    console.error('Failed to track order:', err);
    return null;
  }
}

export async function uploadReviewImageToWordPress(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = async () => {
      try {
        const imageBase64 = reader.result as string;
        const res = await fetch('/api/wp/upload-media', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            imageBase64,
            fileName: file.name || `review-${Date.now()}.jpg`,
            mimeType: file.type || 'image/jpeg',
          }),
        });

        if (!res.ok) {
          const errData = await res.json().catch(() => ({}));
          throw new Error(errData.error || `Upload failed with status ${res.status}`);
        }

        const data = await res.json();
        if (data.success && data.url) {
          resolve(data.url);
        } else {
          throw new Error(data.error || 'WordPress upload failed');
        }
      } catch (err) {
        console.error('WordPress upload error, fallback to temporary URL:', err);
        // Fallback if WP upload fails
        resolve(URL.createObjectURL(file));
      }
    };
    reader.onerror = (err) => reject(err);
    reader.readAsDataURL(file);
  });
}
