import { useState, useCallback } from 'react';
import { Link, useNavigate } from "react-router-dom";
import Slider from '../../common/Slider';
import useShipStore from '../../../stores/shipStore';
import {
    SIGNAL_SOURCE_CODE_AIS,
    SIGNAL_SOURCE_CODE_ENAV,
    SIGNAL_SOURCE_CODE_VPASS,
    SIGNAL_SOURCE_CODE_VTS_AIS,
    SIGNAL_SOURCE_CODE_D_MF_HF,
    SIGNAL_SOURCE_CODE_RADAR,
    SIGNAL_KIND_CODE_FISHING,
    SIGNAL_KIND_CODE_PASSENGER,
    SIGNAL_KIND_CODE_CARGO,
    SIGNAL_KIND_CODE_TANKER,
    SIGNAL_KIND_CODE_GOV,
    SIGNAL_KIND_CODE_KCGV,
    SIGNAL_KIND_CODE_NORMAL,
    SIGNAL_KIND_CODE_BUOY,
    NATIONAL_CODE_KR,
    NATIONAL_CODE_CN,
    NATIONAL_CODE_JP,
    NATIONAL_CODE_KP,
    NATIONAL_CODE_OTHER,
} from '../../../types/constants';

// 신호원 필터 매핑
const SIGNAL_FILTERS = [
    { code: SIGNAL_SOURCE_CODE_AIS, label: 'AIS' },
    { code: SIGNAL_SOURCE_CODE_ENAV, label: 'E-NAV' },
    { code: SIGNAL_SOURCE_CODE_VPASS, label: 'V-PASS' },
    { code: SIGNAL_SOURCE_CODE_VTS_AIS, label: 'VTS_AIS' },
    { code: SIGNAL_SOURCE_CODE_D_MF_HF, label: 'D_MF_HF' },
    { code: SIGNAL_SOURCE_CODE_RADAR, label: 'VTS_RADAR' },
];

// 선종 필터 매핑
const KIND_FILTERS = [
    { code: SIGNAL_KIND_CODE_FISHING, label: '어선' },
    { code: SIGNAL_KIND_CODE_PASSENGER, label: '여객선' },
    { code: SIGNAL_KIND_CODE_CARGO, label: '화물선' },
    { code: SIGNAL_KIND_CODE_TANKER, label: '유조선' },
    { code: SIGNAL_KIND_CODE_GOV, label: '관공선' },
    { code: SIGNAL_KIND_CODE_KCGV, label: '함정' },
    { code: SIGNAL_KIND_CODE_NORMAL, label: '기타' },
    { code: SIGNAL_KIND_CODE_BUOY, label: '어망/부이' },
];

// 국적 필터 매핑
const NATIONAL_FILTERS = [
    { code: NATIONAL_CODE_KR, label: '한국' },
    { code: NATIONAL_CODE_CN, label: '중국' },
    { code: NATIONAL_CODE_JP, label: '일본' },
    { code: NATIONAL_CODE_KP, label: '북한' },
    { code: NATIONAL_CODE_OTHER, label: '기타' },
];

