"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 Checkbox from '@/components/form/input/Checkbox';
import CtModal from "@/components/CtModal";
import { useMultiState } from "@/hooks/useMultiState";
import api from '@/lib/_AG';



function randomUppercase(max: number): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';

  for (let i = 0; i < max; i++) {
    result += chars[Math.floor(Math.random() * chars.length)];
  }

  return result;
}


export interface TerminalModalProps {
  biz_group_name?: string;  // internal use
  biz_reg_num?: string;  // internal use
  //
  isModify: boolean;
  addType: string;
  //
  terminal_id: string;
  biz_group_id: string;
  name: string;
  uid1: string;
  type: string;
}

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

export default function AddModifyTerminalModal({ multiState, onOk, isOpen, closeModal }: AddModifyTerminalModalProps) {
  const [ optAddType, setOptAddType ] = useState<string>("1");
  const [ optTerminalType, setOptTerminalType ] = useState<string>("1");
  const [ isAutoName, setIsAutoName ] = useState<boolean>(true);
  const [ prefix, setPrefix ] = useState<string>(randomUppercase(7)); //...


  const handleChangeUid1 = (value: string) => {
    multiState.set("uid1", value);

    if (isAutoName) {
      //multiState.set("name", multiState.values.biz_group_name + "-" + value);  //...
      //multiState.set("name", prefix + "-" + value);  //...
      multiState.set("name", prefix);  //...
    }
  };

  const handleClickAddOrModify = () => {
    setPrefix(randomUppercase(7));  //...

    if (multiState.values.name == "") {
      alert("그룹명(사업자명)을 입력하셔야 합니다.");
      return;
    }

    if (multiState.values.uid1 == "") {
      alert("TID를 입력하셔야 합니다.");
      return;
    }

    const { biz_group_name, biz_reg_num, ...tmpParams } = multiState.values;
    const params = { ...tmpParams, addType: optAddType, type: optTerminalType };

    if (multiState.values.isModify) {
      api.post('/api/modify-terminal.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-terminal.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))
    }
  }


  useEffect(() => {
    if (isOpen) {
      setOptAddType("1");
      setIsAutoName(true);
    }
  }, [isOpen]);
  
  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 />
        </div>
        <div>
          <div className="flex items-center gap-3">
            <Label redPoint className="mb-8">무인기기명</Label>
            <div className="flex items-center gap-1 ml-2 mb-2">
              <Checkbox checked={isAutoName} onChange={(value) => setIsAutoName(value)} />
              <span className="block font-normal text-gray-700 text-theme-sm dark:text-gray-400">
                자동생성
              </span>
            </div>
          </div>          
          <Input type="text" placeholder="무인기기명을 입력하세요." value={multiState.values.name} onChange={(e) => multiState.set("name", e.target.value)} disabled={multiState.values.isModify || isAutoName} />
        </div>
        <div>
          <Label redPoint>단말기 TID</Label>
          <Input type="text" placeholder="단말기 TID를 입력하세요." value={multiState.values.uid1} onChange={(e) => handleChangeUid1(e.target.value)} disabled={multiState.values.isModify} />
        </div>
        <div>
          <Label redPoint>단말기 벤더</Label>
          <Select
            placeholder="선택하세요"
            options={[
              { label: "KICC", value: "1" },
              { label: "NICE", value: "2" }
            ]}
            defaultValue={multiState.values.type}
            onChange={(value) => {setOptTerminalType(value)}}
            className="dark:bg-dark-900" />
        </div>
        { multiState.values.isModify == false ? <>
        <div>
          <Label redPoint>추가 유형</Label>
          <Select
            placeholder="선택하세요"
            options={[
              { label: "기기생성 및 카드단말기 추가", value: "1" },
              { label: "카드단말기 교체용으로 추가", value: "2" }
            ]}
            defaultValue={multiState.values.addType}
            onChange={(value) => {setOptAddType(value)}}
            className="dark:bg-dark-900" />
        </div>
        </>
        : 
        <div>
        {/*
          <Label>카드단말기 정보</Label>
          <Input type="text" placeholder="TID: " value={""} onChange={(e) => {}} />
          <Input type="text" placeholder="Model Code: " value={""} onChange={(e) => {}} />
          <Input type="text" placeholder="Model Ver: " value={""} onChange={(e) => {}} />
          <Input type="text" placeholder="Serial No: " value={""} onChange={(e) => {}} />
          <Input type="text" placeholder="단말번호: " value={""} onChange={(e) => {}} />
          */}
        </div>
        }
      </CtModal>
    // </div>
  );
};
