import React, { useState } from "react";
import { useLocation } from "react-router-dom";
import post from '../Post.tsx';
import toast, { Toaster } from "react-hot-toast";

function PostActions() {
    const [isMedia, setIsMedia] = useState(false);
    const [oldPost, setOldPost] = useState({ id: 0, type: 0, message: "", authorId: 0, date: new Date(0) });

    const search = useLocation().search
    const searchParams = new URLSearchParams(search)
    const toUpdate = searchParams.get("postId")
    const isUpdating = toUpdate ? true : false;

    const fetchOldData = async () => {
        if (isUpdating) {
            const oldPostContent = await fetch(`/api/v1/post/${toUpdate}`).then(response => response.json())
            if (oldPostContent.type == 1) {
                setIsMedia(true)
            }
            setOldPost(oldPostContent);
        }
    }
    window.onload =
        fetchOldData;

    const getFormData = () => {
        const formData = new FormData();
        const fileUploader = (document.getElementById("fileUploader") as HTMLInputElement);
        if (!fileUploader.files) {
            toast("Выберите файл для загрузки")
            return
        }
        formData.append('file', fileUploader.files![0]);
        return formData
    }


    const postNewPost = async (event) => {
        event.preventDefault();
        let headers = {};
        if (!isMedia) {
            headers = { "Content-Type": "application/json" }
        }
        await fetch(`/api/v1/post/${isUpdating ? `update/${toUpdate}` : "create"}`, {
            method: isUpdating ? "PUT" : "POST",
            headers,
            body: isMedia ? getFormData() : JSON.stringify({
                message: (document.getElementById("textInput") as HTMLInputElement).value
            })
        }).then(() => window.location.href = `..`);
    }

    const changePostType = (event) => {
        setIsMedia(event.target.value == "media")
    }
    return (
        <div className="container">
            <iframe style={{ display: "none" }}></iframe>
            <form onSubmit={postNewPost}>
                <div>
                    <input type="radio" id="plaintext" value="plaintext" name="isMedia" onChange={changePostType}></input>
                    <label htmlFor="plaintext">Текст</label>
                    <input type="radio" id="media" value="media" name="isMedia" onChange={changePostType}></input>
                    <label htmlFor="media">Медиа</label>
                </div>
                <div>
                    {oldPost.type == 1 ? (
                        post.PostTag(oldPost)
                    ) : (
                        <></>
                    )}
                </div>
                <div>
                    {isMedia ? (
                        <input type="file" className="beautiful_input" name="file" id="fileUploader" style={isMedia ? ({ display: "block" }) : ({ display: "none" })}></input>

                    ) : (
                        <input placeholder="Текст поста" type="text" className="beautiful_input" id="textInput" value={oldPost.message} style={isMedia ? ({ display: "none" }) : ({ display: "block" })}></input>

                    )}
                </div>
                <div>

                </div>
                <button type="submit" >{isUpdating ? "Обновить" : "Загрузить"}</button>
            </form>
            <Toaster />
        </div>
    );
}

export default PostActions;