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


function Search(props) {
    const [state, setState] = useState(false);
    const [index, setIndex] = useState(1);
    const [search, setSearch] = useState(queryString.parse(props.location.search).keyword);
    const [bookmark, setBookmark] = useState([])
    const [association, setAssociation] = useState([{ name: " ", address: " ", img: " " }])
    const [pagePlace, setPagePlace] = useState([{ name: " ", address: " ", img: " " }, { name: " ", address: " ", img: " " }])
    const [endPage, setEndPage] = useState(1)
    const [error, setError] = useState('')

    const user = isAuthenticated()

    async function getBookmark() {
        try {
            const response = await axios.get(`/api/users/bookmark?ID=${user}`)
            setBookmark(response.data.bookmark)
        } catch (error) {
            catchErrors(error, setError(error))
        }
    }

    const getAssociation = () => {
        axios.get(`/api/search/association?keyword=${search}`)
            .then(res => {
                setAssociation(res.data)
            })
            .catch(err => {
                console.log("search.associations 에러 발생", err)
            })
    }

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

    useEffect(() => {
        getAssociation()
        getBookmark()
        if (state) {
            props.history.push('/search?keyword=' + search)
            setState(false)
        }
    }, [state]);

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

    const handleChange = (e) => {
        setSearch(e.target.value);
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        setState(true)
        setIndex(1)
        setBookmark([false, false, false, false])
    }

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

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

    async function handlebookmark(index, place) {
        const include = bookmark.findIndex(i => i.name === place.name) !== -1
        if (!include) {
            try {
                const response = await axios.put(`/api/users/bookmark?ID=${user}&place=${pagePlace[index]._id}`)
                alert(response.data, '북마크가 저장되었습니다.')
                getBookmark()
            } catch (error) {
                catchErrors(error, setError)
            }
        } else {
            try {
                const response = await axios.delete(`/api/users/bookmark?ID=${user}&place=${pagePlace[index]._id}`)
                alert(response.data, '저장된 북마크가 삭제되었습니다.')
                getBookmark()
            } catch (error) {
                catchErrors(error, setError)
            }
        }
    }
    return (
        <Container >
            <Link to="/"><Image src={ohuh} /></Link>
            <Row className="mb-2" className="d-flex justify-content-center">
                <Form style={{ width: "90vw" }} onSubmit={handleSubmit}>
                    <InputGroup size="lg">
                        <FormControl
                            placeholder="검색어를 입력하세요."
                            value={search}
                            aria-label="Large"
                            aria-describedby="inputGroup-sizing-sm"
                            onChange={handleChange}
                        />
                        <InputGroup.Append>
                            <Button type="submit" variant="info" >검색</Button>
                        </InputGroup.Append>
                    </InputGroup>
                </Form>
            </Row>
            <Row>

                {pagePlace.map((place, index) => {
                    return (
                        <Col key={index} md={6} >
                            <Card border="info" style={{ margin: "2%" }}>
                                <Row>
                                    <Card.Header style={{ margin: "0", marginLeft: "3%", marginRight: "3%", fontSize: '200%', fontWeight: 'bold', width: "100vw" }} >
                                        {user ?
                                            <Button
                                                style={{ marginRight: "3%" }}
                                                variant={bookmark.findIndex(i => i.name === place.name) !== -1 ? "info" : "light"}
                                                onClick={() => handlebookmark(index, place)}>
                                                <Icon.BookmarkStarFill size={35} />
                                            </Button> : null}
                                        {place.name}
                                    </Card.Header>
                                </Row>
                                <Card.Img variant="top" style={{ padding: "5%", width: "100%", height: "340px" }} src={place.img} />
                                <Card.Body>
                                    <Card.Text style={{ overflow: 'auto', fontSize: '25px', 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 Search;
