import { zodResolver } from '@hookform/resolvers/zod'
import { useTranslations } from 'next-intl'
import { Controller, useForm } from 'react-hook-form'

import { useCreateDatasetMutation } from '@/graphql'

import { TbChevronLeft } from 'react-icons/tb'

import { CheckIcon } from '@/components/atoms/icons'

import {
	Button,
	Form,
	Input,
	Label,
	Tags,
	Textarea,
	Typography
} from '@/components/atoms'

import { useCreateDataset } from '@/hooks'
import { createDatasetSchema, TypeCreateDatasetSchema } from '@/schemas'

const { Title } = Typography

type Step4Props = {
	prevTabHandler: () => void
}

function Step4({ prevTabHandler }: Step4Props) {
	const tg = useTranslations('')
	const t = useTranslations('datasets.creation.steps.four')
	//
	const { name, columns, fileInfo } = useCreateDataset()
	//
	const {
		handleSubmit,
		control,
		formState: { errors }
	} = useForm<TypeCreateDatasetSchema>({
		resolver: zodResolver(createDatasetSchema),
		defaultValues: {
			name,
			description: ''
		}
	})
	//
	const [createDataset, { loading }] = useCreateDatasetMutation({
		onCompleted() {},
		onError(error) {}
	})
	//
	const onSubmit = (data: TypeCreateDatasetSchema) => {
		createDataset({
			variables: {
				data: {
					...data,
					...(fileInfo && { fileId: fileInfo.id }),
					columns: columns.map(col => {
						// @ts-ignore
						delete col.__typename
						return col
					})
				}
			}
		})
	}
	//
	return (
		<div className='flex flex-col gap-y-4'>
			<Form layout='vertical' onSubmit={handleSubmit(onSubmit)}>
				<Form.Item>
					<Label htmlFor='name'>{t('fields.name')}*</Label>
					<Controller
						name='name'
						control={control}
						render={({ field }) => <Input id='name' {...field} />}
					/>
					<Form.Message error={errors.name} />
				</Form.Item>

				<Form.Item className='max-h-36'>
					<Label htmlFor='description'>
						{t('fields.description')}
					</Label>
					<Controller
						name='description'
						control={control}
						render={({ field }) => (
							<Textarea id='description' {...field} />
						)}
					/>
					<Form.Message error={errors.description} />
				</Form.Item>

				<Form.Item>
					<Label htmlFor='name'>{t('fields.access-rights')}</Label>
					<Tags id='guards' />
				</Form.Item>

				<div className='mt-auto flex justify-between'>
					<Button
						color='secondary'
						variant='label'
						onClick={prevTabHandler}
					>
						<TbChevronLeft />
						{tg('back')}
					</Button>

					<Button type='submit' color='success' disabled={loading}>
						{tg('create')} <CheckIcon />
					</Button>
				</div>
			</Form>
		</div>
	)
}

export { Step4 }
