import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import Menu from '../Components/Menu';
import { Image, Button, Container, Form, FormControl, Navbar, Nav } from 'react-bootstrap';
import { BrowserRouter as Router, Route, Redirect, Switch, Link } from 'react-router-dom';
import axios from 'axios'

import userdefault from './KakaoTalk_20201230_153151693.png'

//localStorage에 아이디? 가있는걸로 db에서 그 사람꺼 찾은(findOne 이런걸로) 다음에 닉네임도 불러오고 여기서 수정할 수 있는 기능을 만들자!


////////////////////////////////////////////////////////////////////////////////
// async function sending() {
//     const info = await fetch(`/api/users/signup`, {
//         method: "POST",
//         headers: {
//             "Content-type": 'application/json'
//         },
//         body: JSON.stringify({
//             name: userName,
//             email: userEmail,
//             password: "123123123",
//             nickname: userNickname
//         })
//     })
//     const data = await info.json()
//     console.log(data)
// }

////////////////////////////////////////////////////////////////////////////////

const INIT_USER = {
    name: '',
    email: '',
    nickname: ''
}

function ProfilePage() {
    const [user, setUser] = useState(INIT_USER)

    const [defaultImg, setDefaultImg] = useState(true)
    const [hidden, setHidden] = useState(true)

    function setlocal() {
        localStorage.setItem('_id', '5ff77d56da609732c001b392')
    }
    async function loginedinfo() {
        const userid = localStorage.getItem('_id')
        const response = await axios.post(`/api/users/${userid}`, user)
        setUser(response.data[1])
        console.log(user)
    }

    
    async function getInfo() {  //db에서 로그인 정보 가져옴
        const response = await axios.get('/api/users')
        console.log(response.data)
        setUser(response.data[1])
        console.log(user)
    }
    async function makeLogin() {    //로그인 상태로 만들어줌
        const info = await axios.get('/api/users')
        console.log('info', info.data)
        setUser(info.data[1])

        await axios.post(`/api/users/`, user)
        localStorage.setItem('loginStatus', 'true')
        localStorage.setItem('_id', user._id)
        console.log(user)
    }

    async function authinfo() { //id로 db에서 찾아오기
        const userid = { '_id': localStorage.getItem('_id') }
        const response = await axios.post(`/api/users/${userid._id}`, userid)
        console.log(response.data)
        setUser(response.data)
    }

    //@@그다음에 찾아온걸로 다시 띄우기
    //@@닉네임 수정하기

    function handleEditnick() {
        if (hidden) {
            setHidden(false)
        } else {
            setUser({ ...user, 'nickname': document.getElementById("inputNick").value })
            setHidden(true)
        }
    }
    async function handleNicksave(){
        const userid = { '_id': localStorage.getItem('_id') }
        await axios.put(`/api/users/${userid._id}`, user)

    }

    function setThumbnail(event) {  //불러온 사진 <div id='image_container'>에 띄우기
        let reader = new FileReader();

        reader.onload = function (event) {
            let img = document.createElement("img");
            img.setAttribute("src", event.target.result);
            img.setAttribute("id", "profileImg")
            img.setAttribute("style", 'height:300px; width:300px')
            img.setAttribute("class", "mb-3")
            // img.setAttribute("class","d-flex justify-content-center mb-3")
            document.querySelector("div#image_container").appendChild(img);
        };
        reader.readAsDataURL(event.target.files[0]);

        if (defaultImg) {   //첫 이미지 업로드(default이미지 지우고 유저가 올린걸로 업로드)
            let del = document.getElementById("defaultImg")
            del.remove()
            setDefaultImg(false)
        }
        else {  //기존에 올렸던 사진 지우고 재선택한 사진 업로드
            let del2 = document.getElementById('profileImg')
            del2.remove()

            reader.onload = function (event) {
                let img = document.createElement("img");
                img.setAttribute("src", event.target.result);
                img.setAttribute("id", "profileImg")
                img.setAttribute("style", 'height:300px; width:300px')
                document.querySelector("div#image_container").appendChild(img);
            };
        }
    }




    return (
        <div>
            <Menu />
            <Button onClick={setlocal}>로컬에 추가</Button>
            <Button onClick={loginedinfo}>로그인된 정보 불러오기</Button>
            <Button onClick={getInfo}>불러오기</Button>
            <Button onClick={makeLogin}>로그인 상태로 만들기</Button>
            <Button onClick={authinfo}>로그인 유저 불러오기</Button>
            {/* <Button onClick={sending}>보내기</Button> */}

            <Container className="d-flex justify-content-center">
                <div className="mt-5 shadow w-75">
                    <h1 className="text-center mt-4 ml-5 mr-5 mb-3">Profile Page</h1>
                    <h4 className="text-center mb-5">{user.name}님 환영합니다 !</h4>

                    <div className="d-flex justify-content-center mb-3" id="defaultImg">
                        <Image src={userdefault} width="300px" roundedCircle />
                    </div>
                    <div className="d-flex justify-content-center">
                        <Form className="d-flex justify-content-center">
                            <Form.Group>
                                <div id="image_container"></div>
                                <Form.File label="프로필 사진 변경" accept="image/*" onChange={setThumbnail} />
                            </Form.Group>
                        </Form>
                    </div>

                    <div className="text-center">
                        <div className="m-3" style={{ fontWeight: "bold", fontSize: "x-large" }}>이름 : {user.name}</div>
                        <div className="m-3" id="nickname">
                            <Form className="d-flex justify-content-center" style={{ fontWeight: "bold", fontSize: "x-large" }}>
                                별명 :
                                <div id="mainNick" hidden={!hidden}>
                                    {user.nickname}
                                </div>
                                <Form.Control id="inputNick" type="name" defaultValue={user.nickname} style={{ width: "40%" }} size="sm" hidden={hidden} />
                                <Button className="ml-3" variant="outline-primary" size="sm" onClick={handleEditnick}>수정</Button>
                            </Form>

                        </div>
                        <div className="m-3" style={{ fontWeight: "bold", fontSize: "x-large" }}>이메일 : {user.email}</div>
                    </div>
                    <div className="text-center m-5">
                        <span>
                            <Button variant="outline-success" size="sm" className="mr-4" onClick={handleNicksave}>저장</Button>
                            <Link to='/'>
                                <Button variant="outline-success" size="sm" className="ml-4" >홈 화면으로</Button>
                            </Link>
                        </span>
                    </div>
                </div>
            </Container>

        </div>
    )
}

export default ProfilePage
