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


export interface LocationModalProps {
  isModify: boolean;  // external set
  pid: string;  // external set
  //
  name: string;
  description: string;
  address: string;
}

interface AddModifyLocationModalProps {
  multiState: ReturnType<typeof useMultiState<LocationModalProps>>;
  onOk: (insertedId: number) => void;
  isOpen: boolean;
  closeModal: () => void;
}

export default function AddModifyLocationModal({ multiState, onOk, isOpen, closeModal }: AddModifyLocationModalProps) {

  const handleClickAddOrModify = () => {
    if (multiState.values.name == "") {
      alert("그룹명(사업자명)을 입력하셔야 합니다.");
      return;
    }
    
    if (multiState.values.isModify) {
      api.post('/api/modify-location.do', multiState.values).then((resp) => {
        console.log(resp);
        
        if (resp.data.errCode == 0) {
            alert("수정되었습니다.");
            onOk(-1);
        }
        else {
            alert("일시적으로 사용할 수 없습니다 : " + resp.data.errCode);
        }
      })
      .catch((err) => console.error(err))
    }
    else {
      api.post('/api/add-location.do', multiState.values).then((resp) => {
        console.log(resp);
        
        if (resp.data.errCode == 0) {
            alert("추가되었습니다.");
            onOk(resp.data.result.location_id);
        }
        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 redPoint>위치명</Label>
          <Input type="text" value={multiState.values.name} onChange={(e) => multiState.set("name", e.target.value)} />
        </div>
        <div>
          <Label>설명</Label>
          <Input type="text" value={multiState.values.description} onChange={(e) => multiState.set("description", e.target.value)} />
        </div>
        <div>
          <Label>주소</Label>
          <Input type="text" value={multiState.values.address} onChange={(e) => multiState.set("address", e.target.value)} />
        </div>
      </CtModal>
    // </div>
  );
};
