import { useNavigate } from 'react-router-dom';

import { UserContext } from '../Context.js';
import Article from '../components/Article.js';
import React, { useEffect, useState, useContext } from 'react';

import axios from 'axios';
axios.defaults.withCredentials = true;

function Button({ history, children }) {
  const navigate = useNavigate();
  return (
    <button style={{ width: '40px', height: '30px' }} onClick={() => { navigate('/search'); }}>
      {children}
    </button>
  );
}

function Main() {
  const userContext = useContext(UserContext);
  const [articleList, setArticleList] = useState([]);
  let listItem = [];
  listItem = articleList.map((article) => {
    return (
      <Article
        key={article._id}
        data={article}
      ></Article>
    )
  }
  )
  useEffect(() => {
    requestSortArticle("time")
      .then((response) => {
        console.log(response)
        setArticleList(response.data)
      })
  }, []);

  const handleSortChange = (event) => {
    requestSortArticle(event.target.value)
      .then((response) => {
        console.log(response)
        setArticleList(response.data)
      })
  };

  return (
    <div className="App">
      <h1>모두의 食道樂</h1>
      <div className="introduction">
        가보고 싶은 식당을 찾아보고, 가본 식당을 기록해보세요!
      </div>
      <div style={{ display: 'flex' }}>
        <select id="addInputPrior" defaultValue={"time"} onChange={handleSortChange}>
          <option value="time">최신순</option>
          <option value="like">인기순</option>
        </select>
      </div>
      {listItem}
    </div>);
}

async function requestLoadArticle() {
  const response = await axios({
    url: 'http://localhost:8080/article', // 통신할 웹문서
    method: 'get', // 통신할 방식
  });
  return response;
}

async function requestSortArticle(crit) {
  const response = await axios({
    url: `http://localhost:8080/article/sort/${crit}`, // 통신할 웹문서
    method: 'get', // 통신할 방식
  });
  return response;
}

export default Main;