import odooApi from '@/core/api/odooApi'
import Link from '@/core/components/elements/Link/Link'
import DesktopView from '@/core/components/views/DesktopView'
import { createSlug } from '@/core/utils/slug'
import { useEffect, useState } from 'react'

const Category = () => {
  const [categories, setCategories] = useState([])

  useEffect(() => {
    const loadCategories = async () => {
      let dataCategories = await odooApi('GET', '/api/v1/category/tree')
      dataCategories = dataCategories?.map((category) => {
        category.childs = category.childs.map((child1Category) => {
          return {
            ...child1Category,
            isOpen: false
          }
        })
        return {
          ...category,
          isOpen: false
        }
      })
      setCategories(dataCategories)
    }
    loadCategories()
  }, [])

  return (
    <DesktopView>
      <div className='category-mega-box'>
        {categories?.map((category) => (
          <div key={category.id}>
            <Link
              href={createSlug('/shop/category/', category.name, category.id)}
              className='category-mega-box__parent'
            >
              {category.name}
            </Link>
            <div className='category-mega-box__child-wrapper'>
              <div className='grid grid-cols-3 gap-x-4 gap-y-6 max-h-full overflow-auto'>
                {category.childs.map((child1Category) => (
                  <div key={child1Category.id}>
                    <Link
                      href={createSlug('/shop/category/', child1Category.name, child1Category.id)}
                      className='category-mega-box__child-one mb-4'
                    >
                      {child1Category.name}
                    </Link>
                    <div className='flex flex-col gap-y-3'>
                      {child1Category.childs.map((child2Category) => (
                        <Link
                          href={createSlug(
                            '/shop/category/',
                            child2Category.name,
                            child2Category.id
                          )}
                          className='category-mega-box__child-two'
                          key={child2Category.id}
                        >
                          {child2Category.name}
                        </Link>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        ))}
      </div>
    </DesktopView>
  )
}

export default Category
