import React, {useState, useRef, useEffect} from "react";
import styles from './SurveyInfo.module.css'
import AddDescripImg from '../../assets/add_circle.svg?react';
import TextareaAutosize from 'react-textarea-autosize';
import {useLocation} from "react-router-dom";


interface SurveyInfoProps {
    titleSurvey: string;
    descriptionSurvey: string;
    setDescriptionSurvey?: (text: string) => void;
    setTitleSurvey?: (text: string) => void;
    createdAt?: Date;
}

const SurveyInfo: React.FC<SurveyInfoProps> = ({titleSurvey, setDescriptionSurvey, descriptionSurvey, setTitleSurvey, createdAt = new Date()}) => {
    const [showDescriptionField, setShowDescriptionField] = useState(false);
    const [showNewTitleField, setShowNewTitleField] = useState(false);
    const titleTextareaRef = useRef<HTMLTextAreaElement>(null);
    const descriptionTextareaRef = useRef<HTMLTextAreaElement>(null);

    const location = useLocation();
    const isCompleteSurveyActive = location.pathname === '/complete-survey';
    const isSurveyViewPage = location.pathname.startsWith('/survey/') &&
        !location.pathname.startsWith('/survey/create');

    const handleDescriptionChange = (descripEvent: React.ChangeEvent<HTMLTextAreaElement>) => {
        setDescriptionSurvey?.(descripEvent.target.value);
    };

    const handleNewTitleChange = (titleEvent: React.ChangeEvent<HTMLTextAreaElement>) => {
        setTitleSurvey?.(titleEvent.target.value);
    };

    useEffect(() => {
        if (showNewTitleField && titleTextareaRef.current) {
            titleTextareaRef.current.focus();
        }
    }, [showNewTitleField]);

    useEffect(() => {
        if (showDescriptionField && descriptionTextareaRef.current) {
            descriptionTextareaRef.current.focus();
        }
    }, [showDescriptionField]);


    const handleAddNewTitleClick = () => {
        setShowNewTitleField(true);
    }

    const handleAddDescriptionClick = () => {
        setShowDescriptionField(true);
    }

    const handleTitleKeyDown = (titleClickEnter: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if (titleClickEnter.key === 'Enter'){
            titleClickEnter.preventDefault();
            setShowNewTitleField(false);
        }
    }

    const handleDescriptionKeyDown = (descripClickEnter: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if (descripClickEnter.key === 'Enter'){
            descripClickEnter.preventDefault();
            setShowDescriptionField(false);
        }
    }

    const handleParagraphClick = () => {
        setShowDescriptionField(true);
    }


    const handleTitleBlur = () => {
        setShowNewTitleField(false);
    };

    const handleDescriptionBlur = () => {
        setShowDescriptionField(false);
    };

    const addDate = () => {
        const year = createdAt.getFullYear();
        const month = String(createdAt.getMonth() + 1).padStart(2, '0');
        const day = String(createdAt.getDate()).padStart(2, '0');
        return `${day}/${month}/${year}`;
    }

    const renderTitle = () => {
        if (isCompleteSurveyActive) {
            return (
                <button className={styles.titleSurvey}>
                    <h1>{titleSurvey || 'Название опроса'}</h1>
                </button>
            )
        }

        if (showNewTitleField) {
            return (
                <h1 className={styles.titleSurvey}>
                    <TextareaAutosize
                        className={styles.textareaTitle}
                        ref={titleTextareaRef}
                        value={titleSurvey === 'Название опроса' ? '' : titleSurvey}
                        placeholder={'Название опроса'}
                        onChange={handleNewTitleChange}
                        onKeyDown={handleTitleKeyDown}
                        onBlur={handleTitleBlur}
                    />
                </h1>
            );
        }

        return (
            <button className={styles.titleSurvey} onClick={handleAddNewTitleClick}>
                <h1>{titleSurvey || 'Название опроса'}</h1>
            </button>
        );
    };

    const renderDescription = () => {
        if (isCompleteSurveyActive) {
            return descriptionSurvey ? (
                <p className={styles.desc}>{descriptionSurvey}</p>
            ) : 'Описание';
        }

        if (descriptionSurvey && !showDescriptionField) {
            return (
                <button className={styles.description} onClick={handleParagraphClick}>
                    {descriptionSurvey}
                </button>
            );
        } else if (showDescriptionField) {
            return (
                <div className={styles.descriptionWrapper}>
                    <TextareaAutosize
                        ref={descriptionTextareaRef}
                        className={styles.textareaDescrip}
                        value={descriptionSurvey}
                        placeholder={'Добавить описание'}
                        onChange={handleDescriptionChange}
                        onKeyDown={handleDescriptionKeyDown}
                        onBlur={handleDescriptionBlur}
                        rows={1}
                    />
                </div>
            );
        }
        else {
            return (
                <button
                    className={styles.descripButton}
                    onClick={handleAddDescriptionClick}
                >
                    <span className={styles.textButton}>Добавить описание</span>
                    <AddDescripImg className={styles.descButtonImg}/>
                </button>
            );
        }
    };

    return (
        <div className={styles.blockInfo}>
            <div className={styles.info}>
                {renderTitle()}
                {renderDescription()}

                {(isSurveyViewPage || isCompleteSurveyActive) && createdAt && (
                    <p className={styles.createdAt}>Дата создания: {addDate()}</p>
                )}
            </div>
        </div>
    );

};

export default SurveyInfo;