"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 } 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 AddModifyGroupModal from './AddModifyGroupModal';

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


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



const columns = [
  {
    title: "등록일",
    key: "reg_time" ,
  },
  {
    title: "그룹명(사업자명)",
    key: "name",
  },
  {
    title: "사업자번호",
    key: "biz_reg_num",
  },
  {
    title: "이메일",
    key: "email",
  },
  {
    title: "전화번호",
    key: "phone",
  },
  {
    title: "주소",
    key: "address",
  },
  {
    title: "등록자",
    key: "reg_id",
  },
];

//TempCode, 차후에 API로 불러오는 값
const tableData = [
  {
    reg_time: "2025-06-01 10:23",
    name: "롯데백화점",
    biz_reg_num: "586-86-01134",
    email: "tech02@lotte.co.kr",
    phone: "010-1234-5678",
    address: "서울특별시 강남구 테헤란로 123",
    reg_id: "admin01",
    group_id: "1",
  },
  {
    reg_time: "2025-06-02 09:15",
    name: "현대모비스",
    biz_reg_num: "123-45-67890",
    email: "info@hyundaihmall.com",
    phone: "010-2345-6789",
    address: "서울특별시 송파구 올림픽로 300",
    reg_id: "admin02",
    group_id: "2",
  },
  {
    reg_time: "2025-06-03 14:42",
    name: "한동정보통신",
    biz_reg_num: "234-56-78901",
    email: "contact@shinsegae.com",
    phone: "010-3456-7890",
    address: "서울특별시 중구 소공로 63",
    reg_id: "admin03",
    group_id: "3",
  },
  {
    reg_time: "2025-06-04 11:30",
    name: "가산점",
    biz_reg_num: "345-67-89012",
    email: "support@akplaza.com",
    phone: "010-4567-8901",
    address: "경기도 성남시 분당구 황새울로 360",
    reg_id: "admin04",
    group_id: "1-1",
  },
  {
    reg_time: "2025-06-05 08:50",
    name: "범계점",
    biz_reg_num: "456-78-90123",
    email: "service@galleria.co.kr",
    phone: "010-5678-9012",
    address: "서울특별시 강남구 압구정로 343",
    reg_id: "admin05",
    group_id: "1-2",
  },
  {
    reg_time: "2025-06-06 13:20",
    name: "위병소",
    biz_reg_num: "567-89-01234",
    email: "cs@emart.com",
    phone: "010-6789-0123",
    address: "서울특별시 성동구 뚝섬로 377",
    reg_id: "admin06",
    group_id: "2-1",
  },
  {
    reg_time: "2025-06-07 10:05",
    name: "소각장",
    biz_reg_num: "678-90-12345",
    email: "help@homeplus.co.kr",
    phone: "010-7890-1234",
    address: "서울특별시 강서구 화곡로 398",
    reg_id: "admin07",
    group_id: "2-2",
  },
  {
    reg_time: "2025-06-08 15:10",
    name: "-",
    biz_reg_num: "789-01-23456",
    email: "member@costco.co.kr",
    phone: "010-8901-2345",
    address: "경기도 하남시 덕풍동 745",
    reg_id: "admin08",
    group_id: "",
  },
  {
    reg_time: "2025-06-09 12:45",
    name: "-",
    biz_reg_num: "890-12-34567",
    email: "support@lottemart.com",
    phone: "010-9012-3456",
    address: "서울특별시 중구 청계천로 100",
    reg_id: "admin09",
    group_id: "",
  },
  {
    reg_time: "2025-06-10 09:55",
    name: "-",
    biz_reg_num: "901-23-45678",
    email: "info@ikea.kr",
    phone: "010-0123-4567",
    address: "경기도 광명시 일직로 17",
    reg_id: "admin10",
    group_id: "",
  }
];
//

const treeData_tmp = [
  {
    key: "1",
    title: "롯데백화점",
    children: [
      {
        key: "1-1",
        title: "가산점",
        children: [
          {
            key: "1-1-1",
            title: "3층",
            children: [
              {
                key: "1-1-1-1",
                title: "A구역"
              },
              {
                key: "1-1-2-1",
                title: "B구역"
              },
            ]
          },
          {
            key: "1-1-2",
            title: "옥탑방"
          },
        ]
      },
      {
        key: "1-2",
        title: "범계점",
        children: [
          {
            key: "1-2-1",
            title: "자판기1(TID)"
          },
          {
            key: "1-2-2",
            title: "자판기2(TID)"
          },
        ]
      }
    ]
  },
  {
    key: "2",
    title: "현대모비스",
    children: [
      {
        key: "2-1",
        title: "위병소",
        children: [
          {
            key: "2-1-1",
            title: "앞문자판기"
          },
          {
            key: "2-1-2",
            title: "뒷문게임기"
          },
        ]
      },
      {
        key: "2-2",
        title: "소각장",
        children: [
          {
            key: "2-2-1",
            title: "단독자판기"
          }
        ]
      }
    ]
  },
  {
    key: "3",
    title: "한동정보통신",
    isLeaf: false,
  },
];


export default function BizGroup() {
  const [ tableOffset, setTableOffset ] = useState<number>(0);
  const [ tableTotalCount, setTableTotalCount ] = useState<number>(0);
  
  const [ treeData, setTreeData] = useState(treeData_tmp);
  const [ selectedTreeKeys, setSelectedTreeKeys] = useState<Key[]>([]);
  const [ expandedTreeKeys, setExpandedTreeKeys] = useState<Key[]>([]);

  const { isOpen, openModal, closeModal } = useModal();
  

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

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

  const handleClickDelete = () => {
    if (selectedTreeKeys.length > 0) {
      const node = findNodeByKey(treeData, selectedTreeKeys[0])
      if (node.children == undefined) {
        alert("자판기는 삭제할 수 없습니다.")
        return;
      }

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

  useEffect(() => {
    const keys = getAllNodeKeys(treeData);
    setExpandedTreeKeys(keys);

    const params = {
      group_id: 1
    }
    
    api.post('/api/get-biz-group.do', params)
    //api.post('/api/sign-in.do', params)
      .then((resp) => {
        console.log(resp)
      })
      .catch((err) => console.error(err));
  }, []);

  const handlePageChange = (page: number) => {
    console.log('page change', page);
  };


  const SEARCH_LABEL_WIDTH = 24;

  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="조회할 그룹명(사업자명)을 입력하세요." />
              </WithLabel>
              <WithLabel label="사업자번호" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="조회할 사업자번호를 입력하세요." />
              </WithLabel>
              <WithLabel label="이메일" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="조회할 이메일를 입력하세요." />
              </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="조회할 전화번호를 입력하세요." />
              </WithLabel>
              <WithLabel label="주소" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="조회할 주소를 입력하세요." />
              </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) => {
                      // Handle your logic
                      console.log({ dates, currentDateString });
                    }}
                  />
                  <DatePicker
                    id="date_end-picker"
                    placeholder="조회 종료일"
                    onChange={(dates, currentDateString) => {
                      // Handle your logic
                      console.log({ dates, 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">조회</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}
                  />
                </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>

        <AddModifyGroupModal isOpen={isOpen} openModal={openModal} closeModal={closeModal} />

      </div>
    </div>
  );
}
