'use client'

import {zodResolver} from '@hookform/resolvers/zod'
import fs from 'node:fs'
import path from 'node:path'
import {useCallback, useState} from 'react'
import Dropzone from 'react-dropzone'
import {useFieldArray, useForm} from 'react-hook-form'
import {z} from 'zod'

import {onProductCreateAction} from '@/actions/admin/product'
import {createCategoryFormSchema} from '@/lib/schemas/admin/category'
import {createProductFormSchema} from '@/lib/schemas/admin/product'
import {cn, dump} from '@/lib/utils'
import {ResourceMessages} from '@/types'
import {Button} from '@/ui/button'
import {
	Form,
	FormControl,
	FormField,
	FormItem,
	FormLabel,
	FormMessage
} from '@/ui/form'
import {Input} from '@/ui/input'

export default function CreateForm() {
	const [loading, setLoading] = useState(false)
	const [error, setError] = useState('')
	const [success, setSuccess] = useState('')

	const form = useForm<z.infer<typeof createProductFormSchema>>({
		resolver: zodResolver(createProductFormSchema),
		mode: 'onBlur',
		defaultValues: {
			files: []
		}
	})

	const {fields, append} = useFieldArray({
		name: 'files',
		control: form.control
	})

	console.log(form.formState.errors)

	const onSubmit = async (values: z.infer<typeof createProductFormSchema>) => {
		setLoading(true)
		onProductCreateAction(values).then((res: any) => {
			if (res?.error) {
				setError(res?.error)
				setSuccess('')
				setLoading(false)
			} else {
				setSuccess(res?.success as string)
				setError('')
				setLoading(false)
			}
		})
	}

	return (
		<div className='flex h-screen items-center justify-center'>
			<Form {...form}>
				<form
					action=''
					onSubmit={form.handleSubmit(onSubmit)}
					className='max-w-md flex-1 space-y-5'
				>
					<div className='products_name_price_desc relative'>
						{fields.map((_, index) => {
							return (
								<div key={index}>
									<div className='mb-2 mt-7 text-xl font-bold'>
										{/*{form.getValues(`files.${index}.file.name`)}*/}
										{dump(form.getValues(`files.${index}`))}
									</div>
									<div className='flex gap-x-3'>
										<FormField
											control={form.control}
											key={index}
											name={`files.${index}.alt`}
											render={({field}) => (
												<FormItem>
													<FormLabel>Файл Альт Ім'я</FormLabel>
													<FormControl>
														<Input {...field} />
													</FormControl>
													<FormMessage className='capitalize text-red-500' />
												</FormItem>
											)}
										/>
										<FormField
											control={form.control}
											key={index + 1}
											name={`files.${index}.title`}
											render={({field}) => (
												<FormItem>
													<FormLabel>Назва файлу</FormLabel>
													<FormControl>
														<Input {...field} />
													</FormControl>
													<FormMessage className='capitalize text-red-500' />
												</FormItem>
											)}
										/>
									</div>
								</div>
							)
						})}
					</div>
					<div className='products relative'>
						<FormField
							control={form.control}
							name='files'
							render={() => (
								<Dropzone
									accept={{
										'image/*': ['.jpg', '.jpeg', '.png']
									}}
									onDropAccepted={acceptedFiles => {
										acceptedFiles.map(acceptedFile => {
											console.log('acceptedFile', acceptedFile)

											return append({
												file: acceptedFile,
												alt: '',
												title: ''
											})
										})
									}}
									multiple={true}
									maxSize={5000000}
								>
									{({getRootProps, getInputProps}) => (
										<section>
											<div {...getRootProps()}>
												<input {...getInputProps()} />
												<p>
													Перетягніть тут, киньте кілька файлів або натисніть,
													щоб вибрати файли
												</p>
											</div>
										</section>
									)}
								</Dropzone>
							)}
						/>
					</div>
					<Button type='submit' className='!mt-0 w-full'>
						Створити
					</Button>
				</form>
			</Form>
		</div>
	)

	// return (
	// 	<div className='flex flex-col bg-zinc-200 py-10'>
	// 		<h1 className='text-center text-3xl font-bold capitalize'>
	// 			Створити галерею
	// 		</h1>
	// 		<div className='mx-auto mb-10 mt-6 flex min-h-[320px] w-[80%] flex-wrap gap-1 rounded-md bg-white p-5 shadow-sm'></div>
	// 		<div className='flex justify-center'>
	// 			<Button>Завантажити зображення</Button>
	// 		</div>
	// 	</div>
	// )
}
