import { logger } from '../../utils/logger';
import { IPlatformConnector, PlatformProduct, PublishResult } from './IPlatformConnector';
import axios from 'axios';

interface TikTokProduct {
  product_id: string;
  title: string;
  description: string;
  price: { original_price: string; currency: string };
  main_image: string;
  images: string[];
  skus: Array<{
    id: string;
    price: string;
    stock: number;
    specs: Record<string, string>;
  }>;
  category_id: string;
  attributes: Record<string, any>;
}

interface TikTokOrder {
  order_id: string;
  order_status: string;
  create_time: number;
  buyer_info: {
    user_id: string;
    username: string;
  };
  items: Array<{
    product_id: string;
    sku_id: string;
    quantity: number;
    price: string;
  }>;
  shipping_info: {
    address: string;
    city: string;
    state: string;
    country: string;
    zip_code: string;
  };
  total_amount: string;
  currency: string;
}

export class TikTokConnector implements IPlatformConnector {
  platformCode = 'TIKTOK';
  capabilities = {
    hasApi: true,
    supportsPriceSync: true,
    supportsInventorySync: true,
    supportsOrderPull: true
  };

  private apiBaseUrl = 'https://open-api.tiktokglobalshop.com';
  private appKey = process.env.TIKTOK_APP_KEY || '';
  private appSecret = process.env.TIKTOK_APP_SECRET || '';

  async authorize(shopId: string): Promise<boolean> {
    logger.info(`[TikTokConnector] Authorizing shop: ${shopId}`);
    return true;
  }

  async pullProducts(shopId: string, params?: { page?: number; pageSize?: number }): Promise<PlatformProduct[]> {
    logger.info(`[TikTokConnector] Pulling products for shop: ${shopId}`);

    if (!this.appKey || this.appKey === '') {
      return this.getMockProducts();
    }

    try {
      const response = await axios.get(`${this.apiBaseUrl}/api/products/search`, {
        params: {
          shop_id: shopId,
          page_number: params?.page || 1,
          page_size: params?.pageSize || 50
        }
      });

      const products: TikTokProduct[] = response.data?.data?.products || [];
      return products.map(this.mapToPlatformProduct);
    } catch (error) {
      logger.warn('[TikTokConnector] API call failed, returning mock data');
      return this.getMockProducts();
    }
  }

  async pullOrders(shopId: string, params?: { startTime?: number; endTime?: number }): Promise<TikTokOrder[]> {
    logger.info(`[TikTokConnector] Pulling orders for shop: ${shopId}`);

    if (!this.appKey || this.appKey === '') {
      return this.getMockOrders();
    }

    try {
      const response = await axios.get(`${this.apiBaseUrl}/api/orders/search`, {
        params: {
          shop_id: shopId,
          start_time: params?.startTime || Math.floor(Date.now() / 1000) - 86400 * 7,
          end_time: params?.endTime || Math.floor(Date.now() / 1000)
        }
      });

      return response.data?.data?.orders || [];
    } catch (error) {
      logger.warn('[TikTokConnector] Order API call failed, returning mock data');
      return this.getMockOrders();
    }
  }

  async pushListing(shopId: string, product: PlatformProduct): Promise<PublishResult> {
    logger.info(`[TikTokConnector] Pushing listing to TikTok Shop: ${product.title}`);

    if (!this.appKey || this.appKey === '') {
      return {
        success: true,
        externalId: `TK-${Date.now()}`,
        publishUrl: `https://shop.tiktok.com/product/TK-${Date.now()}`
      };
    }

    try {
      const tiktokProduct = this.mapFromPlatformProduct(product);
      const response = await axios.post(
        `${this.apiBaseUrl}/api/products/create`,
        { shop_id: shopId, product: tiktokProduct }
      );

      return {
        success: true,
        externalId: response.data?.data?.product_id,
        publishUrl: `https://shop.tiktok.com/product/${response.data?.data?.product_id}`
      };
    } catch (error: any) {
      logger.error(`[TikTokConnector] Push listing failed: ${error.message}`);
      return {
        success: false,
        error: error.message
      };
    }
  }

  async updatePrice(shopId: string, externalId: string, newPrice: number): Promise<boolean> {
    logger.info(`[TikTokConnector] Updating price for ${externalId} to ${newPrice}`);

    if (!this.appKey || this.appKey === '') {
      return true;
    }

    try {
      await axios.post(`${this.apiBaseUrl}/api/products/update_price`, {
        shop_id: shopId,
        product_id: externalId,
        price: newPrice
      });
      return true;
    } catch (error: any) {
      logger.error(`[TikTokConnector] Update price failed: ${error.message}`);
      return false;
    }
  }

