"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 { TableIcon, DocsIcon } 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 api, { convertDateTime, convertDateTime2, convertDateTime3, convertDateTime6, postFileDownload, useAuthStore, useUiLoadingStore } from '@/lib/_AG';


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



export default function Logging() {
  const tokenPayload = useAuthStore((s) => s.tokenPayload);  //Bruce, JWT
  const isLoadingGlobal = useUiLoadingStore((s) => s.isLoading);
  
  const [ tableData, setTableData ] = useState<any[]>([]);
  const [ tableOffset, setTableOffset ] = useState<number>(0);
  const [ tableTotalCount, setTableTotalCount ] = useState<number>(0);

  //search fields
  const [ type, setType ] = useState<string>("");
  const [ action, setAction ] = useState<string>("");
  const [ user_id, setUserId ] = useState<string>("");  
  const [ date_start, setDateStart ] = useState<string>("");
  const [ date_end, setDateEnd ] = useState<string>("");


  //function part
  //
  function reqOperatingHistoryList(is_excel: boolean) {

    const params = {
      is_excel: is_excel,
      offset: tableOffset,
      limit: COUNT_PER_PAGE,
      type: type,
      action: action,
      user_id: user_id,
      date_start: date_start,
      date_end: date_end,
    }

    if (is_excel == true) {
      postFileDownload('/api/get-operating-history.do', params);
      return;
    }

    api.post('/api/get-operating-history.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));
  }

  const handleClickDownload = () => {
    reqOperatingHistoryList(false);
  };

  const handleClickSearch = () => {
    reqOperatingHistoryList(false);
  };

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


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

  const columns = [
    {
      title: "날짜",
      key: "reg_time",
      renderItem: (item: any, row: number) => convertDateTime2(item.reg_time)
    },
    {
      title: "유형",
      key: "type",
      renderItem: (item : any) => ( item.type === 1 ? "system" : "operating")
    },
    {
      title: "작업 내용",
      key: "action",
    },
    {
      title: "작업자",
      key: "user_id",
    },
  ];

  return (
    <div>
      <PageBreadcrumb pageTitle1="시스템 관리" pageTitle2="로그 및 감사" />
          
      <div className="space-y-3">
        <ComponentCard title="로그 목록 조회" titleIcon={<TableIcon />}>

          <div className="space-y-3">
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-4">
              <WithLabel label="작업내용 검색어" label_width={SEARCH_LABEL_WIDTH}>
                <Input 
                  type="text" 
                  placeholder="작업내용 검색어를 입력하세요." 
                  value={action} 
                  onChange={(e) => setAction(e.target.value)}
                />
              </WithLabel>
              <WithLabel label="작업자 아이디" label_width={SEARCH_LABEL_WIDTH}>
                <Input 
                  type="text" 
                  placeholder="조회할 작업자 아이디를 입력하세요." 
                  value={user_id} 
                  onChange={(e) => setUserId(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) => { setDateStart(currentDateString); }}
                  />
                  <DatePicker
                    id="date_end-picker"
                    placeholder="조회 종료일"
                    onChange={(dates, currentDateString) => { setDateEnd(currentDateString); }}
                  />
                </div>
              </WithLabel>
              <div className="flex items-center justify-end gap-5">
                <Button size="sm" variant="outline" startIcon={<DocsIcon />} onClick={handleClickDownload}>엑셀파일 다운로드</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}
            onClickPageChange={handlePageChange} />

        </ComponentCard>
      </div>
    </div>
  );
}
