import React, { useEffect } from "react";
import { useNavigate, useLocation } from "react-router";
import { useSelector } from "react-redux";

import Title from "../../component/Title.jsx";
import Table from "../../component/Table.jsx";
import Calendar from "../../component/Calendar.jsx";
import TitleSmall from "../../component/TitleSmall.jsx";
import DateDay from "../../component/DateDay.jsx";
import DateMonth from "../../component/DateMonth.jsx";
import Chart6 from "../../component/chart/Chart6.jsx";
import Modal from "../../component/Modal.jsx";
import ClearIcon from '@mui/icons-material/Clear';
import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutline';
import ErrorIcon from '@mui/icons-material/Error';
import Senior from '../../../resources/files/images/senior.png';
import battery from '../../../resources/files/images/battery.png';
import zeropercent from '../../../resources/files/images/zeropercent.png';
import pullpercent from '../../../resources/files/images/pullpercent.png';
import twentypercent from '../../../resources/files/images/twentypercent.png';
import fortypercent from '../../../resources/files/images/fortypercent.png';
import eightytypercent from '../../../resources/files/images/eightypercent.png';
import sixtytypercent from '../../../resources/files/images/sixtypercent.png';
import calendar from '../../../resources/files/images/calendar.png';
import temperature from '../../../resources/files/images/temperature.png';
import medicine from '../../../resources/files/images/medicine.png';
import calendarBig from '../../../resources/files/images/calendarBig.png';
import mornon from '../../../resources/files/images/mornon.png';
import mornoff from '../../../resources/files/images/mornoff.png';
import lunchon from '../../../resources/files/images/lunchon.png';
import lunchoff from '../../../resources/files/images/lunchoff.png';
import dinneron from '../../../resources/files/images/dinneron.png';
import dinneroff from '../../../resources/files/images/dinneroff.png';
import percent_m_0 from '../../../resources/files/images/percent_m_0.png';
import percent_m_20 from '../../../resources/files/images/percent_m_20.png';
import percent_m_40 from '../../../resources/files/images/percent_m_40.png';
import percent_m_60 from '../../../resources/files/images/percent_m_60.png';
import percent_m_80 from '../../../resources/files/images/percent_m_80.png';
import percent_m_100 from '../../../resources/files/images/percent_m_100.png';

import CommonUtil from "../../../resources/js/CommonUtil.js";

