import React, { useState, useEffect } from 'react'
import { Col, Card, Container, Row, Button, Image } from "react-bootstrap"
import axios from "axios"
import ohuh from '../ohuh-sm.PNG';
import catchErrors from '../utils/catchErrors.js'
import { isAuthenticated } from '../utils/auth'
import * as Icon from 'react-bootstrap-icons';
import { Link } from 'react-router-dom'
import Paginations from '../Components/Paginations';
import _ from 'lodash';




function Bookmark() {
    const [error, setError] = useState('')
    const [bookmark, setBookmark] = useState([true, true, true, true])
    const [pagePlace, setpagePlace] = useState([])
    const [index, setIndex] = useState(1);
    const [endPage, setEndPage] = useState(1)
    const [bookmarkPlace, setBookmarkPlace] = useState([{ name: " ", address: " ", img: " " }])
    const user = isAuthenticated()

    async function getBookmark() {
        try {
            const bookmarkArr = [];
            const response = await axios.get(`/api/users/bookmark?ID=${user}`)
            setBookmarkPlace(response.data.bookmark)
        } catch (err) {
            catchErrors(err, setError(err))
            console.log("북마크에러", error)
        }
    }


    async function handleBookmark(index) {
        if (!bookmark[index]) {
            console.log(bookmarkPlace[index])
            try {
                const response = await axios.put(`/api/users/bookmark?ID=${user}&place=${bookmarkPlace[index]._id}`)
                alert(response.data, '북마크가 저장되었습니다.')
                const showArr = bookmark
                showArr[index] = true
                setBookmark(showArr)
                console.log("bookmark=", bookmark)
            } catch (error) {
                catchErrors(error, setError)
            }
        } else {
            try {
                const response = await axios.delete(`/api/users/bookmark?ID=${user}&place=${bookmarkPlace[index]._id}`)
                alert(response.data, '저장된 북마크가 삭제되었습니다.')
                getBookmark()
                console.log("bookmark=", bookmark)
            } catch (error) {
                catchErrors(error, setError)
            }
        }
    }

    const handlePage = (num) => {
        setIndex(num);
    }

    
    function paginate(items, pageNumber, itemNumber) {
        const startIndex = (pageNumber - 1) * itemNumber

        return _(items)
            .slice(startIndex)
            .take(itemNumber)
            .value();
    }

    useEffect(() => {
        getBookmark()
    }, [])


    useEffect(() => {
        setpagePlace(paginate(bookmarkPlace, index, 4))
        setEndPage(Math.ceil((bookmarkPlace.length / 4)))
    }, [bookmarkPlace, index])

    return (
        <Container>
            <Link to="/"><Image style={{ margin: "1%" }} src={ohuh} /></Link>
            <div class="d-flex align-items-center p-3 text-white bg-info rounded shadow-sm">
                <div >
                    <h1 class="h6 mb-0 text-white">북마크</h1>
                </div>
            </div>
            <Row className="d-flex flex-wrap">
                {console.log("#####################33", bookmarkPlace)}
                {pagePlace.map((place, index) => {
                    return (
                        <Col key={index} md={6} >
                            <Card border="info" style={{ margin: "2%" }}>

                                <Card.Header  style={{ margin: "0", fontSize: '200%', fontWeight: 'bold' }} >
                                    {user ?
                                        <Button
                                        style={{marginRight:"3%"}}
                                            variant={bookmark[index] ? "info" : "light"}
                                            onClick={() => handleBookmark(index, place)}>
                                            <Icon.BookmarkStarFill size={35} />
                                            {console.log("bookmark", bookmark)}
                                            {console.log("bookmark[index]", bookmark[index])}</Button> : null}
                                            {place.name}
                                </Card.Header>
                                <Card.Img variant="top" style={{ padding: "5%", width: "100%", height: "340px" }} src={place.img} />
                                <Card.Body >
                                    <Card.Text style={{ overflow: 'auto', fontSize: '150%', width: '100%', height: "65px" }} >
                                        {place.address} </Card.Text>
                                    <Link to={`/place?name=${place.name}&src=${place.img}&address=${place.address}`} >
                                        <Button variant="info"> {place.name} 자세히 살펴보기</Button>
                                    </Link>
                                </Card.Body>
                            </Card>
                        </Col>
                    )
                })}
            </Row>
            <Row className="mt-2 d-flex justify-content-center">
                <Paginations index={index} endPage={endPage} handlePage={handlePage}></Paginations>
            </Row>
        </Container >
    )
}

export default Bookmark


    // async function handleSubmit(e){
        //     setState(true);  //버튼이 눌려서 handlesubmit이될때 setState값이 true로 바뀐다
    //     try { //respons 서버에 post로 요청하여 데이터를 받아온다
    //         const response = await axios.post('/api/users/bookmark', page)
    //         setSuccess(true)
    //     } catch (error) {
    //         console.log(error)
    //         catchErrors(error, setError)
    //     }
    // }

    // useEffect(() => {
    //     getBookmark(user)
    // }, [user])