  async syncInventory(shopId: string, externalId: string, quantity: number): Promise<boolean> {
    logger.info(`[TikTokConnector] Syncing inventory for ${externalId}: ${quantity}`);

    if (!this.appKey || this.appKey === '') {
      return true;
    }

    try {
      await axios.post(`${this.apiBaseUrl}/api/products/update_stock`, {
        shop_id: shopId,
        product_id: externalId,
        stock: quantity
      });
      return true;
    } catch (error: any) {
      logger.error(`[TikTokConnector] Sync inventory failed: ${error.message}`);
      return false;
    }
  }

  async calculateShipping(shopId: string, params: { countryCode: string; weight: number }): Promise<{
    carrier: string;
    cost: number;
    currency: string;
    estimatedDays: number;
  }> {
    const baseCost = params.countryCode === 'US' ? 3.99 : 8.99;
    const weightCost = Math.max(0, (params.weight - 0.5) * 2);
    
    return {
      carrier: 'TikTok Shipping',
      cost: baseCost + weightCost,
      currency: 'USD',
      estimatedDays: params.countryCode === 'US' ? 3 : 10
    };
  }

  private mapToPlatformProduct(tiktokProduct: TikTokProduct): PlatformProduct {
    return {
      externalId: tiktokProduct.product_id,
      title: tiktokProduct.title,
      description: tiktokProduct.description,
      price: parseFloat(tiktokProduct.price.original_price),
      currency: tiktokProduct.price.currency || 'USD',
      images: [tiktokProduct.main_image, ...tiktokProduct.images],
      skus: tiktokProduct.skus.map(sku => ({
        skuId: sku.id,
        price: parseFloat(sku.price),
        stock: sku.stock,
        specs: sku.specs
      })),
      platform: 'TIKTOK',
      category: tiktokProduct.category_id,
      attributes: tiktokProduct.attributes
    };
  }

  private mapFromPlatformProduct(product: PlatformProduct): Partial<TikTokProduct> {
    return {
      title: product.title,
      description: product.description || '',
      price: {
        original_price: product.price.toString(),
        currency: product.currency || 'USD'
      },
      main_image: product.images[0] || '',
      images: product.images.slice(1),
      category_id: product.category || '',
      attributes: product.attributes || {}
    };
  }

  private getMockProducts(): PlatformProduct[] {
    return [
      {
        externalId: 'TK_PROD_001',
        title: 'TikTok Viral LED Ring Light',
        description: 'Professional 10-inch LED ring light with tripod stand, perfect for TikTok videos and live streaming.',
        price: 29.99,
        currency: 'USD',
        images: [
          'https://example.com/tiktok/ring-light-1.jpg',
          'https://example.com/tiktok/ring-light-2.jpg'
        ],
        skus: [
          { skuId: 'TK_SKU_001_W', price: 29.99, stock: 150, specs: { color: 'White' } },
          { skuId: 'TK_SKU_001_B', price: 29.99, stock: 100, specs: { color: 'Black' } }
        ],
        platform: 'TIKTOK',
        category: 'Electronics',
        attributes: { brand: 'TikTokViral', material: 'ABS Plastic' }
      },
      {
        externalId: 'TK_PROD_002',
        title: 'Trendy Phone Grip Stand',
        description: 'Cute and trendy phone grip stand, perfect accessory for content creators.',
        price: 9.99,
        currency: 'USD',
        images: ['https://example.com/tiktok/phone-grip.jpg'],
        skus: [
          { skuId: 'TK_SKU_002', price: 9.99, stock: 500, specs: {} }
        ],
        platform: 'TIKTOK',
        category: 'Accessories'
      }
    ];
  }

  private getMockOrders(): TikTokOrder[] {
    return [
      {
        order_id: 'TK_ORDER_001',
        order_status: 'SHIPPED',
        create_time: Math.floor(Date.now() / 1000) - 3600,
        buyer_info: {
          user_id: 'TK_USER_001',
          username: 'tiktok_buyer_1'
        },
        items: [
          {
            product_id: 'TK_PROD_001',
            sku_id: 'TK_SKU_001_W',
            quantity: 1,
            price: '29.99'
          }
        ],
        shipping_info: {
          address: '123 Main St',
          city: 'Los Angeles',
          state: 'CA',
          country: 'US',
          zip_code: '90001'
        },
        total_amount: '35.98',
        currency: 'USD'
      }
    ];
  }
}

export default TikTokConnector;