export default function Main_guardian() {
  const navigate = useNavigate();
  const location = useLocation();

  //전역 변수 저장 객체
  const state = useSelector((state) => { return state });
  const defaultUserId = CommonUtil.isEmpty(state.loginUser) ? null : state.loginUser['user_id'];

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

  //검색
  const searching = () => {
    if (CommonUtil.isEmpty(seniorSearch['senior_id']) == false) {
      seniorSelectOne();
      seniorMedicationSelectList();
      seniorTemperatureSelectListByDay();
      visitRecordSelectList();
    } else {
      return;
    }
  }

  //시니어 정보
  const [senior, setSenior] = React.useState({
    'user_id': null,
    'user_name': null,
    'senior_id': null,
  });

  const [seniorSearch, setSeniorSearch] = React.useState({
    'user_id': state.loginUser['authority'] == 'ROLE_SENIOR' ? state.loginUser['user_id'] : null,
    'user_name': state.loginUser['authority'] == 'ROLE_SENIOR' ? state.loginUser['user_name'] : null,
    'senior_id': state.loginUser['authority'] == 'ROLE_SENIOR' ? state.loginUser['user_id'] : null,
  });

  //시니어 상세 조회
  const seniorSelectOne = () => {
    console.log('seniorSelectOne - seniorSearch : ', seniorSearch);

    fetch("/user/seniorSelectOne.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(seniorSearch),
    }).then((response) => response.json()).then((data) => {
      console.log("seniorSelectOne data : ", data);
      setSenior(data);
    }).catch((error) => {
      console.log('seniorSelectOne() /user/seniorSelectOne.json error : ', error);
    });
  };

  //특정 대상자의 실제 복약 정보
  const [seniorMedicationList, setSeniorMedicationList] = React.useState([]);
  const [showMedicationTimeCode, setShowMedicationTimeCode] = React.useState({});
  //특정 대상자의 실제 복약 정보 목록 조회
  const seniorMedicationSelectList = () => {
    fetch("/user/seniorMedicationSelectList.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(seniorSearch),
    }).then((response) => response.json()).then((data) => {
      setSeniorMedicationList(data);
      seniorMedicationSelectListByDay(data);
    }).catch((error) => {
      console.log('seniorMedicationSelectList() /user/seniorMedicationSelectList.json error : ', error);
    });
  };

  //특정 대상자의 일별, 복약시간별 복약 목록
  const [seniorMedicationListByDay, setSeniorMedicationListByDay] = React.useState([]);
  const [stackChartData, setStackChartData] = React.useState([]);
  const [medicationData, setMedicationData] = React.useState([]);
  //특정 대상자의 일별, 복약시간별 복약 목록 조회
  const seniorMedicationSelectListByDay = (seniorMedicationList) => {
    fetch("/user/seniorMedicationSelectListByDay.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(seniorSearch),
    }).then((response) => response.json()).then((data) => {
      setSeniorMedicationListByDay(data);
      let showMedicationTimeCode = {};
      for (let i = 0; i < seniorMedicationList.length; i++) {
        showMedicationTimeCode[seniorMedicationList[i]] = true;
      }
      setShowMedicationTimeCode(showMedicationTimeCode);
      if (CommonUtil.isEmpty(data) == false) {
        let _stackChartData = [];
        let _medicationData = [];
        for (let i = 0; i < data.length; i++) {
          let sum = 0;      // 실제 복약량
          let counter = 0;  // 복약해야하는 양
          let chartData = {
            xName: data[i]['medication_default_date'],
          };
          for (let j = 0; j < data[i]['medication_time_code_list'].length; j++) {
            if (CommonUtil.isEmpty(showMedicationTimeCode[data[i]['medication_time_code_list'][j]]) == false) {
              chartData[data[i]['medication_time_code_list'][j]] = data[i]['medication_time_code_count_list'][j];
              counter++;
              if (i > 0) {
                sum += data[i]['medication_time_code_count_list'][j];
              }
            } else {
              continue;
            }
          }
          _medicationData.push(chartData);
          _stackChartData.push({ "xName": data[i]['medication_default_date'], "sum": sum, "total": counter });
        }
        setMedicationData(_medicationData);
        setStackChartData(_stackChartData);
      }
    }).catch((error) => {
      console.log('seniorMedicationSelectListByDay() /user/seniorMedicationSelectListByDay.json error : ', error);
    });
  };

  const seniorTemperatureList = ['02:00', '10:00', '14:00', '23:00']

  //특정 대상자의 일별, 시간별 온도 목록
  const [seniorTemperatureListByDay, setSeniorTemperatureListByDay] = React.useState([]);
  const [stackTemperatureData, setStackTemperatureData] = React.useState([]);
  //특정 대상자의 일별, 시간별 온도 목록 조회
  const seniorTemperatureSelectListByDay = () => {
    fetch("/user/seniorTemperatureSelectListByDay.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(seniorSearch),
    }).then((response) => response.json()).then((data) => {
      setSeniorTemperatureListByDay(data);
      if (CommonUtil.isEmpty(data) == false) {
        let _stackTemperatureData = [];
        let chartData = {};
        for (let i = 0; i < data.length; i++) {
          chartData = {
            xName: data[i]['temperature_date'],
          };
          chartData['temperature'] = data[i]['temperature_data'];
          chartData['time'] = data[i]['temperature_time'];

          if (data[i]['temperature_date'].substr(5, 2) >= 11 || data[i]['temperature_date'].substr(5, 2) <= 2) {
            _stackTemperatureData.push(chartData);
          } else {
            _stackTemperatureData.unshift(chartData);
          }
        }
        setStackTemperatureData(_stackTemperatureData);
      }
    }).catch((error) => {
      console.log('seniorTemperatureSelectListByDay() /user/seniorTemperatureSelectListByDay.json error : ', error);
    });
  };

  //방문 기록 정보
  const [visitRecordList, setVisitRecordList] = React.useState({});
  const visitRecordInit = {
    'senior_id': senior['senior_id'],
    'visit_date': CommonUtil.getDate(),
    'visit_reason': null,
    'visit_content': null,

    'agent_id': defaultUserId,

    isInsert: true,
  };


  //방문 기록 목록 조회
  const visitRecordSelectList = () => {
    fetch("/welfare/visitRecordSelectList.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(seniorSearch),
    }).then((response) => response.json()).then((data) => {
      console.log("방문 기록 목록 조회 결과(건수) : ", data);
      data.search = visitRecordList.search;
      setVisitRecordList(data['visitRecordList']);
    }).catch((error) => {
      console.log('visitRecordSelectList() /user/visitRecordSelectList.json error : ', error);
    });
  }

  //방문 기록 정보
  const [visitDate, setVisitDate] = React.useState(null);
  const [visitRecord, setVisitRecord] = React.useState({ ...visitRecordInit });
  const visitRecordRef = React.useRef({ ...visitRecordInit });

  // React.useEffect(() => {
  //   searching();
  // }, []);

  const calerndarClick = (data) => {
    console.log("calerndarClick - date, visitRecord", data);
    setVisitDate(data.date);
    if (CommonUtil.isEmpty(data.visitData) == false) {
      setVisitRecord(data.visitData);
    } else {
      setVisitRecord(null);
    }
    openModal();
  }

  const DateMedication = () => {
    var clickDayMedication = [];
    medicationData.map((item, idx) => {
      if (item['xName'] === visitDate) {
        seniorMedicationList.map((time, idx) => {
          clickDayMedication.push(item[time]);
        })
      }
    })
    if (clickDayMedication.length > 0) {
      return (
        <>
          <tr>
            <th></th>
            {seniorMedicationList.map((item, idx) => {
              return (
                <th>
                  {item == 'DAWN' ? '식전' : item == 'MORNING' ? '아침' : item == 'AFTERNOON' ? '점심' : item == 'NIGHT' ? '저녁' : item == 'MIDNIGHT' ? '취침' : null}
                </th>
              )
            })}
          </tr>
          <tr>
            <th>복약량</th>
            {clickDayMedication.map((item) => {
              return (
                <td>{item}</td>
              )
            })}
          </tr>
        </>
      )
    }
  }

  const DateTemperature = () => {
    var clickDayTemperature = [];
    stackTemperatureData.map((item, idx) => {
      if (item['xName'] === visitDate) {
        if (item['time'] === "02:00") {
          clickDayTemperature[0] = item['temperature'];
        } else if (item['time'] === "10:00") {
          clickDayTemperature[1] = item['temperature'];
        } else if (item['time'] === "14:00") {
          clickDayTemperature[2] = item['temperature'];
        } else if (item['time'] === "23:00") {
          clickDayTemperature[3] = item['temperature'];
        }
      }
    })

    if (clickDayTemperature.length > 0) {
      return (
        <>
          <tr>
            <th></th>
            <th>02:00</th>
            <th>10:00</th>
            <th>12:00</th>
            <th>23:00</th>
          </tr>
          <tr>
            <th>온도</th>
            <td>{clickDayTemperature[0]}</td>
            <td>{clickDayTemperature[1]}</td>
            <td>{clickDayTemperature[2]}</td>
            <td>{clickDayTemperature[3]}</td>
          </tr>
        </>
      )
    }
  }

  React.useEffect(() => {
    console.log(`React.useEffect - seniorSearch : `, seniorSearch);
    searching();
  }, [seniorSearch]);

  React.useEffect(() => {
    console.log(`React.useEffect - state['seniorList'].value : `, state['seniorList'].value);
    if (CommonUtil.isEmpty(state['seniorList'].value) == false) {
      setSeniorSearch(state['seniorList'].value[0]);
    } else {
      return;
    }
  }, [state['seniorList'].value]);

  return (
    <>
      <main className="pink">
        {
          CommonUtil.isEmpty(state.loginUser) == false
            && state.loginUser['authority'] == 'ROLE_GUARDIAN' && state['seniorList'].value.length > 1 ?
            <select className="margin-bottom2" onChange={(e) => {
              console.log('e.target.value : ', e.target.value);
              const index = Number(e.target.value);
              console.log('e.target.value index : ', index);
              setSeniorSearch(state['seniorList'].value[index]);
              //setSeniorSearch(e.target.value);
            }}>
              {state['seniorList'].value.map((item, idx) => {
                return (
                  <option key={idx} value={idx}>{item['user_name']}</option>
                )
              })}
            </select>
            : null
        }

        <div className="flex-start main-guardian"><img src={Senior} alt="" />
          <Title title={`${senior['user_name']} 어르신`} explanation={"방문, 복약, 온도, 배터리 현황을 확인하세요."} />
        </div>
        <Calendar data={{ senior: senior, medication: stackChartData, temperature: stackTemperatureData, visitRecordList: visitRecordList, onClick: calerndarClick }} />

        <Modal open={modalOpen} close={closeModal} header="시니어 정보 관리">
          <div className="modal-visit board-wrap">
            <table className="margin-bottom">
              <tbody>
                <DateMedication />
                <DateTemperature />
                <tr>
                  <th>배터리</th>
                  <td colSpan={5}>30%</td>
                </tr>
              </tbody>
            </table>

            {CommonUtil.isEmpty(visitRecord) == false ? (
              <table className="flex70 margin-bottom">{/* questionnaire-table */}
                <tbody>
                  <tr>
                    <th>방문날짜</th>
                    <td colSpan={3}>
                      <input type="date" value={visitRecord['visit_date']}
                        onChange={(e) => {
                          visitRecord['visit_date'] = e.target.value;
                          setVisitRecord({ ...visitRecord });
                        }}
                        ref={el => visitRecordRef.current['visit_date'] = el}
                        disabled={true}
                      />
                    </td>
                  </tr>
                  <tr>
                    <th>방문목적</th>
                    <td colSpan={3}>
                      <select onChange={(e) => {
                        visitRecord['visit_reason'] = e.target.value;
                        setVisitRecord({ ...visitRecord });
                      }}
                        ref={el => visitRecordRef.current['visit_reason'] = el}
                        disabled={true}
                      >
                        <option value="" selected={CommonUtil.isEmpty(visitRecord['visit_reason'])}>방문목적선택</option>
                        <option value="정기방문" selected={visitRecord['visit_reason'] == "정기방문"}>정기방문</option>
                        <option value="어르신케어" selected={visitRecord['visit_reason'] == "어르신케어"}>어르신케어</option>
                        <option value="장비점검" selected={visitRecord['visit_reason'] == "장비점검"}>장비점검</option>
                        <option value="정기방문" selected={visitRecord['visit_reason'] == "기타"}>기타</option>
                      </select>
                    </td>
                  </tr>
                  <tr>
                    <th>방문 상세 사유</th>
                    <td colSpan={3}>
                      <textarea className="medicine" style={{ height: "225px" }} name="" id="" cols="30" rows="10"
                        value={visitRecord['visit_content']}
                        onChange={(e) => {
                          visitRecord['visit_content'] = e.target.value;
                          setVisitRecord({ ...visitRecord });
                        }}
                        ref={el => visitRecordRef.current['visit_content'] = el}
                        disabled={true}
                      ></textarea>
                    </td>
                  </tr>
                </tbody>
              </table>
            ) : null}
          </div>
        </Modal>
      </main>
    </>
  );
}