'use client'

import { useTranslations } from 'next-intl'
import React, { Suspense, useEffect, useState } from 'react'

import { TbInfoHexagon, TbPuzzle, TbPuzzleOff } from 'react-icons/tb'

import { WidgetEmpty } from '../Widget.utils'

import { _ } from '@/utils'

interface ContentProps {
	componentId?: number
	dataOptions: any
	viewOptions: any
}

export function Content({
	componentId,
	dataOptions,
	viewOptions
}: ContentProps) {
	const t = useTranslations('components')
	//
	const [WidgetComponent, setWidgetComponent] =
		useState<React.ComponentType<any>>()
	//
	useEffect(() => {
		const loadWidget = async () => {
			try {
				const component = await import(
					/* webpackIgnore: true */
					`${process.env.NEXT_PUBLIC_SERVER_URL}/components/${componentId}/index.js`
				)
				setWidgetComponent(() => component.default(React))
			} catch (error) {
				return (
					<WidgetEmpty
						icon={<TbInfoHexagon className='text-danger!' />}
						text={'error'}
					/>
				)
			}
		}

		loadWidget()
	}, [componentId])
	//
	useEffect(() => {
		console.log('dataOptions', dataOptions)
		console.log('viewOptions', viewOptions)
	}, [dataOptions, viewOptions])
	//
	if (_.isUndefined(componentId)) {
		return <WidgetEmpty icon={<TbPuzzleOff />} text={t('empty')} />
	}
	//
	//////////
	//
	const WidgetFallback = (
		<WidgetEmpty
			icon={<TbPuzzle />}
			text={t('loading')}
			className='animate-bounce'
		/>
	)
	//
	if (_.isUndefined(WidgetComponent)) {
		return WidgetFallback
	}
	//
	return (
		<Suspense fallback={WidgetFallback}>
			<WidgetComponent
				dataSettings={dataOptions}
				viewSettings={viewOptions}
			/>
		</Suspense>
	)
}
