import React, {useEffect, useState} from "react";
import Modal from "react-bootstrap/Modal";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import Form from "react-bootstrap/Form";
import Table from "react-bootstrap/Table";
import * as EgovNet from "api/egovFetch";
import CODE from "../../../../constants/code";

function QuestionModal({svySeq}){

    const [qtList, setQtList] = useState([]);
    const [selectedQt, setSelectedQt] = useState(null);
    const [tempSeq, setTempSeq] = useState(1);

    function getSurveyQt(){
        EgovNet.requestFetch(
            '/admin/survey/info-qt?svySeq='+svySeq,
            {
                method: "GET"
            },
            (resp) => {
                setQtList(resp.result.qtList)
            },
            function (resp) {
                console.log("err response : ", resp);
            }
        );
    }

    function addQt(){
        const temp = [...qtList]
        temp.push({
            qtSeq: null,
            tempSeq: tempSeq,
            svySeq: svySeq,
            qtTitle: '',
            qtDesc: '',
            qtType: '',
            maxNo: '',
            etcYn: '',
            itemList:[]
        })
        setQtList(temp);
        setTempSeq(tempSeq+1);
    }

    function qtOptionChange(target, value){
        const temp = {...selectedQt}
        temp[target] = value;
        setSelectedQt(temp);
    }

    function addItem(){
        const temp = {...selectedQt}
        temp.itemList.push({
            qtItemSeq: null,
            qtSeq:null,
            itemNm: null,
            questionYn:'Y'
        })
        setSelectedQt(temp);
    }

    function removeQt(index){
        const temp = [...qtList]
        temp.splice(index, 1);
        setQtList(temp);
        setSelectedQt(null)
    }

    function removeItem(index){
        const temp = {...selectedQt}
        temp.itemList.splice(index, 1)
        setSelectedQt(temp)
    }

    function editSurveyQt(e){
        EgovNet.requestFetch(
            '/admin/survey/info-qt',
            {
                method: "PUT",
                headers: {
                    'Content-type': 'application/json'
                },
                body: JSON.stringify(qtList)
            },
            (resp) => {
                if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                    alert("저장되었습니다.")
                }else{
                    alert(resp.resultMessage)
                }
            }
        )
    }

    useEffect(() => {
        getSurveyQt()
    }, []);

    useEffect(() => {
        const tempQt = [...qtList];
        tempQt.forEach(function (qt, index){
            if(qt.qtSeq === null){
                if(qt.tempSeq === selectedQt?.tempSeq){
                    tempQt[index] = selectedQt;
                }
            }else if(qt.qtSeq === selectedQt?.qtSeq){
                tempQt[index] = selectedQt;
            }
        })
        setQtList(tempQt);
    }, [selectedQt]);

    useEffect(() => {

    }, [qtList]);

    return (
        <>
            <Modal.Header closeButton>
                <Modal.Title>질문관리</Modal.Title>
            </Modal.Header>
            <Modal.Body>
                <Row>
                    <Col xs={5}>
                        <Table>
                            <colgroup>
                                <col/>
                                <col className={"w_100"}/>
                            </colgroup>
                            <thead>
                            <tr>
                                <th>질문</th>
                                <th>삭제</th>
                            </tr>
                            </thead>
                            <tbody>
                            {qtList.map((qt, index)=>{
                                return (
                                    <tr onClick={()=>setSelectedQt({...qt})}>
                                        <td>
                                            <Form.Control type={"text"} defaultValue={qt.qtTitle} value={qt.qtTitle}
                                                          onChange={(e)=>{
                                                              qt.qtTitle = e.target.value
                                                              setSelectedQt({...qt})
                                                          }} />
                                        </td>
                                        <td>
                                            <button className={"btn btn_red_h31"} onClick={()=>removeQt(index)}>삭제</button>
                                        </td>
                                    </tr>
                                );
                            })}
                            </tbody>
                            <tfoot>
                            <tr>
                                <td colSpan={2}>
                                    <button className={"btn btn_blue_h31"} onClick={addQt}>추가</button>
                                </td>
                            </tr>
                            </tfoot>
                        </Table>
                    </Col>
                    <Col xs={7} className={selectedQt?"":"d-none"}>
                        <Form.Group as={Row} className="mb-3">
                            <Form.Label column sm={3}>
                                질문유형
                            </Form.Label>
                            <Col sm={9} key={`inline-radio`} className={'my-auto'}>
                                <Form.Check inline label="체크박스" name="qtType" type={'radio'} value={1}
                                            checked={selectedQt?.qtType === 1} defaultChecked={selectedQt?.qtType === 1}
                                            onClick={(e)=>{
                                                qtOptionChange("qtType", Number(e.target.value));
                                            }}/>
                                <Form.Check inline label="라디오버튼" name="qtType" type={'radio'} value={2}
                                            checked={selectedQt?.qtType === 2} defaultChecked={selectedQt?.qtType === 2}
                                            onClick={(e)=>{
                                                qtOptionChange("qtType", Number(e.target.value));
                                            }}/>
                                <Form.Check inline label="직접입력" name="qtType" type={'radio'} value={3}
                                            checked={selectedQt?.qtType === 3} defaultChecked={selectedQt?.qtType === 3}
                                            onClick={(e)=>{
                                                qtOptionChange("qtType", Number(e.target.value));
                                            }}/>
                                <Form.Check inline label="이용자만족도" name="qtType" type={'radio'} value={4}
                                            checked={selectedQt?.qtType === 4} defaultChecked={selectedQt?.qtType === 4}
                                            onClick={(e)=>{
                                                qtOptionChange("qtType", Number(e.target.value));
                                            }}/>
                            </Col>
                        </Form.Group>
                        <Form.Group as={Row}>
                            <Form.Label column sm={3}>
                                설명
                            </Form.Label>
                            <Col sm={9}>
                                <Form.Control as={"textarea"} rows={3} name="qtDesc"
                                              defaultValue={selectedQt?.qtDesc?selectedQt?.qtDesc:''} value={selectedQt?.qtDesc?selectedQt?.qtDesc:''}
                                              onChange={(e)=>{
                                                  qtOptionChange("qtDesc", e.target.value);
                                              }}/>
                            </Col>
                        </Form.Group>
                        <Form.Group as={Row} className={`mb-3 ${selectedQt?.qtType!==1?'d-none':''}`}>
                            <Form.Label column sm={3}>
                                최대 선택 개수
                            </Form.Label>
                            <Col sm={3}>
                                <Form.Control type="text" name="maxNo"
                                              defaultValue={selectedQt?.maxNo} value={selectedQt?.maxNo}
                                              onChange={(e)=>{
                                                  qtOptionChange("maxNo", e.target.value);
                                              }}/>
                            </Col>
                            <Form.Label column sm={'auto'}>
                                기타 여부
                            </Form.Label>
                            <Col sm={3} className={'my-auto'}>
                                <Form.Check type="checkbox" name="etcYn"
                                            defaultChecked={selectedQt?.etcYn==='Y'} checked={selectedQt?.etcYn==='Y'}
                                            onClick={(e)=>{
                                                qtOptionChange("etcYn", e.target.checked?'Y':'N');
                                            }}/>
                            </Col>
                        </Form.Group>
                        <Table className={`mb-3 ${selectedQt?.qtType===3?'d-none':''}`}>
                            <colgroup>
                                <col/>
                                <col className={"w_50"}/>
                                <col className={"w_100"}/>
                            </colgroup>
                            <thead>
                            <tr>
                                <th>보기</th>
                                <th>응답</th>
                                <th>삭제</th>
                            </tr>
                            </thead>
                            <tbody>
                            {selectedQt?.itemList.map((item, index)=>{
                                return (
                                    <tr>
                                        <td>
                                            <Form.Control type={"text"} defaultValue={item.itemNm} value={item.itemNm}
                                                          onChange={(e)=>{
                                                              const qt = {...selectedQt}
                                                              qt.itemList[index].itemNm = e.target.value
                                                              setSelectedQt(qt);
                                                          }}/>
                                        </td>
                                        <td>
                                            <Form.Check type="checkbox" name="questionYn"
                                                        defaultChecked={item.questionYn==='Y'} checked={item.questionYn==='Y'}
                                                        onClick={(e)=>{
                                                            const qt = {...selectedQt}
                                                            qt.itemList[index].questionYn = e.target.checked?'Y':'N'
                                                            setSelectedQt(qt);
                                                        }}/>
                                        </td>
                                        <td>
                                            <button className={"btn btn_red_h31"} onClick={()=>removeItem(index)}>삭제</button>
                                        </td>
                                    </tr>
                                );
                            })}
                            </tbody>
                            <tfoot>
                            <tr>
                                <td colSpan={2}>
                                    <button className={"btn btn_blue_h31"} onClick={addItem}>추가</button>
                                </td>
                            </tr>
                            </tfoot>
                        </Table>
                    </Col>
                </Row>
            </Modal.Body>
            <Modal.Footer>
                <button type="button" className={"btn btn_blue_h31 px-3"} onClick={editSurveyQt}>저장</button>
            </Modal.Footer>
        </>
    );
}

export default QuestionModal;