import {ChangeEventHandler, CSSProperties, FC, FocusEventHandler, forwardRef, PropsWithoutRef} from 'react';
import styled from 'styled-components'

const Base = styled('div')({
	borderRadius: '0.25rem',
	overflow: 'hidden',
	position: 'relative',
	backgroundColor: 'var(--color-bg, white)',
	'::before': {
		content: "''",
		borderWidth: 1,
		borderStyle: 'solid',
		position: 'absolute',
		top: 0,
		left: 0,
		width: '100%',
		height: '100%',
		borderRadius: 'inherit',
		boxSizing: 'border-box',
		opacity: 0.5,
	},
})

const ClickArea = styled('label')({
	position: 'relative',
	height: '100%',
})

const Label = styled('span')({
	position: 'absolute',
	left: -999999,
})

const Input = styled('textarea')({
	display: 'block',
	width: '100%',
	minHeight: '3rem',
	margin: 0,
	padding: '1rem 1rem',
	boxSizing: 'border-box',
	font: 'inherit',
	border: 0,
	backgroundColor: 'transparent',
	color: 'inherit',
	outline: 0,
})

type Props = {
	label: string,
	name: string,
	className?: string,
	block?: boolean,
	placeholder?: string,
	defaultValue?: string | number | readonly string[],
	readOnly?: boolean,
	onChange?: ChangeEventHandler<HTMLTextAreaElement>,
	onBlur?: FocusEventHandler<HTMLTextAreaElement>,
	style?: CSSProperties,
}

const TextArea = forwardRef<HTMLTextAreaElement, PropsWithoutRef<Props>>(({
	label,
	className,
	block,
	style = {},
	...etcProps
}, ref) => {
	return (
		<Base
			className={className}
			style={{
				display: block ? 'block' : 'inline-block',
				width: block ? '100%' : undefined,
			}}
		>
			<ClickArea>
				<Label>
					{label}
				</Label>
				<Input
					{...etcProps}
					ref={ref}
					style={{
						...style,
						resize: block ? 'vertical' : undefined,
					}}
				/>
			</ClickArea>
		</Base>
	)
})

export default TextArea
