import React from "react";
import Button from "./Button.jsx";
import SubTitle from "./SubTitle.jsx";
import Table from "./Table.jsx";
import Pagination from "./Pagination.jsx";


export default function Modal({ open, close, header, useseniorId }) {
  const seniorId = useseniorId;
  //대상자 - 보호자 매칭 리스트 
  const [sgMatchList, setSgMatchList] = React.useState([]);
  const [addGuadian, setAddGuadian] = React.useState(true); //추가된 보호자가 있는지 확인


  //사용자 등록 초기값 설정
  const [userName, setUserName] = React.useState("");
  const [gender, setGender] = React.useState("");
  const [brith, setBrith] = React.useState("");
  const [telNum, setTelNum] = React.useState("");
  const [homeAddress, setHomeAddress] = React.useState("");
  const [relationship, setRelationship] = React.useState("");
  const [matchState, setMatchState] = React.useState(true);

  //-------- 페이징 작업 설정 시작 --------//
  const limit = 5; // 페이지당 보여줄 공지 개수
  const [page, setPage] = React.useState(1); //page index
  const offset = (page - 1) * limit; //게시물 위치 계산
  const [guadianTotal, setGuadianTotal] = React.useState(0); //최대길이 넣을 변수

  //-------- 변경되는 데이터 Handler 설정 --------//
  const handleUserName = (e) => {
    setUserName(e.target.value);
  };
  const handleBrithday = (e) => {
    setBrith(e.target.value);
  };
  const handleTelNum = (e) => {
    e.target.value = e.target.value.replace(/[^0-9]/g, '').replace(/^(\d{2,3})(\d{3,4})(\d{4})$/, `$1-$2-$3`);
    setTelNum(e.target.value);
  };
  const handelRelationship = (e) => {
    setRelationship(e.target.value);
  };
  // 데이터 초기화 함수
  const dataReset = () => {
    setUserName("");
    setBrith("");
    setTelNum("");
    setRelationship("");
  }
  // 매칭 리스트 출력 영역
  const getselectMatchList = () => {
    fetch("/user/selectSeniorGuardianMatch.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        senior_id: seniorId,
      }),
    }).then((response) => response.json()).then((data) => {
      console.log("getselectMatchList : ", data);
      setSgMatchList(data);
      setGuadianTotal(data.length);
      setAddGuadian(false);
    }).catch((error) => {
      console.log('getselectMatchList() /user/selectSeniorGuardianMatch.json error : ', error);
    });
  };
  // 보호자 등록 영역
  const test = () => {
    console.log("userName : ", userName);
    console.log("gender : ", gender);
    console.log("brith : ", brith);
    console.log("telNum : ", telNum);
    console.log("homeAddress : ", homeAddress);
    console.log("relationship : ", relationship);
    console.log("matchState : ", matchState);
  }
  const insertUser = () => {
    fetch("/user/insertSeniorData.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        user_name: userName,
        user_gender: gender != "" ? gender : null,
        user_birth: brith,
        user_phonenumber: telNum,
        user_address: homeAddress != "" ? homeAddress : null,
        agency_id: 'agency01',
        government_id: 'government01',
        user_code: '3',

      }),
    }).then((response) => response.json()).then((data) => {
      console.log("보호자 등록");
      insertGuadian();
    }).catch((error) => {
      console.log('insertUser() /user/insertSeniorData.json error : ', error);
    });
  };

  const insertGuadian = () => {
    fetch("/user/insertGuardian.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        user_phonenumber: telNum,
      }),
    }).then((response) => response.json()).then((data) => {
      console.log("보호자 테이블 데이터 등록");
      matchSeniorGuadian();
    }).catch((error) => {
      console.log('insertGuadian() /user/insertGuardian.json error : ', error);
    });
  };

  const matchSeniorGuadian = () => {
    fetch("/user/insertSeniorGuardianMatch.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        senior_id: useseniorId,
        user_phonenumber: telNum,
        senior_relationship: relationship,
        guardian_match_state: matchState,
      }),
    }).then((response) => response.json()).then((data) => {
      console.log("매칭 등록");
      dataReset();
      setAddGuadian(true);
    }).catch((error) => {
      console.log('matchSeniorGuadian() /user/insertSeniorGuardianMatch.json error : ', error);
    });
  };

  // 보호자 등록페이지 데이터
  const thead3 = [
    "No",
    "이름",
    "생년월일",
    "연락처",
    "대상자와의 관계",
    "삭제"
  ];
  const key3 = [
    "rn",
    "guardian_name",
    "user_birth",
    "user_phonenumber",
    "senior_relationship",
  ];

  React.useEffect(() => {
    getselectMatchList();
  }, [addGuadian])

  return (
    <div class={open ? "openModal modal" : "modal"}>
      {open ? (
        <div className="modal-inner">
          <div className="modal-header flex">
            {header}
            <Button className={"close"} onClick={close} btnName={"X"} />
          </div>
          <div className="modal-main">
            <div className="board-wrap">
              <SubTitle explanation={"최초 ID는 연락처, PW는 생년월일 8자리입니다."} className="margin-bottom" />
              <table className="margin-bottom2 senior-insert">
                <tr>
                  <th>이름</th>
                  <td>
                    <input type="text" value={userName} onChange={handleUserName} />
                  </td>
                  <th>생년월일</th>
                  <td>
                    <div className="flex">
                      <input type='date' value={brith} onChange={handleBrithday} />
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>연락처</th>
                  <td colSpan={3}>
                    <input type="input" maxLength="13" value={telNum} onChange={handleTelNum} />
                  </td>
                </tr>
                <tr>
                  <th>대상자와의 관계</th>
                  <td colSpan={3}>
                    <input type="text" value={relationship} onChange={handelRelationship} />
                  </td>
                </tr>
              </table>
              <div className="btn-wrap flex-center margin-bottom5">
                <Button
                  className={"btn-small green-btn"}
                  btnName={"추가"}
                  onClick={() => {
                    test();
                    insertUser()
                    getselectMatchList();
                  }}
                />
              </div>
              <div>
                <Table
                  className={"caregiver-user"}
                  head={thead3}
                  contents={sgMatchList}
                  contentKey={key3}
                  view={"guadianMatch"}
                  offset={offset}
                  limit={limit}
                />
              </div>
              <div>
                <Pagination total={guadianTotal} limit={limit} page={page} setPage={setPage} />
              </div>
            </div>
          </div>
        </div>
      ) : null}
    </div>

  );
}
