"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, BoxCubeIcon, 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, { useAuthStore, postFileDownload, convertDateTime3, useUiLoadingStore } from '@/lib/_AG';

import { useModal } from "@/hooks/useModal";
import AddModifyDeviceModal, { DeviceModalProps } from './AddModifyDeviceModal';
import ManageGoodsModal, { GoodsModalProps } from './ManageGoodsModal';
import ManageTemplateModal, { TemplateModalProps } from './ManageTemplateModal';
import { useMultiState } from "@/hooks/useMultiState";

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


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



export default function Device() {
  const router = useRouter();
  const tokenPayload = useAuthStore((s) => s.tokenPayload);  //Bruce, JWT
  
  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>("");
  
  // device search fields
  const [ date_start, setDateStart ] = useState<string>("");
  const [ date_end, setDateEnd ] = useState<string>("");
  const [ listIdleTerminal, setListIdelTerminal ] = useState([]);
  const [ listGoods, setListGoods ] = useState([]);
  const isLoadingGlobal = useUiLoadingStore((s) => s.isLoading);
  
  // modal
  const { isOpen, openModal, closeModal } = useModal();
  const modalData = useMultiState<DeviceModalProps>( {biz_group_name: "", biz_reg_num: "", isModify: false, tid: "", device_id: "", biz_group_id: "", new_biz_group_id: "", terminal_id: "", name: "", manager_name: "", optTid: [], optBizGroup: [] });
  
  const { isOpen: isOpenManageBizGroup, openModal: openModalManageBizGroup, closeModal: closeModalManageBizGroup } = useModal();

  const { isOpen: isOpenManageGoods, openModal: openModalManageGoods, closeModal: closeModalManageGoods } = useModal();
  const modalDataManageGoods = useMultiState<GoodsModalProps>( {biz_group_name: "", biz_reg_num: "", device_name: "", device_id: "", 
    prev_device_goods: [], new_device_goods: [], optGoodsList: [] });

  const { isOpen: isOpenManageTemplate, openModal: openModalManageTemplate, closeModal: closeModalManageTemplate } = useModal();
  const modalDataManageTemplate = useMultiState<TemplateModalProps>({ biz_group_id: 0, optGoodsList: [] });
  

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

    const params = {
      is_excel: is_excel,
      is_group_access: groupAccess,
      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-device.do', params);
      return;
    }

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

          //if (selectedTreeKeys.length == 0)
          //  setSelectedTreeKeys([String(biz_group_id)]);

          reqTerminalList(biz_group_id);
          //reqGoodsList(biz_group_id);
      }
      else {
          alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }

  function reqRemoveDevice(biz_group_id: string, device_id: string) {
    const params = {
      biz_group_id: biz_group_id,
      device_id: device_id
    }

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

  function reqTerminalList(biz_group_id: string) {
    const params = {
      limit: 100, // max 100
      biz_group_id: biz_group_id,
      state: 5, // 미사용
    }

    api.post('/api/get-terminal.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
          if (resp.data.result.list.length == 0) {
            setListIdelTerminal([]);
            return;
          }
          setListIdelTerminal(resp.data.result.list);
      }
      else {
          alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }

  function reqGoodsList(biz_group_id: string) {
    const params = {
      limit: 100, // max 100
      biz_group_id: biz_group_id
    }

    api.post('/api/get-goods.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
          if (resp.data.result.list.length == 0) {
            setListGoods([]);
            return;
          }
          setListGoods(resp.data.result.list);
      }
      else {
          alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }

  function reqDeviceGoodsList(device_id: string) {
    const params = {
      device_id: device_id
    }

    api.post('/api/get-device-goods.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
          if (resp.data.result.list.length > 0) {
            const prev_device_goods = structuredClone(resp.data.result.list);
            modalDataManageGoods.set("prev_device_goods", prev_device_goods);

            const new_device_goods = structuredClone(resp.data.result.list);
            modalDataManageGoods.set("new_device_goods", new_device_goods);
          }
          
          openModalManageGoods();
      }
      else {
          alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }
  //


  // event processing part
  //
  // tree part //////////
  const handleClickGroupManage = () => {
    openModalManageBizGroup();
  }

  const handleManageBizGroupModalClose = () => {
    closeModalManageBizGroup();
    reqBizGroupTree3(String(tokenPayload?.biz_group_id), setTreeData, setSelectedTreeKeys, setExpandedTreeKeys, (resp: any) => {
      reqDeviceList(false, String(resp.data.result.tree[0].key), tokenPayload?.permission == 1);
    });
  };

  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);
    }
    else {
      reqBizGroupTree3(String(tokenPayload?.biz_group_id), setTreeData, setSelectedTreeKeys, setExpandedTreeKeys, (resp: any) => {
        //reqDeviceList(false, String(resp.data.result.tree[0].key), tokenPayload?.permission == 1);
        reqDeviceList(false, String(resp.data.result.tree[0].key), isGroupAccess);
      });
    }
  };

  const handleClickNode = (key: Key) => {
    if (isGroupAccess == false) {
      const root = findRootNodeByKey(treeData, key as string);
      reqDeviceList(false, root.key as string, isGroupAccess);
      return;
    }
    
    setTableOffset(0);
    reqDeviceList(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;
      }

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

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


  const handleClickDownload = () => {
    reqDeviceList(true, selectedTreeKeys[0] as string, isGroupAccess);
  };
  
  const handleClickSearch = () => {
    if (selectedTreeKeys.length <= 0) {
      alert("조회하려면 사업자를 선택해야 합니다.");
      return;
    }
    
    reqDeviceList(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
    //router.push("/device/detail?m=0&bgid=" + selectedTreeKeys[0]);

    const tidList = [{ label: "카드단말기없음", value: "0" }];

    listIdleTerminal.map((item: any) => (
      tidList.push({ 
        label: item.uid1 + "(" + (item.type == 1 ? "KICC" : "NICE") + ")", 
        value: String(item.terminal_id)
      })
    ));
    modalData.set("optTid", tidList);

    const treeList = treeToList(treeData);
    //console.log("treeList: ", treeList)
    const optBizGroup = treeList.map((item: any) => (
      { label: item.title, value: item.key }
    ));
    //console.log("optBizGroup: ", optBizGroup)
    modalData.set("optBizGroup", optBizGroup);

    const node = findNodeByKey(treeData, selectedTreeKeys[0]);
    modalData.setAll({
      isModify: false,
      biz_group_name: node.name,
      biz_reg_num: node.biz_reg_num,
      device_id: "",
      biz_group_id: node.key,
      terminal_id: "",
      name: "",
    });
    openModal();
  };

  const handleRowClickGoods = (row: number) => {
    //if (listGoods.length == 0) {
    //  alert("등록된 상품이 없습니다. 좌측 '상품관리' 메뉴에서 상품목록을 등록하세요.");
    //  return;
    //}

    router.push(`/device/manage-goods?id=${tableData[row].device_id}`);
    /*    
    const goodsList: { label: string; value: string; }[] = [];
    listGoods.map((item: any) => (
      goodsList.push({ label: item.name + "(" + item.code + ")", value: item.goods_id })
    ));
    //modalDataManageGoods.set("optGoodsList", goodsList);

    const node = findNodeByKey(treeData, String(tableData[row].biz_group_id));
    modalDataManageGoods.setAll({
      biz_group_name: node.name,
      biz_reg_num: node.biz_reg_num,
      device_name: tableData[row].name,
      optGoodsList: goodsList,
      device_id: tableData[row].device_id,
    });

    //openModalManageGoods();
    modalDataManageGoods.set("prev_device_goods", []);
    modalDataManageGoods.set("new_device_goods", []);
    reqDeviceGoodsList(tableData[row].device_id);
    */
  }

  const handleRowClickModify = (row: number) => {
    const tidList = [{ label: tableData[row].uid1 ? (tableData[row].uid1
      + "(" + (tableData[row].type == 1 ? "KICC" : "NICE") 
      + (tableData[row].state == 1 ? ") - 사용중" : ")"))
      : "카드단말기없음", value: "0" }];

    if (tableData[row].state == 1) {
      listIdleTerminal.map((item: any) => (
        tidList.push({ 
          label: item.uid1 + "(" + (item.type == 1 ? "KICC" : "NICE") + ")", 
          value: String(item.terminal_id)
        })
      ));
    }
    modalData.set("optTid", tidList);
    modalData.set("tid", tableData[row].uid1);
    

    const treeList = treeToList(treeData);
    //console.log("treeList: ", treeList)
    const optBizGroup = treeList.map((item: any) => (
      { label: item.title, value: item.key }
    ));
    //console.log("optBizGroup: ", optBizGroup)
    modalData.set("optBizGroup", optBizGroup);

    const node = findNodeByKey(treeData, String(tableData[row].biz_group_id));
    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("정말로 삭제하시겠습니까?")) {
      reqRemoveDevice(tableData[row].biz_group_id, tableData[row].device_id);
    }    
  };

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

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

  //const handleManageGoodsModalOk = () => {
  //  closeModalManageGoods();
  //};

  const handleClickTemplateManage = () => {
    if (selectedTreeKeys.length <= 0) {
      alert("템플릿을 관리하려면 사업자를 선택해야 합니다.");
      return;
    }

    if (listGoods.length == 0) {
      alert("등록된 상품이 없습니다. 좌측 '상품관리' 메뉴에서 상품목록을 등록하세요.");
      return;
    }

    const goodsList: { label: string; value: string; }[] = [];
    listGoods.map((item: any) => (
      goodsList.push({ label: item.name + "(" + item.code + ")", value: item.goods_id })
    ));

    modalDataManageTemplate.setAll({
      biz_group_id: Number(selectedTreeKeys[0]),
      optGoodsList: goodsList
    });

    openModalManageTemplate();
  };

  const handleManageTemplateModalOk = () => {
    // 템플릿 관리 완료 후 필요한 경우 추가 작업
  };
  //

  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);

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

  useEffect(() => {
   reqDeviceList(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) => {
        return item.uid1 ? (item.uid1 + " (" + (item.type == 1 ? "KICC" : "NICE") +")") : ""
      }
    },
    {
      title: "상태",
      key: "state",
      renderItem: (item: any) => {
        const connectTime = item.connect_time ? new Date(item.connect_time.replace(' ', 'T')) : null;
        const disconnectTime = item.disconnect_time ? new Date(item.disconnect_time.replace(' ', 'T')) : null;

        let color: "success" | "error" | "info" = "info";
        let text = "";

        if (connectTime && (!disconnectTime || disconnectTime < connectTime)) {
          color = "success";
          text = "가동중";
        } else if (connectTime && disconnectTime && disconnectTime > connectTime) {
          color = "error";
          text = "장애";
        }

        return (
          <Badge size="sm" color={color}>
            {text}
          </Badge>
        );
      },
    },
    {
      title: "가동시간",
      key: "connect_time",
      renderItem: (item: any, row: number) => convertDateTime3(item.connect_time)
    },
    {
      title: "장애발생시간",
      key: "disconnect_time",
      renderItem: (item: any, row: number) => convertDateTime3(item.disconnect_time)
    },
    {
      title: "관리자",
      key: "manager_name",
    },
    {
      title: "상품관리",
      key: "_",
      renderItem: (item: any, row: number) => (
        <div>
          <BoxCubeIcon
            className="cursor-pointer hover:fill-error-500 dark:hover:fill-error-500 fill-gray-700 dark:fill-gray-400"
            onClick={() => {handleRowClickGoods(row)}} />
        </div>
      ),
    },
    {
      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="사업자 그룹별로 관리"
          isOpen={isTreeOpen}
          setOpen={setTreeOpen}
          name={name}
          bizRegNum={biz_reg_num}
          onChangeName={setName}
          onChangeBizRegNum={setBizRegNum}
          onClickSearch={handleClickGroupSearch}
          onClickManage={handleClickGroupManage}
          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">
                { isTreeOpen && <>
                <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="primary" startIcon={<PlusIcon />} onClick={handleClickTemplateManage}>템플릿 관리</Button>*/}
                <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}>신규 추가하기</Button>
          </div>
           */}

        </ComponentCard>

        <ManageBizGroupModal treeData={treeData} isOpen={isOpenManageBizGroup} closeModal={handleManageBizGroupModalClose} />

        <AddModifyDeviceModal multiState={modalData} onOk={handleModalOk} isOpen={isOpen} closeModal={closeModal} />
        
        {/*<ManageGoodsModal multiState={modalDataManageGoods} onOk={handleManageGoodsModalOk} isOpen={isOpenManageGoods} closeModal={closeModalManageGoods} />*/}
        <ManageTemplateModal multiState={modalDataManageTemplate} onOk={handleManageTemplateModalOk} isOpen={isOpenManageTemplate} closeModal={closeModalManageTemplate} />

      </div>
    </div>
  );
}
