'use client'

import { type ReactNode, useMemo, useState } from 'react'

import { LayerModel, useUpdateLayerMutation } from '@/graphql'

import { GridSizeType, LayoutsType, ProjectData } from '@/types'

import { ProjectContext, type ProjectContextProps } from '@/contexts'

type ProjectProviderProps = {
	project: ProjectData
	children: ReactNode
}

export function ProjectProvider({ project, children }: ProjectProviderProps) {
	const [layer, setLayer] = useState<LayerModel>()
	const [layouts, setLayouts] = useState<LayoutsType>({})
	const [tempLayouts, setTempLayouts] = useState<LayoutsType>({})
	//
	const [isEdit, setIsEdit] = useState(false)
	const [gridKey, setGridKey] = useState(0)
	const [gridSize, setGridSize] = useState<GridSizeType>('full')

	const [updateLayer] = useUpdateLayerMutation({
		onCompleted() {
			setLayouts(tempLayouts)
			//
			setIsEdit(false)
			setGridSize('full')
		}
	})

	const saveHandler = () => {
		updateLayer({
			variables: {
				data: {
					projectId: project.id,
					layerId: layer!.id,
					layouts: tempLayouts
				}
			}
		})
	}

	const cancelHandler = () => {
		setTempLayouts(layouts)
		//
		setIsEdit(false)
		setGridKey(Math.random())
		setGridSize('full')
	}

	const contextValue = useMemo<ProjectContextProps>(
		() => ({
			project,
			//
			layer,
			setLayer,
			//
			layouts,
			setLayouts,
			//
			tempLayouts,
			setTempLayouts,
			//
			isEdit,
			setIsEdit,
			//
			gridKey,
			setGridKey,
			//
			gridSize,
			setGridSize,
			//
			saveHandler,
			cancelHandler
		}),
		[
			project,
			//
			layer,
			setLayer,
			//
			layouts,
			setLayouts,
			//
			tempLayouts,
			setTempLayouts,
			//
			isEdit,
			setIsEdit,
			//
			gridKey,
			setGridKey,
			//
			gridSize,
			setGridSize,
			//
			saveHandler,
			cancelHandler
		]
	)

	return (
		<ProjectContext.Provider value={contextValue}>
			{children}
		</ProjectContext.Provider>
	)
}
