import React from 'react'

import { Grid, Product } from '../../components'

import { database } from '../../firebase/config'
import { collection, getDocs, limit, query, where } from 'firebase/firestore'

export const generateAccountOptions = (accounts: Array<any>) => {
  const data = accounts.map(({ account_name, account_number }: any) => {
    const text = account_name + ' ' + account_number

    return {
      name: text,
      value: text
    }
  })

  return data
}

export const getCategories = async () => {
  let categories: Array<any> = []

  const q = query(collection(database, '/modules/v_procurement/categories'))

  const results = await getDocs(q)

  results.forEach((document: any) => {
    const data = document.data()

    let category = {
      id: document.id,
      ...data
    }

    return categories.push(category)
  })

  return categories
}

export const handleScan = (setBasket: Function, setScan: Function) => {
  return setScan((state: string) => {
    let _scan = state

    if (_scan.includes('undefined')) _scan = _scan.replace('undefined', '')

    const q = query(
      collection(database, '/modules/v_procurement/products'),
      where('sku', '==', _scan),
      limit(1)
    )

    getDocs(q).then(snapshot => {
      snapshot.forEach(document => {
        const data = document.data()

        addToBasket(data, setBasket)
      })
    })

    return ''
  })
}

export const renderCategories = (data: Array<any>, action: Function) => {
  if (!data) {
    return <p>Loading..</p>
  }

  if (data.length === 0) {
    return <p className='text-gray-500'>No categories found</p>
  }

  return (
    <Grid columns={4}>
      {data
        .sort((a, b) => a.name.localeCompare(b.name))
        .map((item: any) => (
          <div
            key={item.id}
            className='bg-gray-100 hover:bg-gray-200 border cursor-pointer flex h-28 items-center justify-center p-2 rounded text-center'
            onClick={() => action(item.id)}
          >
            <p>{item.name}</p>
          </div>
        ))}
    </Grid>
  )
}

export const getProducts = async () => {
  let products: Array<any> = []

  const q = query(collection(database, '/modules/v_procurement/products'))

  const results = await getDocs(q)

  results.forEach((document: any) => {
    const data = document.data()

    let category = {
      id: document.id,
      ...data
    }

    return products.push(category)
  })

  return products
}

export const addToBasket = (product: any, setBasket: Function) => {
  const _product = {
    id: product.id,
    sku: product.sku,
    name: product.name,
    unit_price: product.unit_price,
    quantity: 1
  }

  setBasket((state: Array<any>) => {
    const item = state.find(item => item.id == product.id)

    if (item) {
      return state.map(item =>
        item.id === product.id
          ? { ..._product, quantity: (item.quantity += 1) }
          : item
      )
    } else {
      return [...state, _product]
    }
  })
}

export const renderProducts = (
  data: Array<any>,
  category: string | null,
  catalogue_id: string,
  setBasket: Function
) => {
  if (!data) {
    return <p>Loading..</p>
  }

  if (data.length === 0) {
    return <p className='text-gray-500'>No products found</p>
  }

  if (!category) {
    return null
  }

  return (
    <Grid columns={3}>
      {data
        .filter(({ category_id }) => category_id === category)
        .filter(product => product.catalogue_id === catalogue_id)
        .map((item: any) => (
          <Product
            data={item}
            key={item.id}
            onClick={() => addToBasket(item, setBasket)}
          />
        ))}
    </Grid>
  )
}