export default function DisplayComponent({ isOpen, onToggle }) {
    const navigate = useNavigate();

    // 스토어 연결
    const {
        sourceVisibility,
        kindVisibility,
        nationalVisibility,
        darkSignalVisible,
        darkSignalCount,
        toggleSourceVisibility,
        toggleKindVisibility,
        toggleNationalVisibility,
        toggleDarkSignalVisible,
        clearDarkSignals,
    } = useShipStore();

    // 투명도
    const [opacity, setOpacity] = useState(70);

    // 아코디언
    const [isAccordionOpen1, setIsAccordionOpen1] = useState(true); // 신호
    const [isAccordionOpen2, setIsAccordionOpen2] = useState(true); // 선종
    const [isAccordionOpen3, setIsAccordionOpen3] = useState(true); // 국적
    const [isAccordionOpen4, setIsAccordionOpen4] = useState(false); // AI 모드

    const toggleAccordion1 = () => setIsAccordionOpen1(prev => !prev);
    const toggleAccordion2 = () => setIsAccordionOpen2(prev => !prev);
    const toggleAccordion3 = () => setIsAccordionOpen3(prev => !prev);
    const toggleAccordion4 = () => setIsAccordionOpen4(prev => !prev);

    // 신호 전체 On/Off
    const isAllSignalsOn = SIGNAL_FILTERS.every(f => sourceVisibility[f.code]);
    const toggleAllSignals = useCallback(() => {
        SIGNAL_FILTERS.forEach(f => {
            if (isAllSignalsOn) {
                // 모두 켜져있으면 모두 끄기
                if (sourceVisibility[f.code]) toggleSourceVisibility(f.code);
            } else {
                // 하나라도 꺼져있으면 모두 켜기
                if (!sourceVisibility[f.code]) toggleSourceVisibility(f.code);
            }
        });
    }, [isAllSignalsOn, sourceVisibility, toggleSourceVisibility]);

    // 선종 전체 On/Off
    const isAllKindsOn = KIND_FILTERS.every(f => kindVisibility[f.code]);
    const toggleAllKinds = useCallback(() => {
        KIND_FILTERS.forEach(f => {
            if (isAllKindsOn) {
                if (kindVisibility[f.code]) toggleKindVisibility(f.code);
            } else {
                if (!kindVisibility[f.code]) toggleKindVisibility(f.code);
            }
        });
    }, [isAllKindsOn, kindVisibility, toggleKindVisibility]);

    // 국적 전체 On/Off
    const isAllNationalsOn = NATIONAL_FILTERS.every(f => nationalVisibility[f.code]);
    const toggleAllNationals = useCallback(() => {
        NATIONAL_FILTERS.forEach(f => {
            if (isAllNationalsOn) {
                if (nationalVisibility[f.code]) toggleNationalVisibility(f.code);
            } else {
                if (!nationalVisibility[f.code]) toggleNationalVisibility(f.code);
            }
        });
    }, [isAllNationalsOn, nationalVisibility, toggleNationalVisibility]);

    // 탭이동
    const [activeTab, setActiveTab] = useState('filter');

    const tabs = [
        { id: 'filter', label: '필터' },
        { id: 'layer', label: '레이어' },
    ];
    return (
        <aside className={`slidePanel ${!isOpen ? 'is-closed' : ''}`}>
        {/* 탭 버튼 */}
        <div className="tabBox p0">
            <div className="tabDefault borderLess">
            {tabs.map(tab => (
                <button
                key={tab.id}
                type="button"
                className={activeTab === tab.id ? 'on' : ''}
                onClick={() => setActiveTab(tab.id)}
                >
                {tab.label}
                </button>
            ))}
            </div>
        </div>

        {/* 탭 콘텐츠 01 */}
        <div className={`tabWrap scrollY ${activeTab === 'filter' ? 'is-active' : ''}`}>

            <div className="tabWrapInner">
                <div className="tabWrapCnt">

                    {/* 스위치그룹 01 - 신호 */}
                    <div className="switchGroup">
                        <div className="sgHeader">
                            <div className="colL">
                                <span>신호</span>
                                <label className="switch">
                                    <input
                                        type="checkbox"
                                        aria-label="신호"
                                        checked={isAllSignalsOn}
                                        onChange={toggleAllSignals}
                                    />
                                    <span></span>
                                </label>
                            </div>
                            <button
                                type="button"
                                className={`toggleBtn ${isAccordionOpen1 ? 'is-open' : ''}`}
                                aria-expanded={isAccordionOpen1}
                                onClick={toggleAccordion1}
                            ></button>
                        </div>
                        {/* 여기서부터 토글 */}
                        <div className={`switchBox ${isAccordionOpen1 ? 'is-open' : ''}`}>
                            <ul className="switchList">
                                {SIGNAL_FILTERS.map(({ code, label }) => (
                                    <li key={code}>
                                        <span>{label}</span>
                                        <label className="switch sm">
                                            <input
                                                type="checkbox"
                                                aria-label={label}
                                                checked={sourceVisibility[code] || false}
                                                onChange={() => toggleSourceVisibility(code)}
                                            />
                                            <span></span>
                                        </label>
                                    </li>
                                ))}
                            </ul>
                        </div>
                        {/* 여기까지 */}
                    </div>

                    {/* 스위치그룹 02 - 선종 */}
                    <div className="switchGroup">
                        <div className="sgHeader">
                            <div className="colL">
                                <span>선종/기종</span>
                                <label className="switch">
                                    <input
                                        type="checkbox"
                                        aria-label="선종/기종"
                                        checked={isAllKindsOn}
                                        onChange={toggleAllKinds}
                                    />
                                    <span></span>
                                </label>
                            </div>
                            <button
                                type="button"
                                className={`toggleBtn ${isAccordionOpen2 ? 'is-open' : ''}`}
                                aria-expanded={isAccordionOpen2}
                                onClick={toggleAccordion2}
                            ></button>
                        </div>
                        {/* 여기서부터 토글 */}
                        <div className={`switchBox ${isAccordionOpen2 ? 'is-open' : ''}`}>
                            <ul className="switchList">
                                {KIND_FILTERS.map(({ code, label }) => (
                                    <li key={code}>
                                        <span>{label}</span>
                                        <label className="switch sm">
                                            <input
                                                type="checkbox"
                                                aria-label={label}
                                                checked={kindVisibility[code] || false}
                                                onChange={() => toggleKindVisibility(code)}
                                            />
                                            <span></span>
                                        </label>
                                    </li>
                                ))}
                            </ul>
                        </div>
                        {/* 여기까지 */}
                    </div>

                    {/* 스위치그룹 03 - 국적 */}
                    <div className="switchGroup">
                        <div className="sgHeader">
                            <div className="colL">
                                <span>국적</span>
                                <label className="switch">
                                    <input
                                        type="checkbox"
                                        aria-label="국적"
                                        checked={isAllNationalsOn}
                                        onChange={toggleAllNationals}
                                    />
                                    <span></span>
                                </label>
                            </div>
                            <button
                                type="button"
                                className={`toggleBtn ${isAccordionOpen3 ? 'is-open' : ''}`}
                                aria-expanded={isAccordionOpen3}
                                onClick={toggleAccordion3}
                            ></button>
                        </div>
                        {/* 여기서부터 토글 */}
                        <div className={`switchBox ${isAccordionOpen3 ? 'is-open' : ''}`}>
                            <ul className="switchList">
                                {NATIONAL_FILTERS.map(({ code, label }) => (
                                    <li key={code}>
                                        <span>{label}</span>
                                        <label className="switch sm">
                                            <input
                                                type="checkbox"
                                                aria-label={label}
                                                checked={nationalVisibility[code] || false}
                                                onChange={() => toggleNationalVisibility(code)}
                                            />
                                            <span></span>
                                        </label>
                                    </li>
                                ))}
                            </ul>
                        </div>
                        {/* 여기까지 */}
                    </div>
                    {/* 스위치그룹 04 */}
                    <div className="switchGroup">
                        <div className="sgHeader">
                            <div className="colL">
                                <span>AI 모드</span>
                                <label className="switch"> <input type="checkbox" aria-label="AI 모드" /> <span></span></label>
                            </div>
                            <button
                                type="button"
                                className={`toggleBtn ${isAccordionOpen4 ? 'is-open' : ''}`}
                                aria-expanded={isAccordionOpen4}
                                onClick={toggleAccordion4}
                                ></button>
                        </div>
                        {/* 여기서부터 토글 */}
                        <div className={`switchBox ${isAccordionOpen4 ? 'is-open' : ''}`}>
                        <ul className="switchList">
                            <li>
                                <span>MMSI 변조</span>
                                <label className="switch sm"> <input type="checkbox" aria-label="MMSI 변조" /> <span></span></label>
                            </li>
                            <li>
                                <span>중국 허가선박</span>
                                <label className="switch sm"> <input type="checkbox" aria-label="중국 허가선박" /> <span></span></label>
                            </li>
                            <li>
                                <span>관공선</span>
                                <label className="switch sm"> <input type="checkbox" aria-label="관공선" /> <span></span></label>
                            </li>
                            <li>
                                <span>비정상 접촉</span>
                                <label className="switch sm"> <input type="checkbox" aria-label="비정상 접촉" /> <span></span></label>
                            </li>
                            <li>
                                <span>비정상 선박</span>
                                <label className="switch sm"> <input type="checkbox" aria-label="비정상 선박" /> <span></span></label>
                            </li>
                            <li>
                                <span>북한선박</span>
                                <label className="switch sm"> <input type="checkbox" aria-label="북한선박" /> <span></span></label>
                            </li>
                        </ul>
                        </div>
                        {/* 여기까지 */}
                    </div>

                    {/* 스위치그룹 05 - 다크시그널 */}
                    <div className="switchGroup">
                        <div className="sgHeader">
                            <div className="colL">
                                <span>다크시그널</span>
                                {darkSignalCount > 0 && <span className="count">({darkSignalCount})</span>}
                                {darkSignalCount > 0 && (
                                    <button
                                        type="button"
                                        className="btnDelDark"
                                        onClick={clearDarkSignals}
                                        title="다크시그널 삭제"
                                    >
                                        삭제
                                    </button>
                                )}
                            </div>
                            <label className="switch">
                                <input
                                    type="checkbox"
                                    aria-label="다크시그널"
                                    checked={darkSignalVisible}
                                    onChange={toggleDarkSignalVisible}
                                />
                                <span></span>
                            </label>
                        </div>
                    </div>

                    {/* 스위치그룹 06 */}
                    <div className="switchGroup">
                        <div className="sgHeader">
                            <div className="colL">
                                <span>위험물</span>
                            </div>
                            <label className="switch"> <input type="checkbox" aria-label="위험물" /> <span></span></label>
                        </div>
                    </div>

                    {/* 스위치그룹 07 */}
                    <div className="switchGroup">
                        <div className="sgHeader">
                            <div className="colL">
                                <i className="favship"></i>
                                <span>관심선박</span>
                            </div>
                            <label className="switch"> <input type="checkbox" aria-label="관심선박" /> <span></span></label>
                        </div>
                    </div>
                </div>

                {/* 버튼영역 */}
                <div className="btnBox">
                    <button type="button" className="btn btnLine">저장</button>
                </div>
            </div>
        </div>

        {/* 탭 콘텐츠 02 */}
        <div className={`tabWrap ${activeTab === 'layer' ? 'is-active' : ''}`}>
            <div className="tabTop">
                <div className="title">레이어</div>
            </div>

            <div className="tabBtm noLine">
                <div className="tabBtmInner">
                    <ul className="lineList tabBtmCnt">
                        <li className="rowSB">
                            <label className="checkbox checkL">
                                <input type="checkbox" />
                                <span>배경지도</span>
                            </label>
                            <div className="row">
                                <span>투명도 조절</span>
                                <div>
                                <Slider label="투명도 조절" />
                                </div>
                            </div>
                        </li>
                        <li className="p0">
                            <ul className="optionList">
                                <li>
                                    <span>전자해도</span>
                                    <label className="radio"> <input type="radio" name="map" aria-label="전자해도" /> <span></span></label>
                                </li>
                                <li>
                                    <span>일반지도</span>
                                    <label className="radio"> <input type="radio" name="map" aria-label="일반지도" /> <span></span></label>
                                </li>
                                <li>
                                    <span>영상지도</span>
                                    <label className="radio"> <input type="radio" name="map" aria-label="영상지도" /> <span></span></label>
                                </li>
                            </ul>
                        </li>
                        <li>
                            <label className="checkbox checkL">
                                <input type="checkbox" />
                                <span>해경관할구역</span>
                            </label>
                        </li>
                        <li>
                            <label className="checkbox checkL">
                                <input type="checkbox" />
                                <span>검문검색위치</span>
                            </label>
                        </li>
                    </ul>
                    <div className='btnBox'>
                        <button 
                        type="button" 
                        className="btn btnLine w15r"
                        onClick={() => navigate("/display/layer/register")}
                        >레이어 등록</button>
                    </div>
                </div>
            </div>
        </div>

        {/* 사이드패널 토글버튼 */}
        <button
            type="button"
            className="toogle"
            aria-expanded={isOpen}
            onClick={onToggle}
        >
            <span className="blind">
            {isOpen ? '패널 접기' : '패널 열기'}
            </span>
        </button>
        </aside>
    );
}
