"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, TableIcon, TrashBinIcon, PencilIcon } from "@/icons";
import WithLabel from '@/components/form/WithLabel';
import Input from '@/components/form/input/InputField2';
import DatePicker from '@/components/form/date-picker2';

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

import { useModal } from "@/hooks/useModal";
import AddModifyBizGroupModal, { BizGroupModalProps } from './AddModifyBizGroupModal';
import { useMultiState } from "@/hooks/useMultiState";

import CtTree, { CtTreeNode, expandAndSelectTreeNode, getAllNodeKeys, findParentKeys, findNodeByKey, deleteNodeByKey } from "@/components/CtTree";


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


export default function BizGroup() {
  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[]>([]);

  // search fields
  const [ name, setName ] = useState<string>("");
  const [ biz_reg_num, setBizRegNum ] = useState<string>("");
  const [ email, setEmail ] = useState<string>("");
  const [ phone, setPhone ] = useState<string>("");
  const [ address, setAddress ] = useState<string>("");
  const [ date_start, setDateStart ] = useState<string>("");
  const [ date_end, setDateEnd ] = useState<string>("");
  //

  // modal
  const { isOpen, openModal, closeModal } = useModal();
  const modalData = useMultiState<BizGroupModalProps>( {isModify: false, pid: "", name: "", biz_reg_num: "", phone: "", email: "", ceo: "", address: "" });
  

  // function part
  function reqBizGroupList() {
    const params = {
      offset: tableOffset,
      limit: COUNT_PER_PAGE,
      name: name,
      biz_reg_num: biz_reg_num,
      email: email,
      phone: phone,
      address: address,
      date_start: date_start,
      date_end: date_end,
    }
    
    api.post('/api/get-biz-group.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
          if (resp.data.result.list.length == 0) {
              alert("조회 결과가 없습니다.");
              setTableTotalCount(0);
              setTableData([]);
              setTreeData([]);
              return;
          }

          setTableTotalCount(resp.data.result.totalCount);
          setTableData(resp.data.result.list);

          setTreeData(resp.data.result.tree);

          const keys = getAllNodeKeys(resp.data.result.tree);
          setExpandedTreeKeys(keys);
      }
      else {
          alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }

  function reqRemoveBizGroup(biz_group_id: Key) {
    const params = {
      ids: biz_group_id
    }

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

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

  const handleClickTableRow = (row: number) => {
    expandAndSelectTreeNode(treeData, "" + tableData[row].biz_group_id, setSelectedTreeKeys, expandedTreeKeys, setExpandedTreeKeys);
  };

  const handleClickTreeExpanded = (key: Key) => {
    //console.log("onClickExpanded, key = ", key);
  }

  const handleClickAdd = () => {
    if (selectedTreeKeys.length > 0) {
      modalData.setAll({
        isModify: false,
        pid: selectedTreeKeys[0] as string,
        name: "",
        biz_reg_num: "",
        phone: "",
        email: "",
        ceo: "",
        address: "",
      });
    }
    else {
      modalData.reset();
    }    
    openModal();
  };

  const handleRowClickModify = (row: number) => {
    expandAndSelectTreeNode(treeData, "" + tableData[row].biz_group_id, setSelectedTreeKeys, expandedTreeKeys, setExpandedTreeKeys);

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

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

  const handleClickDelete = () => {
    if (selectedTreeKeys.length <= 0)
      return;
    
    const node = findNodeByKey(treeData, selectedTreeKeys[0]);
    if (confirm("'" + node.title + "' 사업자를 삭제하시겠습니까?")) {
      //const newTreeData = deleteNodeByKey(treeData, selectedTreeKeys[0]);
      //setTreeData(newTreeData);
      reqRemoveBizGroup(selectedTreeKeys[0]);
    }
  };

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

  const handleModalOk = () => {
    closeModal();
    reqBizGroupList();
  };
  //

  useEffect(() => {
    reqBizGroupList();
  }, []);

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

  // UI part
  const columns = [
    {
      title: "등록일",
      key: "reg_time",
      renderItem: (item: any, row: number) => convertDateTime3(item.reg_time)
    },
    {
      title: "그룹명(사업자명)",
      key: "name",
    },
    {
      title: "사업자번호",
      key: "biz_reg_num",
    },
    {
      title: "이메일",
      key: "email",
    },
    {
      title: "전화번호",
      key: "phone",
    },
    {
      title: "주소",
      key: "address",
    },
    {
      title: "등록자",
      key: "reg_id",
      renderItem: (item: any, row: number) => (
        <div>
          한동관리자
        </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="영업관리" 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-3">
              <WithLabel label="그룹명(사업자명)" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="조회할 그룹명(사업자명)을 입력하세요." value={name} onChange={(e) => setName(e.target.value)} />
              </WithLabel>
              <WithLabel label="사업자번호" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="조회할 사업자번호를 입력하세요." value={biz_reg_num} onChange={(e) => setBizRegNum(e.target.value)} />
              </WithLabel>
              <WithLabel label="이메일" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="조회할 이메일를 입력하세요." value={email} onChange={(e) => setEmail(e.target.value)} />
              </WithLabel>
            </div>
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
              <WithLabel label="전화번호" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="조회할 전화번호를 입력하세요." value={phone} onChange={(e) => setPhone(e.target.value)} />
              </WithLabel>
              <WithLabel label="주소" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="조회할 주소를 입력하세요." value={address} onChange={(e) => setAddress(e.target.value)} />
              </WithLabel>
            </div>
            <div className="space-y-2 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>

          <div className="flex flex-col sm:flex-row gap-2">
              <ComponentCard title='조직 계층도'>
                <div className="min-w-[310px] w-full h-[330px] overflow-auto">
                  <CtTree    
                    treeData={treeData}
                    selectedKeys={selectedTreeKeys}
                    setSelectedKeys={setSelectedTreeKeys}
                    expandedKeys={expandedTreeKeys}
                    setExpandedKeys={setExpandedTreeKeys}
                    onClickExpanded={handleClickTreeExpanded}
                  />
                </div>
                <div className="flex items-center gap-5">
                  <Button size="sm" variant="primary" startIcon={<PlusIcon />} onClick={handleClickAdd}>선택사업자 하위에<br></br>신규사업자 추가</Button>
                  <Button size="sm" variant="primary" startIcon={<TrashBinIcon />} onClick={handleClickDelete}>선택사업자<br></br>삭제</Button>
                </div>
              </ComponentCard>
            <div className="flex-1">
              <CtTable1 columns={columns} bodyData={tableData} 
                offset={tableOffset} totalCount={tableTotalCount} countPerPage={COUNT_PER_PAGE} pageNumCount={PAGE_NUM_COUNT}
                onClickRow={handleClickTableRow} onClickPageChange={handlePageChange} />
            </div>
          </div>
        </ComponentCard>

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

      </div>
    </div>
  );
}
