"use client"
import PageBreadcrumb from "@/components/common/PageBreadCrumb2";
import ComponentCard from '@/components/common/ComponentCard2';
import BizGroupPanel from "@/components/common/BizGroupPanel";
import CtTable1 from '@/components/tables/CtTable1';
import Button from '@/components/ui/button/Button2';
import { DocsIcon, PlusIcon, TrashBinIcon, TableIcon, PencilIcon } from "@/icons";
import WithLabel from '@/components/form/WithLabel';
import Input from '@/components/form/input/InputField2';
import Select from '@/components/form/Select2';
import DatePicker from '@/components/form/date-picker2';
import Checkbox from "@/components/form/input/Checkbox";
import Badge from "@/components/ui/badge/Badge";

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

import { useModal } from "@/hooks/useModal";
import AddModifyTerminalModal, { TerminalModalProps } from './AddModifyTerminalModal';
import { useMultiState } from "@/hooks/useMultiState";

import CtTree, { CtTreeNode, expandAndSelectTreeNode, getAllNodeKeys, findParentKeys, findNodeByKey, addNodeByKey, deleteNodeByKey, findRootNodeByKey } from "@/components/CtTree";
import { reqBizGroupTree2, reqBizGroupTree3 } from "@/app/(admin)/biz-group/BizGroupContent";


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


