"use client";
import React, { useEffect, useState } from "react";
import Label from '@/components/form/Label2';
import Input from '@/components/form/input/InputField2';
import Select from '@/components/form/Select2';
import CtModal from "@/components/CtModal";
import { useMultiState } from "@/hooks/useMultiState";
import api from '@/lib/_AG';
import Button from "@/components/ui/button/Button2";


export interface DeviceModalProps {
  biz_group_name?: string;  // internal use
  biz_reg_num?: string;  // internal use
  optTid: { label: string; value: string; }[];
  optBizGroup: { label: string; value: string; }[];
  tid: string;
  //
  isModify: boolean;
  //
  device_id: string;
  biz_group_id: string;
  new_biz_group_id: string;
  name: string;
  terminal_id: string;
  manager_name: string;
}

interface AddModifyDeviceModalProps {
  multiState: ReturnType<typeof useMultiState<DeviceModalProps>>;
  onOk: () => void;
  isOpen: boolean;
  closeModal: () => void;
}

export default function AddModifyDeviceModal({ multiState, onOk, isOpen, closeModal }: AddModifyDeviceModalProps) {

  const handleReboot = () => {
    if (confirm("정말로 단말기를 리부팅 하시겠습니까?") == false)
      return;

    const params = "tid=" + multiState.values.tid;

    const res = fetch("/tapi/reboot.do", {
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain; charset=UTF-8',
      },
      body: params,
    });
  }

  const handleResetTime = () => {
    const params = {
      device_id: multiState.values.device_id
    }

    api.post('/api/config-device.do', params).then((resp) => {
      console.log(resp);
      
      if (resp.data.errCode == 0) {
          alert("초기화 완료.");
          onOk();
      }
      else {
          alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
      }
    })
    .catch((err) => console.error(err))
  }

  const handleTest1 = () => {
    const params = "tid=" + multiState.values.tid;

    const res = fetch("/tapi/test1.do", {
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain; charset=UTF-8',
      },
      body: params + "&type=1",
    });
  }
  const handleTest2 = () => {
    const params = "tid=" + multiState.values.tid;

    const res = fetch("/tapi/test1.do", {
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain; charset=UTF-8',
      },
      body: params + "&type=2",
    });
  }
  const handleTest3 = () => {
    const params = "tid=" + multiState.values.tid;

    const res = fetch("/tapi/test1.do", {
      method: 'POST',
      headers: {
        'Content-Type': 'text/plain; charset=UTF-8',
      },
      body: params + "&type=3",
    });
  }
  
  const handleClickAddOrModify = () => {
    //if (multiState.values.name == "") {
    //  alert("기기 명칭을 입력하셔야 합니다.");
    //  return;
    //}

    const { biz_group_name, biz_reg_num, optTid, optBizGroup, ...params } = multiState.values;

    if (multiState.values.isModify) {
      api.post('/api/modify-device.do', params).then((resp) => {
        console.log(resp);
        
        if (resp.data.errCode == 0) {
            alert("수정되었습니다.");
            onOk();
        }
        else if (resp.data.errCode == -11) {
            alert("기기명이나 TID는 중복될 수 없습니다.");
        }
        else {
            alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
        }
      })
      .catch((err) => console.error(err))
    }
    else {
      api.post('/api/add-device.do', params).then((resp) => {
        console.log(resp);
        
        if (resp.data.errCode == 0) {
            alert("추가되었습니다.");
            onOk();
        }
        else if (resp.data.errCode == -11) {
            alert("이미 추가된 장치 입니다.");
        }
        else {
            alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
        }
      })
      .catch((err) => console.error(err))
    }
  }

  return (
    // <div className="rounded-2xl border  border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
      <CtModal
        title={multiState.values.isModify ? "기기 정보 수정": "기기 추가"}
        description={multiState.values.isModify ? "수정할 무인기기 정보를 입력하세요." : "새로 등록할 무인기기 정보를 입력하세요."}
        okBtnText={multiState.values.isModify ? "수정": "추가"}
        onClickOk={handleClickAddOrModify}
        isOpen={isOpen}
        closeModal={closeModal}
        className="max-w-[700px] p-6 lg:p-10"
      >
        <div>
          <Label>사업자원장</Label>
          {/*<Input type="text" value={multiState.values.biz_group_name + "(" + multiState.values.biz_reg_num + ")"} disabled />*/}
          <Select
            placeholder="선택하세요"
            defaultValue={multiState.values.biz_group_id}
            options={multiState.values.optBizGroup}
            onChange={(value) => {multiState.set("new_biz_group_id", value)}}
            className="dark:bg-dark-900" />
        </div>
        <div>
          <Label redPoint>무인기기명칭 또는 관리이름</Label>
          <Input type="text" placeholder="장치명을 입력하세요." value={multiState.values.name} onChange={(e) => multiState.set("name", e.target.value)} />
        </div>
        <div>
          <Label redPoint>단말기 TID</Label>
          <Select
            placeholder="선택하세요"
            defaultValue={multiState.values.optTid.length > 0 ? multiState.values.optTid[0].value : undefined}
            options={multiState.values.optTid}
            onChange={(value) => {multiState.set("terminal_id", value)}}
            className="dark:bg-dark-900" />
        </div>
        <div>
          <Label>관리자 이름</Label>
          <Input type="text" placeholder="관리자명을 입력하세요." value={multiState.values.manager_name} onChange={(e) => multiState.set("manager_name", e.target.value)} />
        </div>
        <div>
          <Button size="sm" variant="outline" onClick={handleReboot}>카드단말기 리부팅</Button>
          <Button size="sm" variant="outline" onClick={handleResetTime}>장애시간 초기화(알람끄기)</Button>
          {/**
          <Button size="sm" variant="outline" onClick={handleTest1}>1</Button>
          <Button size="sm" variant="outline" onClick={handleTest2}>2</Button>
          <Button size="sm" variant="outline" onClick={handleTest3}>3</Button>
           */}
        </div>
      </CtModal>
    // </div>
  );
};
