import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import Menu from '../Components/Menu';
import { Image, Button, Container, Form, FormControl, Navbar, Nav, Row, Col, Dropdown, Carousel } 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'
import img1 from './img_1.png'
import img2 from './img_2.png'
import img3 from './img_3.jpg'
import DropdownItem from 'react-bootstrap/esm/DropdownItem';


// const INIT_USER = {
//     username: '',
//     email: '',
//     nickname: ''
// }

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

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


    async function getLoginedUser() { //email로 db에서 찾아오기 ㅇㅇㅇㅇㅇ
        const userid = localStorage.getItem('user')
        const response = await axios.post(`/users/${userid}`, { 'email': userid })
        setUser(response.data)
    }

    function handleSubmit(e) {
        e.preventDefault()
        if (hidden) {
            setHidden(false)
        } else {
            setHidden(true)
        }
        console.log(document.cookie)
    }
    function handleChange(e) {
        setUser({ ...user, 'nickname': e.target.value })
    }
    async function handleNicksave() {
        const userid = localStorage.getItem('user')
        await axios.put(`/users/${userid}`, 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);
            };
        }
    }
    useEffect(() => {
        if (localStorage.getItem('user')) { //id뿐만아니라 토큰같은거를 확인 못하나 + 이런식으로 확인해도 되는것도 맞나
            getLoginedUser()
        }
        else {
            alert("로그인 후 이용하세요")
            window.location.href = '/login'
        }
    }, [])

    return (
        <div>
            <Menu />
            <Container>
                <Row><h1>ProfilePage</h1></Row>
                <Row><h2>{user.username}님 환영합니다 !</h2></Row>
            </Container>
            <Container className="mt-5 shadow w-75">
                <Row>
                    <Col sm={4}>
                        <Row>
                            <div className="d-flex justify-content-center mb-3" id="defaultImg">
                                <Image src={userimg} width="300px" roundedCircle />
                            </div>
                        </Row>
                        <Row>
                            <Form className="d-flex justify-content-center">
                                <Form.Group>
                                    <div id="image_container"></div>
                                    <Form.File label="프로필 사진 변경" accept="image/*" onChange={setThumbnail} />
                                </Form.Group>
                            </Form>
                        </Row>
                        <Row className="d-flex justify-content-center">
                            <Dropdown>
                                <Dropdown.Toggle variant='success' id='dropdown-basic'>
                                    프로필 사진 선택
                                </Dropdown.Toggle>
                                <Dropdown.Menu>
                                    <Dropdown.Item as='button'>홈으로</Dropdown.Item>
                                    <Dropdown.Item href='/'>라이언</Dropdown.Item>
                                    <Dropdown.Item href='/'>어피치</Dropdown.Item>
                                </Dropdown.Menu>
                            </Dropdown>
                        </Row>
                    </Col>
                    <Col sm={8}>

                        <Row className="m-3 justify-content-flex-start" style={{ fontWeight: "bold", fontSize: "x-large" }}>
                            <Col sm={2.5}>이름 :</Col>
                            <Col sm={8}>{user.username}</Col>
                        </Row>
                        <Row className="m-3 justify-content-flex-start" id="nickname">
                            <Form className="d-flex" onSubmit={handleSubmit} style={{ fontWeight: "bold", fontSize: "x-large" }}>

                                <Row>
                                    <Col>별명 :</Col>
                                    <Col hidden={!hidden}>
                                        {user.nickname}
                                    </Col>
                                    <Col hidden={hidden}>
                                        <Form.Control defaultValue={user.nickname} style={{width : "110%"}} onChange={handleChange} />
                                    </Col>
                                    <Col>
                                        <Button className="ml-3 d-flex justify-content-end" variant="outline-primary" size="sm" type='submit'>수정</Button>
                                    </Col>
                                </Row>
                            </Form>

                        </Row>
                        <Row className="m-3" style={{ fontWeight: "bold", fontSize: "x-large" }}>
                            <Col sm={2.5}>이메일 : </Col>
                            <Col sm={8}>{user.email}</Col>
                        </Row>
                        <Row className='justify-content-center'>
                            <Form>
                                <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>
                            </Form>
                        </Row>
                    </Col>
                </Row>
            </Container>




            <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.username}님 환영합니다 !</h4>

                    <div className="d-flex justify-content-center mb-3" id="defaultImg">
                        <Image src={userimg} width="300px" roundedCircle />
                    </div>
                    <Row 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>
                    </Row>
                    <Row className="d-flex justify-content-center">
                        <Dropdown>
                            <Dropdown.Toggle variant='success' id='dropdown-basic'>
                                프로필 사진 선택
                                </Dropdown.Toggle>
                            <Dropdown.Menu>
                                <Dropdown.Item as='button'>홈으로</Dropdown.Item>
                                <Dropdown.Item href='/'>라이언</Dropdown.Item>
                                <Dropdown.Item href='/'>어피치</Dropdown.Item>
                            </Dropdown.Menu>
                        </Dropdown>
                    </Row>
                    {/* <Carousel className="d-flex justify-content-center" style={{ width: "300px", height: "300px" }}>
                        <Carousel.Item className="d-flex justify-content-center">
                            <Image
                                className="d-block w-100"
                                src={img1}
                            />
                            <Carousel.Caption>
                                <p style={{color : 'black'}}>펭수입니다.</p>
                            </Carousel.Caption>
                        </Carousel.Item>
                        <Carousel.Item>
                            <Image
                                className="d-block w-100"
                                src={img2}
                            />
                            <Carousel.Caption>
                                <p>라이언입니다.</p>
                            </Carousel.Caption>
                        </Carousel.Item>
                        <Carousel.Item>
                            <Image
                                className="d-block w-100"
                                src={img3}
                            />
                            <Carousel.Caption>
                                <p>어피치 입니다.</p>
                            </Carousel.Caption>
                        </Carousel.Item>
                    </Carousel> */}
                    <div className="text-center">
                        <div className="m-3" style={{ fontWeight: "bold", fontSize: "x-large" }}>이름 : {user.username}</div>
                        <div className="m-3" id="nickname">
                            <Form className="d-flex justify-content-center" onSubmit={handleSubmit} style={{ fontWeight: "bold", fontSize: "x-large" }}>
                                별명 :
                                <div hidden={!hidden}>
                                    {user.nickname}
                                </div>
                                <Form.Control defaultValue={user.nickname} style={{ width: "40%" }} size="sm" onChange={handleChange} hidden={hidden} />
                                <Button className="ml-3" variant="outline-primary" size="sm" type='submit'>수정</Button>
                            </Form>

                        </div>
                        <div className="m-3" style={{ fontWeight: "bold", fontSize: "x-large" }}>이메일 : {user.email}</div>
                    </div>
                    <div className="text-center m-5">
                        <Form>
                            <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>
                        </Form>
                    </div>
                </div>
            </Container>

        </div>
    )
}

export default ProfilePage
