import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { changeDescription } from '@/lib/api/ChangeDescription';

export default function AboutMe() {
    const maxLength = 250;

    const [about, setAbout] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const handleSave = async () => {
        if (loading) return;

        setLoading(true);
        setError(null);

        const res = await changeDescription(about);

        if (res.error) {
            setError(res.error.general);
        }

        setLoading(false);
    };

    return (
        <div className="flex flex-col flex-start gap-[10px] w-[600px] h-[284px]">
            <p className="font-medium text-light-violet ml-[20px]">ОБО МНЕ</p>

            <div className="flex flex-row p-[20px] w-[600px] h-[120px] border-solid border-[1px] rounded-[20px]">
                <textarea
                    value={about}
                    onChange={(e) => setAbout(e.target.value)}
                    maxLength={maxLength}
                    placeholder="Введите описание о себе"
                    className="w-full h-full resize-none outline-none bg-transparent"
                />

                <p
                    className={`ml-[10px] flex items-end ${
                        maxLength - about.length <= 10
                            ? 'text-red'
                            : 'text-light-violet'
                    }`}
                >
                    {maxLength - about.length}
                </p>
            </div>

            {error && <p className="text-red text-sm ml-[20px]">{error}</p>}

            <Button
                className="w-[105px]"
                onClick={handleSave}
                disabled={loading}
            >
                {loading ? 'Сохранение...' : 'Сменить'}
            </Button>
        </div>
    );
}
