import React, {useEffect, useRef, useState} from 'react';
import './textarea.scss'
import FormError from "../FormError/FormError";

type TextAreaProps = {

    value?: string
    onChange: (s: string) => void
    required?: boolean
    type?: 'text' | 'email'
    theme?: 'default' |  'user-form-field'
    id?: string
    readOnly?: boolean
    inputMode?: 'text' | 'numeric'
    placeholder?: string
    hasError?: any
    maxLength?: number
    validation?: any
    isForGate?: boolean
    maxRows?: number;
}

const CustomTextArea = (
    {
        value,
        onChange,
        required = false,
        theme = 'default',
        id = 'fieldId',
        readOnly = false,
        inputMode = 'text',
        placeholder = 'παρακαλώ συμπληρώστε',
        maxRows = 2,
        hasError = '',
        maxLength,
        validation
    }: TextAreaProps) => {
    const textAreaRef = useRef<HTMLTextAreaElement>(null);

    useEffect(() => {
        const element = textAreaRef.current;
        if (element) {
            element.style.overflow = "hidden";
            element.style.height = "50px";
        }
    }, []);
    const handleInput = (event: React.FormEvent<HTMLTextAreaElement>) => {
        const element = event.currentTarget;
        if (maxRows !== undefined) {
            const rows = element.value.split("\n");
            let exceedsMaxRows = false;

            for (let i = 0; i < rows.length; i++) {
                if (rows[i].length > 86) {
                    exceedsMaxRows = true;
                    break;
                }
            }

            if (exceedsMaxRows || rows.length > maxRows) {
                element.style.overflow = "auto";
                element.style.height = "75px";
            } else {
                element.style.overflow = "hidden";
                element.style.height = "50px";
            }

        }
    };


    //@ts-ignore
    return (

        <>
            {hasError &&  <FormError>{hasError}</FormError>}
            <textarea
                rows={1}
                ref={textAreaRef}
                className={`text-area ${theme} ${readOnly && 'disable'} ${hasError && 'hasError'}`}
                readOnly={readOnly}
                id={id}
                required={required}
                inputMode={inputMode}
                placeholder={placeholder}
                maxLength={maxLength}
                value={value}
                onChange={(e) => onChange(e.target.value)}
                onBlur={(e) => validation && validation(id, e.target.value)}
                onInput={handleInput}
            >
            </textarea>


        </>);
}

export default CustomTextArea;