import fs from 'fs'
import path from 'path'
import productsData from '@/data/products.json'
import { cleanupOldProductFiles, cleanupProductFiles } from '@/lib/fileUtils'

export interface Product {
  id: number
  slug: string
  name: string
  description: string
  price: string
  images: string[]
  videoUrl: string | null
  featured: boolean
}

const productsFilePath = path.join(process.cwd(), 'data', 'products.json')

// Dynamic data functions (read from file system for real-time updates)
export async function getAllProducts(): Promise<Product[]> {
  return await readProductsFromFile()
}

export async function getProductBySlug(slug: string): Promise<Product | undefined> {
  const products = await readProductsFromFile()
  const product = products.find((product) => product.slug === slug)
  return product
}

export async function getFeaturedProducts(): Promise<Product[]> {
  const products = await readProductsFromFile()
  return products.filter((product) => product.featured)
}

// Legacy synchronous functions for backward compatibility (use dynamic versions instead)
export function getAllProductsSync(): Product[] {
  return productsData as Product[]
}

export function getProductBySlugSync(slug: string): Product | undefined {
  return productsData.find((product) => product.slug === slug) as Product | undefined
}

export function getFeaturedProductsSync(): Product[] {
  return productsData.filter((product) => product.featured) as Product[]
}

// Dynamic data functions (for admin operations)
export async function readProductsFromFile(): Promise<Product[]> {
  try {
    const fileContents = fs.readFileSync(productsFilePath, 'utf8')
    return JSON.parse(fileContents) as Product[]
  } catch (error) {
    console.error('Error reading products file:', error)
    return []
  }
}

export async function writeProductsToFile(products: Product[]): Promise<void> {
  try {
    // Fix any existing slugs with Cyrillic characters
    const fixedProducts = products.map(product => {
      if (product.slug && /[^a-z0-9-]/.test(product.slug)) {
        // Slug contains non-ASCII characters, regenerate it
        return {
          ...product,
          slug: generateSlug(product.name)
        }
      }
      return product
    })

    const jsonData = JSON.stringify(fixedProducts, null, 2)
    fs.writeFileSync(productsFilePath, jsonData, 'utf8')
  } catch (error) {
    console.error('Error writing products file:', error)
    throw new Error('Failed to save products')
  }
}

export async function createProduct(productData: Omit<Product, 'id' | 'slug'>): Promise<Product> {
  const products = await readProductsFromFile()

  // Generate slug from name
  const slug = generateSlug(productData.name)

  // Check if slug already exists
  if (products.find(p => p.slug === slug)) {
    throw new Error('Товар з такою назвою вже існує')
  }

  // Generate new ID
  const maxId = products.length > 0 ? Math.max(...products.map(p => p.id)) : 0
  const newProduct: Product = {
    ...productData,
    id: maxId + 1,
    slug,
  }

  products.push(newProduct)
  await writeProductsToFile(products)

  return newProduct
}

export async function updateProduct(slug: string, productData: Partial<Omit<Product, 'id' | 'slug'>>): Promise<Product | null> {
  const products = await readProductsFromFile()
  const productIndex = products.findIndex(p => p.slug === slug)

  if (productIndex === -1) {
    return null
  }

  const oldProduct = { ...products[productIndex] }

  // If name is being updated, generate new slug
  if (productData.name && productData.name !== products[productIndex].name) {
    const newSlug = generateSlug(productData.name)
    // Check if new slug conflicts with existing products
    if (products.find(p => p.slug === newSlug && p.id !== products[productIndex].id)) {
      throw new Error('Товар з такою назвою вже існує')
    }
    products[productIndex].slug = newSlug
  }

  // Update product data
  products[productIndex] = {
    ...products[productIndex],
    ...productData,
  }

  // Clean up old files that are no longer referenced
  cleanupOldProductFiles(oldProduct, products[productIndex])

  await writeProductsToFile(products)
  return products[productIndex]
}

export async function deleteProduct(slug: string): Promise<boolean> {
  const products = await readProductsFromFile()
  const productToDelete = products.find(p => p.slug === slug)

  if (!productToDelete) {
    return false // Product not found
  }

  // Clean up all files for this product
  cleanupProductFiles(productToDelete)

  const filteredProducts = products.filter(p => p.slug !== slug)
  await writeProductsToFile(filteredProducts)
  return true
}

// Transliterate Cyrillic to Latin
function transliterate(text: string): string {
  const cyrillicToLatin: { [key: string]: string } = {
    'а': 'a', 'б': 'b', 'в': 'v', 'г': 'h', 'ґ': 'g', 'д': 'd', 'е': 'e', 'є': 'ye', 'ж': 'zh',
    'з': 'z', 'и': 'y', 'і': 'i', 'ї': 'yi', 'й': 'y', 'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n',
    'о': 'o', 'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u', 'ф': 'f', 'х': 'kh', 'ц': 'ts',
    'ч': 'ch', 'ш': 'sh', 'щ': 'shch', 'ь': '', 'ю': 'yu', 'я': 'ya',
    'ё': 'yo', 'ъ': '', 'ы': 'y', 'э': 'e',
    // Uppercase
    'А': 'a', 'Б': 'b', 'В': 'v', 'Г': 'h', 'Ґ': 'g', 'Д': 'd', 'Е': 'e', 'Є': 'ye', 'Ж': 'zh',
    'З': 'z', 'И': 'y', 'І': 'i', 'Ї': 'yi', 'Й': 'y', 'К': 'k', 'Л': 'l', 'М': 'm', 'Н': 'n',
    'О': 'o', 'П': 'p', 'Р': 'r', 'С': 's', 'Т': 't', 'У': 'u', 'Ф': 'f', 'Х': 'kh', 'Ц': 'ts',
    'Ч': 'ch', 'Ш': 'sh', 'Щ': 'shch', 'Ь': '', 'Ю': 'yu', 'Я': 'ya',
    'Ё': 'yo', 'Ъ': '', 'Ы': 'y', 'Э': 'e'
  }

  return text.split('').map(char => cyrillicToLatin[char] || char).join('')
}

function generateSlug(name: string): string {
  let slug = transliterate(name)
    .toLowerCase()
    .replace(/[^a-z0-9\s-]/g, '') // Remove special characters (only allow ASCII letters, numbers, spaces, hyphens)
    .replace(/\s+/g, '-') // Replace spaces with hyphens
    .replace(/-+/g, '-') // Replace multiple hyphens with single
    .trim()
    .replace(/^-|-$/g, '') // Remove leading/trailing hyphens

  // Fallback: if slug is empty or only contains invalid characters, use a generic slug
  if (!slug || slug.length === 0) {
    slug = `product-${Date.now()}`
  }

  return slug
}

