import React from "react";
import Button from "./Button.jsx";
import Modal from "./MatchingModal.jsx";
import Modal2 from "./Modal.jsx";
import SubTitle from "./SubTitle.jsx";
import { useNavigate } from "react-router";
import TableTest from "./TableTest.jsx"
// import styled from "styled-components";

export default function Table({ head, contents, contentKey, onClick, className, view, offset, limit }) {
  const navigate = useNavigate();
  // 모달 title에 대상자 명 출력을 위함
  const [useName, setUseUserName] = React.useState("");
  // 매칭을 위해 대상자 ID 값 전달을 위함
  const [useseniorId, setUseSeniorId] = React.useState("");

  //대상자 - 보호자 매칭 리스트 
  const [sgMatchList, setSgMatchList] = React.useState([]);
  
  //사용자 등록 초기값 설정
  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);

  //-------- 변경되는 데이터 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("");
    relationship("")
  }

  const [modalOpen, setModalOpen] = React.useState(false);
  const openModal = () => {
    setModalOpen(true);
  };

  const [modalOpen2, setModalOpen2] = React.useState(false);
  const openModal2 = () => {
    setModalOpen2(true);
    dataReset();
  };

  const closeModal = () => {
    setModalOpen(false);
  };

  const closeModal2 = () => {
    setModalOpen2(false);
  };
  // 매칭 리스트 출력 영역
  const getselectMatchList = () => {
    fetch("/user/selectSeniorGuardianMatch.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify({
        senior_id: useseniorId,
      }),
    }).then((response) => response.json()).then((data) => {
      console.log("getselectMatchList : ", data);
      setSgMatchList(data);
      openModal();
    }).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();
    }).catch((error) => {
      console.log('matchSeniorGuadian() /user/insertSeniorGuardianMatch.json error : ', error);
    });
  };

  // 보호자 등록페이지 데이터
  const thead3 = [
    "No",
    "이름",
    "생년월일",
    "연락처",
    "대상자와의 관계",
  ];
  const key3 = [
    "rn",
    "guardian_name",
    "user_birth",
    "user_phonenumber",
    "senior_relationship",
  ];
  
  const buttonPrint = (name, id) => {
    if (view == 'mySenior') {
      return (
        <td>
          <Button
            className={"btn-small gray-btn"}
            btnName={"보기"}
            onClick={() =>{
              setUseUserName(name);
              setUseSeniorId(id);
              getselectMatchList();
              }}
          />
        </td>)
    }
    else if (view == 'allSenior') {
      return (
        <>
          <td>
            <Button
              className={"btn-small gray-btn"}
              btnName={"선택"}
              onClick={()=>{setUseSeniorId(id); openModal2}}
            />
          </td>
          <td>
            <Button
              className={"btn-small gray-btn"}
              btnName={"보기"}
              onClick={(e) =>{
              setUseUserName(name);
              setUseSeniorId(id);
              getselectMatchList();
              }}
          />
          </td>
        </>
      )
    }
  }
  React.useEffect(() => {
  }, [])
  return (
    <>
      <Modal open={modalOpen2} close={closeModal2} header="담당자 배정" />
      {/* 보호자 보기 모달창  */}
      <Modal2 open={modalOpen} close={closeModal} header={useName+"님의 가족"} >
        <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>
            <TableTest
              className={"caregiver-user"}
              head={thead3}
              contents={sgMatchList}
              contentKey={key3}
            />
          </div>
        </div>
      </Modal2>
      <table className={className}>
        <thead>
          <tr>
            {head.map((i) => {
              return <th>{i}</th>;
            })}
          </tr>
        </thead>
        <tbody>
          {contents.slice(offset, offset + limit).map((i, index) => {
            const userName = i.user_name;
            const userId = i.user_id
            return (
              <tr key={index}>
                {contentKey.map((kes) => {
                  return (
                    <>
                      <td onClick={() => {
                        navigate("/SeniorSelectOne")}}>{i[kes]}
                      </td>
                    </>
                  )
                })}
                {buttonPrint(userName, userId)}
              </tr>
            );
          })}
        </tbody>
      </table>
    </>
  );
}


// const TableStyled = styled.table`
//   border-top: 2px solid #2d303f;
//   border-bottom: 1px solid #e4dccf;
//   /* &:hover {
//     background-color: #e4dccf;
//   } */
// `;

// const TrStyled = styled.tr`
//   cursor: pointer;
// `;

// const ThStyled = styled.th`
//   padding: 1rem 0;
//   font-weight: bold;
//   background-color: #f0ebe3;
//   font-size: 1.4rem;
//   text-align: center;
// `;

// const TdStyled = styled.td`
//   padding: 1rem 0;
//   border-top: 1px solid #ececec;
//   text-align: center;
//   font-size: 1.3rem;
//   background-color: #ffffff;
// `;
