import React, { useState,  useEffect, useCallback } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import Pagination from './Pagination';

const BoardList = () => {
  const [posts, setPosts] = useState([
    {"rnum":1,"hitCnt":18,"idx":5756,"title":"BatchTitle2","creaNm":"관리자","creaId":"2025-09-16"},
  ]);

  const [searchTerm, setSearchTerm] = useState('');//검색어 (검색바)
  const [submittedSearchTerm, setSubmittedSearchTerm] = useState(''); //검색어 (페이징 리스트)
  const [searchType, setSearchType] = useState('TITLE'); //검색 조건
  const [submittedSearchType, setSubmittedSearchType] = useState('TITLE');
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(100);

  //핸들링 이벤트의 실행주체
  const handleSearch = useCallback(() => {
    console.log(searchTerm);
    console.log(searchType);
    setSubmittedSearchTerm(searchTerm);
    setCurrentPage(1); // Reset to first page on new search
  }, [searchTerm, searchType]);

  //이벤트 감지기 (키이벤트)
  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {//엔터를 입력 했을때
      handleSearch();
    }
  };

  //서버 주소 처리
  const retriveBoard = useCallback((type, keyword) => {
    console.log(type, keyword);
    axios.get("<http://localhost:8080/RestBoard/board/api/list>"
      , {params: {
        type: type,
        keyword: keyword,
        page: currentPage,
      }})
      .then(response => {
        setPosts(response.data.list);
        setTotalPages(response.data.totalpage);  
        console.log(response);
      }).catch(error=>{
        console.log(error);
        // [추가] API 오류 시 대체 데이터 설정
         setPosts([{ "rnum": 1, "hitCnt": 0, "idx": 9999, "title": "[오류] 목록을 불러올 수 없습니다. 백엔드 확인 필요.", "creaNm": "시스템", "creaDtm": "2025-11-04" }]);
          setTotalPages(1);
      })
  }, [currentPage]);

  useEffect(()=>{
    retriveBoard(submittedSearchType, submittedSearchTerm);
  
  }, [submittedSearchType, submittedSearchTerm, currentPage, retriveBoard])

  // Change page
  const handlePageChange = (page) => setCurrentPage(page);

  return (
    <div className="container mt-4">     {/* Bootstrap 컨테이너 추가 */}
      <h2 className="mb-4">Board List</h2>

      {/* 검색 및 새 글쓰기 버튼 영역 */}
      <div className="row justify-content-between mb-3">
        <div className="col-md-auto">
            <Link to="/new" className="btn btn-primary">New Post</Link>
        </div>
        <div className="col-md-7">
          <div className="input-group">
            <select className="form-select" style={{ flex: '0 0 120px' }} value={searchType} onChange={e => setSearchType(e.target.value)}>
              <option value="TITLE">Title</option>
              <option value="CONTENTS">Content</option>
              <option value="ID">Author</option>  
            </select>
            <input
              type="text"
              className="form-control"
              placeholder={`Search by ${searchType}...`}
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              onKeyDown={e => handleKeyPress(e)}
            />
            <button className="btn btn-outline-secondary" type="button" onClick={e => handleSearch()}>Search</button>
          </div>
        </div>
      </div>
    

      {/* Post List */}
      <ul className="list-group mb-4">
        {/* 게시판 헤더 - 요청하신 글번호, 제목, 작성자, 작성일, 조회수 표시 */}
        <li className="list-group-item list-group-item-dark d-flex align-items-center fw-bold text-center">
            {/* 글번호 (rnum) - 10% */}
          <div className="col-1">글번호</div> 
          {/* 게시글 제목 (title) - 50% */}
          <div className="col-6 text-start">게시글 제목</div> 
          {/* 작성자 이름 (creaNm) - 15% */}
          <div className="col-2">작성자</div>
          {/* 작성일 (creaDtm) - 15% */}
          <div className="col-2">작성일</div>
          {/* 조회수 (hitCnt) - 10% */}
          <div className="col-1">조회수</div>
        </li>

        {/* 게시글 목록 */}
        {posts.map(post => (
          <li key={post.idx} className="list-group-item d-flex align-items-center text-center">
               {/* 글번호 (rnum) */}
            <div className="col-1">{post.rnum}</div>
            
            {/* 게시글 제목 (title) - text-start로 왼쪽 정렬 */}
            <div className="col-6 text-start text-truncate">
              <Link to={`/post/${post.idx}`} className="text-decoration-none">{post.title}</Link>
            </div>
            
            {/* 작성자 이름 (creaNm) */}
            <div className="col-2 text-truncate">{post.creaNm}</div>
            
            {/* 작성일 (creaDtm) - 작은 폰트로 표시 */}
            <div className="col-2 small text-truncate">{post.creaDtm}</div>

            {/* 작성일 (creaIdm) - 작은 폰트로 표시 */}
            {/* <div className="col-3 small text-truncate">{post.creaId}</div>  */}
            
            {/* 조회수 (hitCnt) */}
            <div className="col-1">{post.hitCnt}</div>

            {/*<Link to={`/post/${post.idx}`}>{post.title}</Link>
            <span>{post.creaNm}</span>  */}
          </li>
        ))}

        {/* 게시글이 없는 경우 */}
        {posts.length === 0 && (
          <li className="list-group-item text-center text-muted">
            게시글이 없습니다.
          </li>
        )}
      </ul>

      {/* Pagination */}      
      <Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={handlePageChange}  />
    </div>
  );
};

export default BoardList;