'use client'

import { useTranslations } from 'next-intl'
import { useState } from 'react'

import { DatasetFileEncoding } from '@/graphql'

import { Input, Label, Select, Typography, Upload } from '@/components/atoms'

import { useCreateDataset } from '@/hooks'
import { bytes, SizeStringValue } from '@/utils'

const { Title } = Typography

const maxSize = bytes(
	process.env.NEXT_PUBLIC_DATASET_MAX_SIZE as SizeStringValue
)

function UploadFile() {
	const t = useTranslations('datasets.creation.steps.two.file')
	//
	const {
		setName,
		//
		fileInfo,
		setFileInfo,
		//
		datasetFileInfo,
		setDatasetFileInfo
	} = useCreateDataset()
	//
	const [format, setFormat] = useState('.csv,.txt')
	//
	const changeHandler = (files: any[]) => {
		setName(files[0] ? files[0].originalName! : '')
		setFileInfo(files[0] ? { ...files[0], progress: 100 } : null)
		setDatasetFileInfo(prev => {
			return {
				...prev,
				path: files[0]?.path!
			}
		})
	}
	//
	return (
		<div className='mb-4 flex flex-col gap-y-4'>
			<div className='grid grid-cols-24 gap-4'>
				<div className='col-span-7 flex flex-col gap-1'>
					<Label>{t('fields.format')}</Label>
					<Select defaultValue={format} onValueChange={setFormat}>
						<Select.Item value='.csv,.txt'>CSV</Select.Item>
						<Select.Item value='.xlsx,.xls'>XLSX</Select.Item>
						<Select.Item value='.json'>JSON</Select.Item>
						<Select.Item value='.xml'>XML</Select.Item>
					</Select>
				</div>
				{/*  */}
				<div className='col-span-9 flex flex-col gap-1'>
					<Label>{t('fields.encoding')}</Label>
					<Select
						defaultValue={datasetFileInfo.encoding}
						onValueChange={(value: DatasetFileEncoding) => {
							setDatasetFileInfo(prev => {
								return {
									...prev,
									encoding: value
								}
							})
						}}
						disabled={!format.includes('csv')}
					>
						{/* <Select.Item value='windows-1251'>
							windows-1251
						</Select.Item>
						<Select.Item value='maccyrillic'>
							maccyrillic
						</Select.Item>
						<Select.Item value='koi8_r'>koi8_r</Select.Item>
						<Select.Item value='utf-16'>utf-16</Select.Item> */}
						<Select.Item value={DatasetFileEncoding.Utf_8}>
							utf-8
						</Select.Item>
					</Select>
				</div>
				{/*  */}
				<div className='col-span-8 flex flex-col gap-1'>
					<Label>{t('fields.separator')}</Label>
					<Input
						value={datasetFileInfo.separator}
						onChange={e => {
							setDatasetFileInfo(prev => {
								return {
									...prev,
									separator: e.target.value
								}
							})
						}}
						disabled={!format.includes('csv')}
					/>
				</div>
			</div>
			<Upload
				onChange={changeHandler}
				acceptedTypes={format}
				maxSize={maxSize}
				defaultValue={fileInfo ? [fileInfo] : []}
			/>
		</div>
	)
}

export { UploadFile }
