import React, { useEffect, useState } from 'react';
import moment from 'moment';
import axios from 'axios';
import { ToastContainer, toast } from 'react-toastify';
import { useHistory, Link } from 'react-router-dom';
import { CircularProgress  } from '@material-ui/core';

import ModalMemo from '../../component/modal_memo';
import ModalConfirm from '../../component/modal_confirm';
import ModalPdf from '../../component/pdf/modal_pdf';
import Notification from '../notification';
import ModalSettingNotify from '../../component/modal_setting_notify';
import Alert from '../../component/alert';


const MeetingDetail = (props) => {

  const history = useHistory();
  const [loaded, setLoaded] = useState(false);
  const [submit, setSubmit] = useState(false);
  const [notice, setNotice] = useState(localStorage.getItem('notice'));
  const [_success_delete, setSuccessDelete] = useState('');
  const [_400error, set400Error] = useState('');
  
  const [showConfirm, setShowConfirm] = useState(false);
  const [showSettingNotify, setShowSettingNotify] = useState(false);
  const [showMemo, setShowMemo] = useState(false);
  const [showNotify, setShowNotify] = useState(false);
  const [showPdf, setShowPdf] = useState(false);

  const [meeting, setMeeting] = useState(null);
  const [thumbnail, setThumbnail] = useState(null);

  useEffect(() => {
    let father_id = document.getElementById('father_id').value;
    setLoaded(false);
    axios.get(`/api/fathers/meetings/detail/${props.match.params?.id}`, {params: { father_id: father_id}})
    .then((response) => {
      setLoaded(true);
      setNotice(response.data.notice);
      if(response.data.status_code==200){
        console.log(response.data.params);
        var list = response.data.params;
        var total=0, num=0;
        if(list.approval){
          for(var i in list.approval)
          {
            if(list.approval[i].approval_at) num ++;
            total ++;
          }
        }
        setMeeting({...list, denominator:total, numerator:num});
        setThumbnail(response.data.params.meeting_image[0]?.image);
      } 
    });
  }, []);

  async function showModalConfirm() {
    setShowConfirm(true);
  };

  const handleCloseConfirm = () => {
    setShowConfirm(false);
  };

  const handleAcceptDelete = () => {
    setSubmit(true);
    axios.delete(`/api/fathers/meetings/delete/${props.match.params?.id}`)
    .then(response => {
      setSubmit(false);
      setShowConfirm(false);
      switch(response.data.status_code){
        case 200: setSuccessDelete('ミーティングの削除に成功しました！'); break;
        case 400: set400Error('ミーティングの削除に失敗しました。'); break;
      }
    });
  };
  
  async function showModalMemo() {
    setShowMemo(true);
  };


  async function showModalNotify() {
    setShowNotify(true);
  };

  async function handleCloseNotify() {
    setShowNotify(false);
  };
  
  async function handleClosePdf() {
    setShowPdf(false);
  };

  async function handleCloseMemo() {
    setShowMemo(false);
  };

  async function handleAcceptNotify() {
    try {
      axios.post(`/api/fathers/children/listOfMeetingNotifyUnapprovel/${props.match.params?.id}`)
        .then(response => {
          if(response.data.status_code == 200){
              axios.delete(`/api/smss/register/${props.match.params?.id}`)
                .then(response => {
                });
          }
        });
      setShowNotify(false);
    } catch (error) {
      console.log('error', error);
    }
  };

  async function handleCloseAlert() {
    setShowAlert(false);
  };

  async function handleFavorite(meetingId, currentFavorite) {
    const formdata = new FormData();
    formdata.append('meeting_id', meetingId);
    formdata.append('is_favorite', currentFavorite == 1 ? 0 : 1);
    axios.post('/api/meetings/registerFavorite', formdata).then((response) => {})

    const updatedItem = {
      ...meeting,
      is_favorite: currentFavorite == 1 ? 0 : 1,
    };
    setMeeting(updatedItem);
  };

  if (!meeting) return null;

	return (
      <div className="l-content">
        <div className="l-content-w560">
          <div className="l-content__ttl">
            <div className="l-content__ttl__left">
              <h2>ミーティング詳細</h2>
            </div>
            <Notification notice={notice}/>
          </div>
          {
            !loaded &&
              <CircularProgress color="secondary" className="css-loader"/>
          }
          {
            loaded &&
            <div className="l-content-wrap">
              <div className="p-article">
                <div className="p-article-wrap">
                  <article className="p-article__body">
                    <div className="p-article__content">       
                      <div className="meeting-member">
                        <div className="meeting-member-wrap">
                          <div onClick={()=>setShowSettingNotify(true)} data-url="login.html" className="meeting-member-link">
                            <ul className="meeting-member-count">
                              <li className="numerator">{meeting?.numerator}</li>
                              <li className="denominator">{meeting?.denominator}</li>
                            </ul>
    
                            <ul className="meeting-member-list" role="list">
                              { meeting?.approval.map((v, inx) =>
                                  <li className="meeting-member__item" role="listitem" key={inx}>
                                    <div className="avatar">
                                      <img alt="name" className="avatar-img" src={v?.child.image} />
                                    </div>
                                  </li>
                                ) 
                              }
                            </ul>
                          </div>
                        </div>
                      </div>
                      <h3 className="meeting-ttl">{ meeting.title }</h3>
                      <time dateTime="2021-07-30" className="meeting-time">
                        <span className="meeting-date">{ moment(meeting.updated_at).format('YYYY/MM/DD') }</span>
                      </time>
                      <ul className="p-article-btn-list">
                        <li className="p-article-btn__item">
                          <Link to={`/p-account/meeting/edit/${props.match.params?.id}`}
                              className="btn-default btn-yellow btn-pdf btn-r8 btn-h48">編集</Link>
                        </li>
                        <li className="p-article-btn__item">
                          <a onClick={showModalConfirm} className="btn-default btn-yellow btn-pdf btn-r8 btn-h48">削除</a>
                        </li>
                        <li className="p-article-btn__item">
                          <Link to='/p-account/meeting/new'
                             className="btn-default btn-yellow btn-pdf btn-r8 btn-h48">複製</Link>
                        </li>
                        <li className="p-article-btn__item">
                          <a onClick={showModalNotify} className="btn-default btn-yellow btn-pdf btn-r8 btn-h48">再通知</a>
                        </li>
                      </ul>
                    
                      <div className="p-article__context">
    
                        <div className="p-file-list">
                          <div className="p-file-for">
                              <figure>
                              {
                                  thumbnail && 
                                  <img src={thumbnail} alt="thumbnail"/>
                              }
                              </figure>
                          </div>
                          <div className="p-file-nav">
                            { 
                              meeting?.meeting_image.map((v, inx) => 
                                <figure onClick={() => setThumbnail(v.image)}  key={inx}>
                                  <img src={v.image} alt="" />
                                </figure> 
                              ) 
                            }
                            {
                              [...Array(10-meeting.meeting_image.length)].map((x, k)=>
                                <figure key={k}></figure>
                              )
                            }
                          </div>
                        </div>

                        <div className="p-article__pdf">
                          <div className="p-article__pdf__btn">
                            <a 
                                onClick={e => {
                                  e.preventDefault();
                                  setShowPdf(true); 
                                }} 
                                className="btn-default btn-yellow btn-pdf btn-r8 btn-h52">
                              <span>PDFを確認する</span>
                            </a>
                          </div>
                          <button type="button" onClick={showModalMemo}  
                            aria-label="メモ" 
                            data-tooltip="メモ" 
                            aria-pressed="false" 
                            style={{marginRight:10}} 
                            className="icon a-icon text-icon icon-text icon-starFill-wrap a-icon-size_medium"></button>
                          <button type="button" 
                            onClick={e => {
                              e.preventDefault();
                              handleFavorite(meeting.id, meeting.is_favorite);
                            }} 
                            aria-label="お気に入り" data-tooltip="お気に入り" aria-pressed="false" className={`icon a-icon like-icon  ${meeting.is_favorite == 1 ? "icon-starFill icon-starFill-wrap" : "icon-star icon-star-wrap"} a-icon-size_medium`}></button>
                        </div>
                    
                        <p className="p-article__txt">{ meeting.text }</p>
                      </div>
                    </div>
                  </article>
                </div>
              </div>
            </div>
          }
        </div>
        <ModalSettingNotify 
          show={showSettingNotify}
          meetingId={meeting.id}
          handleClose={()=>setShowSettingNotify(false)} 
          // handleAccept={handleAccept} 
        />
        <ModalMemo 
          show={showMemo}
          title={"メモ"}
          content={meeting?.memo}
          handleClose={handleCloseMemo} 
        />
        <ModalConfirm 
          show={showConfirm} 
          message={"本当に削除しても\nよろしいでしょうか？"}
          handleClose={handleCloseConfirm} 
          handleAccept={handleAcceptDelete} 
          loading={submit}
        />
        <ModalConfirm 
          show={showNotify} 
          message={"本当に再通知しても\nよろしいでしょうか？"}
          handleClose={handleCloseNotify} 
          handleAccept={handleAcceptNotify} 
        />
        <ModalPdf 
          show={showPdf}
          pdfPath={meeting.pdf ?? '/pdf/test.pdf'}
          handleClose={handleClosePdf} 
        />
        { _400error && <Alert type="fail">{_400error}</Alert> }
        {
            _success_delete && 
            <Alert type="success" 
                hide={()=>  
                history.push({
                pathname: "/p-account/meeting",
                state: {}
            })}>{_success_delete}</Alert>
        }
      </div>  
	)
}

export default MeetingDetail;