"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';


export interface GoodsModalProps {
  biz_group_name?: string;  // internal use
  biz_reg_num?: string;  // internal use
  //
  isModify: boolean;
  //
  goods_id: string;
  biz_group_id: string;
  code: string;
  name: string;
  price: string;
  inventory: string;
  vendor: string;
}

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

function randomCode(): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let result = '';

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

  return result;
}

export default function AddModifyGoodsModal({ multiState, onOk, isOpen, closeModal }: AddModifyGoodsModalProps) {
  const [ isAutoCode, setIsAutoCode ] = useState<boolean>(true);

  const handleClickAddOrModify = () => {

    if (multiState.values.code == "") {
      alert("상품코드를 입력하셔야 합니다.");
      return;
    }

    if (multiState.values.name == "") {
      alert("상품명을 입력하셔야 합니다.");
      return;
    }

    const { biz_group_name, biz_reg_num, ...params } = multiState.values; // remove biz_group_name, biz_reg_num

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


  useEffect(() => {
    if (isOpen) {
      if (multiState.values.isModify == false) {
        setIsAutoCode(true);
        multiState.set("code", randomCode());
      }
    }
  }, [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>
            { multiState.values.isModify == false &&
            <div className="flex items-center gap-1 ml-2 mb-2">
              <Checkbox checked={isAutoCode} onChange={(value) => setIsAutoCode(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.code} onChange={(e) => multiState.set("code", e.target.value)} disabled={multiState.values.isModify == false && isAutoCode} />
        </div>
        <div>
          <Label redPoint>상품명</Label>         
          <Input type="text" placeholder="상품명을 입력하세요." value={multiState.values.name} onChange={(e) => multiState.set("name", e.target.value)} />
        </div>
        {/*
        <div>
          <Label>단가</Label>
          <Input type="number" placeholder="단가를 입력하세요." value={multiState.values.price} onChange={(e) => multiState.set("price", e.target.value)} />
        </div>
        <div>
          <Label>재고 수량</Label>         
          <Input type="number" placeholder="재고 수량을 입력하세요." value={multiState.values.inventory} onChange={(e) => multiState.set("inventory", e.target.value)} />
        </div>
        */}
        <div>
          <Label>공급사</Label>         
          <Input type="text" placeholder="공급사명을 입력하세요." value={multiState.values.vendor} onChange={(e) => multiState.set("vendor", e.target.value)} />
        </div>
      </CtModal>
    // </div>
  );
};