export default function Terminal() {
  //const router = useRouter();
  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);
  
  const [ treeData, setTreeData ] = useState<CtTreeNode[]>([]);
  const [ selectedTreeKeys, setSelectedTreeKeys ] = useState<Key[]>([]);
  const [ expandedTreeKeys, setExpandedTreeKeys ] = useState<Key[]>([]);
  const [ isGroupAccess, setGroupAccess ] = useState(tokenPayload?.permission == 1);  //TempCode
  const [ isTreeOpen, setTreeOpen ] = useState(tokenPayload?.permission == 1);  //TempCode

  // group search fields
  const [ name, setName] = useState<string>("");
  const [ biz_reg_num, setBizRegNum] = useState<string>("");
  
  // terminal search fields
  const [ date_start, setDateStart] = useState<string>("");
  const [ date_end, setDateEnd] = useState<string>("");

  // modal
  const { isOpen, openModal, closeModal } = useModal();  
  const modalData = useMultiState<TerminalModalProps>({biz_group_name: "", biz_reg_num: "", isModify: false, addType: "1", terminal_id: "", biz_group_id: "", name: "", uid1: "", type: "" });


  // function part
  //
  function reqTerminalList(is_excel: boolean, biz_group_id: string, groupAccess: boolean) {
    if (!biz_group_id)
      return;

    const params = {
      is_group_access: groupAccess,
      is_excel: is_excel,
      offset: tableOffset,
      limit: COUNT_PER_PAGE,
      biz_group_id: biz_group_id,
      date_start: date_start,
      date_end: date_end,
    }

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

    api.post('/api/get-terminal.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
          if (resp.data.result.list.length == 0) {
              alert("조회 결과가 없습니다.");
              setTableData([]);
              return;
          }

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

  function reqRemoveTerminal(biz_group_id: string, terminal_id: string) {
    const params = {
      biz_group_id: biz_group_id,
      terminal_id: terminal_id
    }

    api.post('/api/remove-terminal.do', params).then((resp) => {
      console.log(resp);
            
      if (resp.data.errCode == 0) {
        reqTerminalList(false, biz_group_id, isGroupAccess);
      }
      else {
        alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }
  //


  // event processing part
  //
  // tree part //////////  
  const handleClickGroupSearch = () => {
    if (tokenPayload?.permission == 1) {
      if (name == "" && biz_reg_num == "") {
        alert("그룹명(사업자명) 또는 사업자등록번호를 입력하셔야 합니다.");
        return;
      }
      if (name != "" && name.length < 3) {
        alert("그룹명(사업자명)은 세글자 이상 입력해야 합니다.");
        return;
      }
      if (biz_reg_num != "" && biz_reg_num.length < 3) {
        alert("사업자등록번호는 세글자 이상 입력해야 합니다.");
        return;
      }

      //reqBizGroupTree3("", setTreeData, setSelectedTreeKeys, setExpandedTreeKeys);
      reqBizGroupTree2(true, "", "", "", "", name, biz_reg_num, treeData, setTreeData);
    }
  };

  const handleClickNode = (key: Key) => {
    if (isGroupAccess == false) {
      const root = findRootNodeByKey(treeData, key as string);
      reqTerminalList(false, root.key as string, isGroupAccess);
      return;
    }

    setTableOffset(0);
    reqTerminalList(false, key as string, isGroupAccess);
  }

  const handleClickTreeExpanded = (key: Key) => {
    const node = findNodeByKey(treeData, key);
    if (node.children == undefined)
      reqBizGroupTree2(false, key as string, "", "", "", "", "2", treeData, setTreeData);
  }

  const handleClickGroupAccess = (value: boolean) => {
    setGroupAccess(value);
    
    if (tokenPayload?.permission == 1) {
      if (selectedTreeKeys.length <= 0) {
        return;
      }

      reqTerminalList(false, selectedTreeKeys[0] as string, value);
      return;
    }

    if (value == false || selectedTreeKeys.length <= 0) {
      reqTerminalList(false, String(tokenPayload?.biz_group_id), value);
    }
    else {
      reqTerminalList(false, selectedTreeKeys[0] as string, value);
    }
  }
  // tree part //////////

  const handleClickDownload = () => {
    reqTerminalList(true, selectedTreeKeys[0] as string, isGroupAccess);
  };
  
  const handleClickSearch = () => {
    if (selectedTreeKeys.length <= 0) {
      alert("조회하려면 사업자를 선택해야 합니다.");
      return;
    }
    
    reqTerminalList(false, selectedTreeKeys[0] as string, isGroupAccess);
  };

  const handleClickAdd = () => {
    if (selectedTreeKeys.length <= 0) {
      alert("신규 추가하려면 사업자를 선택해야 합니다.");
      return;
    }

    // m: 0 = isModify is false, 1 = isModify is true
    // bgid: biz_group_id
    // n: name
    // brn: biz_reg_num
    //router.push(`/terminal/detail?m=0&bgid=${selectedTreeKeys[0]}&n=${name}&=brn=${biz_reg_num}`);   
    const node = findNodeByKey(treeData, selectedTreeKeys[0]);
    modalData.setAll({
      isModify: false,
      biz_group_name: node.name,
      biz_reg_num: node.biz_reg_num,
      terminal_id: "",
      biz_group_id: node.key,
      name: "",
      uid1: ""
    });
    openModal();
  };

  const handleRowClickModify = (row: number) => {
    //router.push(`/terminal/detail?m=1&bgid=${selectedTreeKeys[0]}&n=${name}&brn=${biz_reg_num}`);
    const node = findNodeByKey(treeData, selectedTreeKeys[0]);

    modalData.setAll({
      ...tableData[row],
      isModify: true,
      biz_group_name: node.name,
      biz_reg_num: node.biz_reg_num,
    });
    openModal();
  };

  const handleRowClickDelete = (row: number) => {
    if (confirm("'" + tableData[row].name + "'를 삭제하시겠습니까?")) {
      reqRemoveTerminal(tableData[row].biz_group_id, tableData[row].terminal_id);
    }    
  };

  const handlePageChange = (page: number) => {
    setTableOffset((page - 1) * COUNT_PER_PAGE);
    reqTerminalList(false, selectedTreeKeys[0] as string, isGroupAccess);
  };

  const handleModalOk = () => {
    closeModal();
    reqTerminalList(false, selectedTreeKeys[0] as string, isGroupAccess);
  };  
  //

  useEffect(() => {
    if (tokenPayload == undefined)
      return;

    if (tokenPayload?.permission == 1)
      return;

    reqBizGroupTree3(String(tokenPayload?.biz_group_id), setTreeData, setSelectedTreeKeys, setExpandedTreeKeys, (resp: any) => {
      setGroupAccess(tokenPayload?.permission == 1);
      setTreeOpen(tokenPayload?.permission == 1);

      reqTerminalList(false, String(resp.data.result.tree[0].key), tokenPayload?.permission == 1);
    });
  }, [tokenPayload]);

  useEffect(() => {
    reqTerminalList(false, selectedTreeKeys[0] as string, isGroupAccess);
  }, [tableOffset]);


  // UI part
  //
  const columns = [
    {
      title: "등록일",
      key: "reg_time",
      renderItem: (item: any, row: number) => convertDateTime3(item.reg_time)
    },
    {
      title: "사업자",
      key: "biz_group_name",
    },
    {
      title: "기기명",
      key: "name",
    },
    {
      title: "단말기 TID",
      key: "uid1",
      renderItem: (item: any, row: number) => (item.uid1 + " (" + (item.type == 1 ? "KICC" : "NICE") +")")
    },
    {
      title: "무인기기 장착 여부",
      key: "state",
      renderItem: (item: any, row: number) => (
        <Badge size="sm" color={item.state === 1 ? "success" : "warning"}>
          {item.state === 1 ? "장착중" : "단말기만"}
        </Badge>
      ),
    },
    {
      title: "설정",
      key: "_",
      renderItem: (item: any, row: number) => (
        <div>
          <PencilIcon
            className="cursor-pointer hover:fill-error-500 dark:hover:fill-error-500 fill-gray-700 dark:fill-gray-400"
            onClick={() => {handleRowClickModify(row)}} />
        </div>
      ),
    },
    {
      title: "삭제",
      key: "_",
      renderItem: (item: any, row: number) => (
        <div>
          <TrashBinIcon 
            className="cursor-pointer hover:fill-error-500 dark:hover:fill-error-500 fill-gray-700 dark:fill-gray-400"
            onClick={() => {handleRowClickDelete(row)}} />
        </div>
      ),
    },
  ];

  return (
    <div>
      <PageBreadcrumb pageTitle1="카드단말기 관리" />

      <div className="space-y-3">
        <BizGroupPanel
          title="사업자별 계층도"
          name={name}
          bizRegNum={biz_reg_num}
          onChangeName={setName}
          onChangeBizRegNum={setBizRegNum}
          onClickSearch={handleClickGroupSearch}
          isDisabled={isLoadingGlobal}
          searchLabelWidth={SEARCH_LABEL_WIDTH}
        >
          <CtTree
            treeData={treeData}
            selectedKeys={selectedTreeKeys}
            setSelectedKeys={setSelectedTreeKeys}
            onClickNode={handleClickNode}
            expandedKeys={expandedTreeKeys}
            setExpandedKeys={setExpandedTreeKeys}
            onClickExpanded={handleClickTreeExpanded}
          />
        </BizGroupPanel>

        <ComponentCard title="카드단말기 목록" titleIcon={<TableIcon />}>
          <div>
            <div className="space-y-2 grid grid-cols-1 gap-3 sm:grid-cols-3">
              <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 gap-3">
                <Checkbox checked={isGroupAccess} onChange={(value) => handleClickGroupAccess(value)} />
                <span className="block font-normal text-gray-700 text-theme-sm dark:text-gray-400">
                  그룹단위로 조회
                </span>
              </div>
              <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} disabled={isLoadingGlobal}>조회</Button>
              </div>
            </div>
          </div>
          
          <CtTable1 columns={columns} bodyData={tableData} 
            offset={tableOffset} totalCount={tableTotalCount} countPerPage={COUNT_PER_PAGE} pageNumCount={PAGE_NUM_COUNT}
            onClickPageChange={handlePageChange} />

          <div>
            <Button size="sm" variant="primary" startIcon={<PlusIcon />} onClick={handleClickAdd} disabled={isLoadingGlobal}>신규 추가하기</Button>
          </div>

        </ComponentCard>

        <AddModifyTerminalModal multiState={modalData} onOk={handleModalOk} isOpen={isOpen} closeModal={closeModal} />                

      </div>
    </div>
  );
}
