import React, {useState, useEffect, useRef} from 'react';
import {Link, useNavigate, useLocation, useParams} from 'react-router-dom';
import Modal from "react-bootstrap/Modal";

import * as EgovNet from 'api/egovFetch';
import URL from 'constants/url';
import CODE from 'constants/code';

import {default as EgovLeftNav} from 'components/leftmenu/EgovLeftNavAdmin';
import EgovRadioButtonGroup from 'components/EgovRadioButtonGroup';
import {Form} from "react-bootstrap";


function AboutSiteModal({props, reloadFunction}) {
    console.group("AboutSiteModal");
    console.log("[Start] AboutSiteModal ------------------------------");
    console.log("AboutSiteModal [props] : ", props);

    const navigate = useNavigate();
    const location = useLocation();
    const checkRef = useRef([]);
    const fileInputRef = useRef(null);

    console.log("AboutSiteModal [location] : ", location);

    let item = null;
    item = props;
    console.log("@@@ item : " + JSON.stringify(item));

    const [modeInfo, setModeInfo] = useState(item != null ? {mode: props.mode} : {mode: CODE.MODE_CREATE});
    const [boardDetail, setBoardDetail] = useState({});
    console.log("@@@ mode : " + modeInfo.mode);

    useEffect(() => {
        initMode();
        const fileDOM = document.querySelector('#file');
        const preview = document.querySelector('.preview');

        if(fileDOM) {
            fileDOM.addEventListener('change', () => {
                const reader = new FileReader();
                reader.onload = ({target}) => {
                    preview.src = target.result;
                };
                reader.readAsDataURL(fileDOM.files[0]);
            });
        }
    }, []);

    const initMode = () => {
        if (modeInfo.mode === CODE.MODE_MODIFY) {
            setBoardDetail(item);
        }
    }

    function editPartnerSite(e) {
        e.preventDefault();
        e.stopPropagation();
        const form = e.target;
        const formData = new FormData(form); // 새 FormData 객체 생성

        // FormData 객체에 파일 데이터 추가
        console.log("@@@ current : " + fileInputRef.current);
        console.log("@@@ file : " + fileInputRef.current.files[0]);
        formData.append('file', currentFile);

        if (modeInfo.mode === CODE.MODE_MODIFY) {
            formData.append('siteSeq', props.siteSeq); // 수정 모드일 때 필요한 추가 정보 추가
            formData.append('fileGrpId', props.fileGrpId);
        }
        EgovNet.requestFetch(
            '/admin/config/partner-site-mgt',
            {
                method: "PUT",
                body: formData
            },
            (resp) => {
                if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                    alert("저장되었습니다.");
                    reloadFunction();
                } else if (Number(resp.resultCode) === Number(CODE.RCV_ERROR_AUTH)) {
                    console.log("토큰 갱신중.")
                } else {
                    alert(resp.result.resultMessage)
                }
            }
        )
    }

    function deletePartnerSite(partnerSite){
        if(window.confirm("삭제하시겠습니까?")) {
            EgovNet.requestFetch(
                '/admin/config/partner-site-mgt',
                {
                    method: "DELETE",
                    headers: {
                        'Content-type': 'application/json'
                    },
                    body: JSON.stringify(partnerSite)
                },
                (resp) => {
                    if (Number(resp.resultCode) === Number(CODE.RCV_SUCCESS)) {
                        alert("삭제되었습니다.")
                        reloadFunction();
                    } else if (Number(resp.resultCode) === Number(CODE.RCV_ERROR_AUTH)) {
                        console.log("토큰 갱신중.")
                    } else {
                        alert(resp.result.resultMessage)
                    }
                }
            )
        }
    }

    const Logo = () => (
        <svg className="uploadIcon" x="0px" y="0px" viewBox="0 0 24 24">
            <path fill="transparent" d="M0,0h24v24H0V0z"/>
            <path fill="#000" d="M20.5,5.2l-1.4-1.7C18.9,3.2,18.5,3,18,3H6C5.5,3,5.1,3.2,4.8,3.5L3.5,5.2C3.2,5.6,3,6,3,6.5V19  c0,1.1,0.9,2,2,2h14c1.1,0,2-0.9,2-2V6.5C21,6,20.8,5.6,20.5,5.2z M12,17.5L6.5,12H10v-2h4v2h3.5L12,17.5z M5.1,5l0.8-1h12l0.9,1  H5.1z"/>
        </svg>
    )

    const [currentFile, setCurrentFile] = useState(null);
    const [uploadedInfo, setUploadedInfo] = useState(null);
    const [previewImage, setPreviewImage] = useState(null);

    const UploadBox = () => {
        const [isActive, setActive] = useState(false);

        const onDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
            e.preventDefault();
            e.stopPropagation();
        };
        const onDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
            e.preventDefault();
            e.stopPropagation();
        };
        const onDragOver = (e: React.DragEvent<HTMLDivElement>) => {
            e.preventDefault();
            e.stopPropagation();
        };

        const setFileInfo = (file) => {
            const { name, size: byteSize, type } = file;
            const isImage = type.includes('image');
            const size = (byteSize / (1024 * 1024)).toFixed(2) + 'mb';
            setUploadedInfo({ name, size, type }); // name, size, type 정보를 uploadedInfo에 저장

            if (!isImage) {
                setUploadedInfo({ name, size, type });
                return;
            }
            const reader = new FileReader();
            reader.onload = () => {
                setPreviewImage(reader.result);
                setUploadedInfo({ name, size, type, imageUrl: String(reader.result) });
            };
            reader.readAsDataURL(file);
        };

        const onDrop = (e: React.DragEvent<HTMLDivElement>) => {
            e.preventDefault();
            e.stopPropagation();
            setActive(false);

            const droppedFile = e.dataTransfer.files[0];
            console.log("@@@ handleDrop file : " + droppedFile);
            if (droppedFile.type.startsWith('image/')) {
                setCurrentFile(droppedFile);
                setFileInfo(droppedFile);
            } else {
                // 이미지 파일이 아닌 경우에 대한 처리
                alert('이미지 파일만 업로드할 수 있습니다.');
            }
        };

        const handleUpload = (e: ChangeEvent<HTMLInputElement>) => {
            const file = e.target.files[0];
            console.log("@@@ handleUpload file : " + file);
            if (file.type.startsWith('image/')) {
                setCurrentFile(file);
                setFileInfo(file);
            } else {
                // 이미지 파일이 아닌 경우에 대한 처리
                alert('이미지 파일만 업로드할 수 있습니다.');
            }
        };

        return (
            <label
                className={`preview${isActive ? ' active' : ''}`}
                onDragEnter={onDragEnter}
                onDragOver={onDragOver}
                onDragLeave={onDragLeave}
                onDrop={onDrop}
            >
                <input type="file" className="file" onChange={handleUpload} ref={fileInputRef} />
                {previewImage && <img src={previewImage} alt="Preview Image" className="preview_image" />}
                {!uploadedInfo && (
                    <>
                        <Logo />
                        <p className="preview_msg">클릭 혹은 파일을 이곳에 드롭하세요.</p>
                        <p className="preview_desc">파일당 최대 3MB</p>
                    </>
                )}
            </label>
        );
    };

    console.log("------------------------------AboutSiteModal [End]");
    console.groupEnd("AboutSiteModal");

    const defaultUseYn = props?.useYn ? props.useYn : "Y";

    return (
        <>
            {/* <!-- 본문 --> */}
            <Modal.Header closeButton>
                <Modal.Title>
                    {modeInfo.mode === CODE.MODE_CREATE && '관련사이트 생성'}
                    {modeInfo.mode === CODE.MODE_MODIFY && '관련사이트 수정'}
                </Modal.Title>
            </Modal.Header>

            <Modal.Body>
                <UploadBox/>
                <div className="board_view2">
                    <Form onSubmit={(e) => {editPartnerSite(e)}} noValidate>
                        <dl>
                            <dt><label htmlFor="siteTitle">사이트명</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_input2 w_full" type="text" name="siteTitle" placeholder="사이트명" required
                                              defaultValue={props?.siteTitle} readOnly={props!==undefined}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="siteUrl">URL</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_input2 w_full" type="text" name="siteUrl" placeholder="URL" required
                                              defaultValue={props?.siteUrl}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="siteOrder">정렬순서</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Control className="f_txtar w_full" type="text" name="siteOrder" placeholder="정렬순서" required
                                              defaultValue={props?.siteOrder}/>
                            </dd>
                        </dl>
                        <dl>
                            <dt><label htmlFor="useYn">사용여부</label><span className="req">필수</span></dt>
                            <dd>
                                <Form.Check inline type="radio" label="Y" name="useYn" value="Y" defaultChecked={defaultUseYn === "Y"}/>
                                <Form.Check inline type="radio" label="N" name="useYn" value="N" defaultChecked={defaultUseYn === "N"}/>
                            </dd>
                        </dl>

                        {/* <!-- 버튼영역 --> */}
                        <div className="board_btn_area">
                            <div className="left_col btn1">
                                <button type="submit" className="btn btn_skyblue_h46 w_100">저장
                                </button>
                                {modeInfo.mode === CODE.MODE_MODIFY &&
                                <button type={"button"} className="btn btn_skyblue_h46 w_100" onClick={()=>{deletePartnerSite(props)}}>삭제</button>
                                }
                            </div>

                            <div className="right_col btn1">
                                <button type={"button"} className="btn btn_blue_h46 w_100" onClick={()=>{reloadFunction()}}>목록</button>
                            </div>
                        </div>
                        {/* <!--// 버튼영역 --> */}
                    </Form>
                </div>
            </Modal.Body>
        </>

    );
}

export default AboutSiteModal;