import React, { useState, useEffect } from 'react'
import Menu from '../Components/Menu';
import { Image, Button, Container, Form, Row, Col } from 'react-bootstrap';
import { BrowserRouter as Link } from 'react-router-dom';
import axios from 'axios'
import catchErrors from '../utils/catchErrors'
import { isAuthenticated } from '../utils/auth';

const INIT_USER = {
    username: '',
    email: '',
    nickname: '',
    imageUrl: []
}

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

    const [hidden, setHidden] = useState(true)
    const [changed, setChanged] = useState(false)

    const userId = isAuthenticated()

    async function getProfile(userId) {
        try {
            const response = await axios.get(`/users/${userId}`)
            setUser(response.data)
        } catch (error) {
            catchErrors(error, setError)
        }
    }

    function handleSubmitHidVis(e) {
        e.preventDefault()
        if (hidden) {
            setHidden(false)
        } else {
            setHidden(true)
        }
    }
    function handleChange(e) {
        const { name, value, files } = e.target
        if (files) {
            setUser({ ...user, [name]: files })
        } else {
            setUser({ ...user, [name]: value })
        }
        setChanged(true)
    }
    async function handleSubmit(e) {
        e.preventDefault()
        if (changed) {
            const formData = new FormData()
            if (user.imageUrl) {
                formData.append('imageUrl', user.imageUrl[0])
            }
            formData.append('newNickname', user.nickname)   //얘네는 req.body로 들어감
            try {
                if (userId) {
                    await axios.put(`/users/${userId}`, formData)
                    alert('저장되었습니다.')
                    window.location.reload()
                }
            } catch (error) {
                catchErrors(error, setError)
            }
        }
        else {
            alert('변경사항이 없습니다.')
        }
    }

    useEffect(() => {
        getProfile(userId)
    }, [userId])

    return (
        <>
            <Menu />
            <Container>
                <Row >
                    <Col sm={4}>
                        <Row className='justify-content-center'>
                            <Image src={user.profileimg && `/images/${user.profileimg}`} style={{ width: "300px", height: "300px" }} roundedCircle />
                        </Row>
                        <Row className='ml-3 mt-3 justify-content-center'>
                            <Form className="d-flex">
                                <Form.Group>
                                    <Form.Label>프로필 사진 변경</Form.Label>
                                    <Form.Control type='file' name='imageUrl' onChange={handleChange} accept='image/*' />
                                </Form.Group>
                            </Form>
                        </Row>
                    </Col>
                    <Col sm={8}>
                        <Row className='m-5 justify-content-center'>
                            <h2>{user.username}님의 프로필 정보</h2>
                        </Row>
                        <Row className="m-3 justify-content-flex-start" style={{ fontWeight: "bold", fontSize: "large" }}>
                            <Col xs={3}>이름 :</Col>
                            <Col xs={6}>{user.username}</Col>
                        </Row>
                        <Row className="m-3 justify-content-flex-start" id="nickname" style={{ fontWeight: "bold", fontSize: "large" }}>
                            <Col xs={3}>별명 :</Col>
                            <Col xs={6} hidden={!hidden}>
                                {user.nickname}
                            </Col>
                            <Col xs={6} hidden={hidden}>
                                <Form>
                                    <Form.Control defaultValue={user.nickname} name='nickname' style={{ width: "110%" }} onChange={handleChange} />
                                </Form>
                            </Col>
                            <Col xs={3}>
                                <Form className="d-flex" onSubmit={handleSubmitHidVis}>
                                    <Button className="ml-3 d-flex justify-content-end" variant="outline" style={{ border: "3px solid", borderColor: "#b49dc9", background: 'white' }} size="sm" type='submit'>수정</Button>
                                </Form>
                            </Col>
                        </Row>
                        <Row className="m-3" style={{ fontWeight: "bold", fontSize: "large" }}>
                            <Col xs={3}>이메일 : </Col>
                            <Col xs={6}>{user.email}</Col>
                        </Row>
                        <Row className='m-3 justify-content-center'>
                            <Form onSubmit={handleSubmit}>
                                <Button size="sm" className="mr-4" type='submit' variant="outline" style={{ border: "3px solid", borderColor: "#9174ad", background: 'white' }}>저장</Button>
                                <Link to='/'>
                                    <Button size="sm" className="ml-4" variant="outline" style={{ border: "3px solid", borderColor: "#9174ad", background: 'white' }}>홈 화면으로</Button>
                                </Link>
                            </Form>
                        </Row>
                    </Col>
                </Row>
            </Container>
        </>
    )
}

export default ProfilePage
