"use client"
import PageBreadcrumb from "@/components/common/PageBreadCrumb2";
import ComponentCard from '@/components/common/ComponentCard2';
import CtTable1 from '@/components/tables/CtTable1';
import Button from '@/components/ui/button/Button2';
import { DocsIcon, FileIcon, PlusIcon } from "@/icons";
import WithLabel from '@/components/form/WithLabel';
import Input from '@/components/form/input/InputField2';
import DatePicker from '@/components/form/date-picker2';

import React from "react";
import { useEffect, useState } from 'react';
import { useRouter } from "next/navigation";
import api, { convertDateTime3 } from '@/lib/_AG';

import { useModal } from "@/hooks/useModal";
import AddModifyNoticeModal, {NoticeModalProps} from './AddModifyNoticeModal';
import { useMultiState } from "@/hooks/useMultiState";


const SEARCH_LABEL_WIDTH = 24;
const COUNT_PER_PAGE = 10;
const PAGE_NUM_COUNT = 5;


export default function Notice() {
  const router = useRouter();

  const [ tableData, setTableData ] = useState<any[]>([]);
  const [ tableOffset, setTableOffset ] = useState<number>(0);
  const [ tableTotalCount, setTableTotalCount ] = useState<number>(0);

  // search fields
  const [ title, setTitle ] = useState<string>("");
  const [ content, setContent ] = useState<string>("");
  const [ date_start, setDateStart ] = useState<string>("");
  const [ date_end, setDateEnd ] = useState<string>("");
  const [ uid1, setUid1 ] = useState<string>("");
  //

  // modal
  const { isOpen, openModal, closeModal } = useModal();
  const modalData = useMultiState<NoticeModalProps>({isModify: false, user_id: "", user_pw: "", nick_name: "", email: "", gid: "", state: ""});


  const fetchAccountList = () => {
    api.post('/api/get-all-account.do').then((resp) => {
        console.log(resp);

        if (resp.data.errCode === 0) {
          setTableData(resp.data.result.list);
        } 
        else {
          alert("조회 실패 :" + resp.data.errCode);
        }
     })
     .catch((err) => console.error(err));
    };


    

  // function part
  function reqNoticeList() {
    const params = {
      offset: tableOffset,
      limit: COUNT_PER_PAGE,
      title: title,
      content: content,
      date_start: date_start,
      date_end: date_end,
    }
    
    api.post('/api/get-notice.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
          if (resp.data.result.list.length == 0) {
              alert("검색 결과가 없습니다.");
              setTableTotalCount(0);
              setTableData([]);
              return;
          }

          setTableTotalCount(resp.data.result.totalCount);
          setTableData(resp.data.result.list);
      }
      else {
          alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }

  useEffect(() => {
  //  api.get('/api-test')
  //    .then((resp) => {
  //      console.log(resp)
  //    })
  //    .catch((err) => console.error(err));
    reqNoticeList();
  }, []);

  // event processing part
  const handleClickDownload = () => {
    //...
  };
  
  const handleClickSearch = () => {
    reqNoticeList();
  };

  const handleClickAdd = () => {
    openModal();
  };

  const handleClickTableRow = (row: number) => {
    // nid: notice_id
    router.push("/notice/detail?nid=" + tableData[row].notice_id);
  };

  const handlePageChange = (page: number) => {
    setTableOffset((page - 1) * COUNT_PER_PAGE);
    reqNoticeList();
  };

  useEffect(() => {
    reqNoticeList();
  }, [tableOffset]);

  const columns = [
    {
      title: "날짜",
      key: "reg_time",
      renderItem: (item: any, row: number) => convertDateTime3(item.reg_time)
    },
    {
      title: "홈화면 시작일",
      key: "open_time",
    },
    {
      title: "홈화면 종료일",
      key: "close_time",
    },
    {
      title: "첨부파일",
      key: "attachment",
      renderItem: (item: any) => (
        item.attachment ? <FileIcon /> : <FileIcon />
      ),
    },
    {
      title: "제목",
      key: "title",
    },
    {
      title: "작성자",
      key: "submitter",
    },
  ];

  return (
    <div>
      <PageBreadcrumb pageTitle1="게시판" pageTitle2="공지사항" />

      <div className="space-y-3">
        <ComponentCard title='공지사항 목록 조회'>

          <div className="space-y-3">
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
              <WithLabel label="제목" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="제목을 입력하세요." value={title} onChange={(e) => setTitle(e.target.value)} />
              </WithLabel>
              <WithLabel label="작성자 아이디" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="조회할 작성자 아이디를 입력하세요."  value={uid1} onChange={(e) => setUid1(e.target.value)}  />
              </WithLabel>
            </div>
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
              <WithLabel label="등록일" label_width={SEARCH_LABEL_WIDTH}>
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                  <DatePicker
                    id="date_start-picker"
                    placeholder="조회 시작일"
                    // onChange={(dates, currentDateString) => {
                    //   // Handle your logic
                    //   console.log({ dates, currentDateString });
                    // }}
                    onChange={(dates, currentDateString) => { setDateStart(currentDateString); }}
                  />
                  <DatePicker
                    id="date_end-picker"
                    placeholder="조회 종료일"
                    // onChange={(dates, currentDateString) => {
                    //   // Handle your logic
                    //   console.log({ dates, currentDateString });
                    // }}
                    onChange={(dates, currentDateString) => { setDateEnd(currentDateString); }}
                  />
                </div>
              </WithLabel>
              <div className="flex items-center justify-end gap-5">
                <Button size="sm" variant="outline" startIcon={<DocsIcon />}>엑셀파일 다운로드</Button>
                <Button size="sm" variant="primary" onClick={handleClickSearch}>조회</Button>
              </div>
            </div>
          </div>

          <CtTable1 columns={columns} bodyData={tableData} 
            offset={tableOffset} totalCount={tableTotalCount} countPerPage={COUNT_PER_PAGE} pageNumCount={PAGE_NUM_COUNT} onClickRow={handleClickTableRow}
            onClickPageChange={handlePageChange} />

          <div>
            {/*<Button size="sm" variant="primary" startIcon={<PlusIcon />} onClick={handleClickAdd}>새글 등록하기</Button>*/}
          </div>

        </ComponentCard>

        <AddModifyNoticeModal isOpen={isOpen} openModal={openModal} closeModal={closeModal} multiState={modalData} onSuccess={fetchAccountList} />
      </div>
    </div>
  );
}
