"use client"
import PageBreadcrumb from "@/components/common/PageBreadCrumb2";
import ComponentCard from '@/components/common/ComponentCard2';
import Button from '@/components/ui/button/Button2';
import { DocsIcon, FileIcon, PlusIcon, TrashBinIcon, TableIcon, PencilIcon } from "@/icons";
import Label from '@/components/form/Label';
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 AddModifyLocationModal, { LocationModalProps } from "./AddModifyLocationModal";
import { useMultiState } from "@/hooks/useMultiState";

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

const SEARCH_LABEL_WIDTH = 24;


export default function Location() {
  const { isOpen, openModal, closeModal } = useModal();
  
  // tree part
  const [ treeData, setTreeData] = useState<CtTreeNode[]>([]);
  const [ selectedTreeKeys, setSelectedTreeKeys] = useState<Key[]>([]);
  const [ expandedTreeKeys, setExpandedTreeKeys] = useState<Key[]>([]);

  // search fields
  const [ name, setName] = useState<string>("");
  const [ description, setDescription] = useState<string>("");
  const [ address, setAddress] = useState<string>("");
  const [ date_start, setDateStart] = useState<string>("");
  const [ date_end, setDateEnd] = useState<string>("");
  //  

  // form fields
  const [ form_name, setFormName] = useState<string>("");
  const [ form_description, setFormDescription] = useState<string>("");
  const [ form_address, setFormAddress] = useState<string>("");
  //

  const modalData = useMultiState<LocationModalProps>({isModify: false, pid: "", name: "", description, address: "" });
  

  // function part
  //
  function reqLocationTree(isRoot: boolean, location_id: string) {
    const params: any = {
      isRoot: isRoot,
      id: location_id,
      date_start: date_start,
      date_end: date_end,
    }

    if (isRoot == true) {
      params.name = name;
      params.description = description;
      params.address = address;
    }

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

          if (location_id == "") {
            setTreeData(resp.data.result.tree);
          }
          else {
            setTreeData(treeData => addNodeByKey(treeData, location_id, resp.data.result.tree));
          }
      }
      else {
          alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }

  function reqRemoveLocation(location_id: Key) {
    const params = {
      ids: location_id
    }

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

  function reqModifyLocation(location_id: Key) {
    if (form_name == "") {
      alert("위치명을 입력하셔야 합니다.");
      return;
    }

    const params = {
      location_id: location_id,
      name: form_name,
      description: form_description,
      address: form_address,
    }
    
    api.post('/api/modify-location.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
        const node = findNodeByKey(treeData, location_id);
        node.key = location_id;
        node.title = form_name
        node.name = form_name;
        node.description = form_description;
        node.address = form_address;        
        
        setTreeData(treeData => changeNodeByKey(treeData, location_id, node));
      }
      else {
        alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }
  //

  // event processing part
  //
  const handleClickSearch = () => {
    reqLocationTree(true, "");
  };

  const handleClickTreeExpanded = (key: Key) => {
    //console.log("handleClickTreeExpanded, key = ", key);
    const node = findNodeByKey(treeData, key);
    if (node.children == undefined)
      reqLocationTree(false, key as string);
  }
  
  const handleClickNode = (key: Key) => {
    //console.log("handleClickNode, key = ", key);
    const node = findNodeByKey(treeData, key);
    //console.log("findNodeByKey = ", node);
    
    setFormName(node.name);
    setFormDescription(node.description);
    setFormAddress(node.address);
  }

  const handleClickAdd = () => {
    modalData.reset();
    
    if (selectedTreeKeys.length > 0) {
      modalData.set("pid", String(selectedTreeKeys[0]));
    }

    //... expandAndSelectTreeNode(treeData, String(selectedTreeKeys[0]), setSelectedTreeKeys, expandedTreeKeys, setExpandedTreeKeys);
    
    openModal();
  };

  const handleClickModify = () => {
    if (selectedTreeKeys.length <= 0)
      return;
    
    const node = findNodeByKey(treeData, selectedTreeKeys[0]);
    if (confirm("수정 하시겠습니까?")) {
      reqModifyLocation(selectedTreeKeys[0]);
    }
  };

  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);
      reqRemoveLocation(selectedTreeKeys[0]);
    }
  };

  const handleModalOk = (insertedId: number) => {
    closeModal();

    const newNode = {
      isModify: false,
      key: String(insertedId),
      title: modalData.values.name,
      pid: modalData.values.pid, 
      name: modalData.values.name, 
      description: modalData.values.description, 
      address: modalData.values.address,
      isLeaf: false,
    };
    setTreeData(treeData => addNodeByKey(treeData, newNode.pid, newNode));

    setFormName(newNode.name);
    setFormDescription(newNode.description);
    setFormAddress(newNode.address);

    //... setTimeout(() => {
    //  expandAndSelectTreeNode(treeData, newNode.pid, setSelectedTreeKeys, expandedTreeKeys, setExpandedTreeKeys);
    //}, 2500);
    //queueMicrotask(() => {
      //console.log('렌더링 후 실행');
      //expandAndSelectTreeNode(treeData, insertedId, setSelectedTreeKeys, expandedTreeKeys, setExpandedTreeKeys);
    //});

  };

  useEffect(() => {
    //reqLocationTree(true, '');
  }, []);

  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={name} onChange={(e) => setName(e.target.value)}
                  onKeyDown={(e) => {if (e.key === "Enter") handleClickSearch()}} />
              </WithLabel>
              <WithLabel label="설명" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="조회할 설명를 입력하세요." value={description} onChange={(e) => setDescription(e.target.value)}
                onKeyDown={(e) => {if (e.key === "Enter") handleClickSearch()}} />
              </WithLabel>
              <WithLabel label="주소" label_width={SEARCH_LABEL_WIDTH}>
                <Input type="text" placeholder="조회할 주소를 입력하세요." value={address} onChange={(e) => setAddress(e.target.value)}
                onKeyDown={(e) => {if (e.key === "Enter") handleClickSearch()}} />
              </WithLabel>
              <div className="flex items-center gap-5">
                <Button size="sm" variant="primary" onClick={handleClickSearch}>조회</Button>
              </div>
            </div>
          </div>

          <div className="flex flex-col sm:flex-row gap-8">
            <ComponentCard title="지역 계층도">
              <div className="min-w-[500px] w-full h-[370px] overflow-auto">
                <CtTree    
                  treeData={treeData}
                  selectedKeys={selectedTreeKeys}
                  setSelectedKeys={setSelectedTreeKeys}
                  onClickNode={handleClickNode}
                  expandedKeys={expandedTreeKeys}
                  setExpandedKeys={setExpandedTreeKeys}
                  onClickExpanded={handleClickTreeExpanded}
                />
              </div>
              <div className="flex items-center gap-5  flex-wrap">
                <p className="w-full mt-2">
                  <span className="relative before:content-['*'] before:text-red-500 before:mr-1"></span>
                  위치를 선택하고 [신규추가] 버튼을 클릭하면 하위에 추가됩니다.
                </p>
                <Button size="sm" variant="primary" startIcon={<PlusIcon />} onClick={handleClickAdd}>신규추가</Button>
                <Button size="sm" variant="primary" startIcon={<TrashBinIcon />} onClick={handleClickDelete}>선택삭제</Button>
              </div>
            </ComponentCard>
            <div className="w-[380px]">
              <div className="flex-1 space-y-6">
                <div>
                  <Label>위치명</Label>
                  <Input type="text" value={form_name} onChange={(e) => setFormName(e.target.value)} />
                </div>
                <div>
                  <Label>설명</Label>
                  <Input type="text" value={form_description} onChange={(e) => setFormDescription(e.target.value)} />
                </div>
                <div>
                  <Label>주소</Label>
                  <Input type="text" value={form_address} onChange={(e) => setFormAddress(e.target.value)} />
                </div>
                <Button size="sm" variant="primary" startIcon={<TrashBinIcon />} onClick={handleClickModify}>수정</Button>
              </div>
            </div>
          </div>
        </ComponentCard>
        
        <AddModifyLocationModal multiState={modalData} onOk={handleModalOk} isOpen={isOpen} closeModal={closeModal} />

      </div>
    </div>
  );
}
