import { useState } from 'react';
import type { EncMapSettings } from '../model/types';
import { DEFAULT_ENC_MAP_SETTINGS, ENC_DEPTH_COLOR_TARGETS } from '../model/types';

interface EncMapSettingsPanelProps {
  value: EncMapSettings;
  onChange: (next: EncMapSettings) => void;
}

const SYMBOL_TOGGLES: { key: keyof EncMapSettings; label: string }[] = [
  { key: 'showBuoys', label: '부표' },
  { key: 'showBeacons', label: '비콘' },
  { key: 'showLights', label: '등대' },
  { key: 'showDangers', label: '위험물' },
  { key: 'showLandmarks', label: '랜드마크' },
  { key: 'showSoundings', label: '수심' },
  { key: 'showPilot', label: '도선소' },
  { key: 'showAnchorage', label: '정박지' },
  { key: 'showRestricted', label: '제한구역' },
  { key: 'showDredged', label: '준설구역' },
  { key: 'showTSS', label: '통항분리대' },
  { key: 'showContours', label: '등심선' },
];

const AREA_COLOR_INPUTS: { key: keyof EncMapSettings; label: string }[] = [
  { key: 'backgroundColor', label: '바다 배경' },
  { key: 'landColor', label: '육지' },
  { key: 'coastlineColor', label: '해안선' },
];

export function EncMapSettingsPanel({ value, onChange }: EncMapSettingsPanelProps) {
  const [open, setOpen] = useState(false);

  const update = <K extends keyof EncMapSettings>(key: K, val: EncMapSettings[K]) => {
    onChange({ ...value, [key]: val });
  };

  const isDefault = JSON.stringify(value) === JSON.stringify(DEFAULT_ENC_MAP_SETTINGS);

  const allChecked = SYMBOL_TOGGLES.every(({ key }) => value[key] as boolean);
  const toggleAll = (checked: boolean) => {
    const next = { ...value };
    for (const { key } of SYMBOL_TOGGLES) {
      (next as Record<string, unknown>)[key] = checked;
    }
    onChange(next);
  };

  return (
    <>
      <button
        className={`map-settings-gear${open ? ' open' : ''}`}
        onClick={() => setOpen((p) => !p)}
        title="ENC 설정"
        type="button"
      >
        ⚙
      </button>

      {open && (
        <div className="map-settings-panel">
          <div className="ms-title">
            ENC 설정
            {!isDefault && (
              <button
                className="ms-reset-btn"
                onClick={() => onChange(DEFAULT_ENC_MAP_SETTINGS)}
                title="기본값 복원"
                type="button"
              >
                초기화
              </button>
            )}
          </div>

          {/* ── 레이어 토글 ── */}
          <div className="ms-section">
            <div className="ms-label">
              레이어 표시
              <label className="ms-toggle-item ms-toggle-all">
                <input
                  type="checkbox"
                  checked={allChecked}
                  onChange={(e) => toggleAll(e.target.checked)}
                />
                <span>전체</span>
              </label>
            </div>
            <div className="ms-toggle-grid">
              {SYMBOL_TOGGLES.map(({ key, label }) => (
                <label key={key} className="ms-toggle-item">
                  <input
                    type="checkbox"
                    checked={value[key] as boolean}
                    onChange={(e) => update(key, e.target.checked as never)}
                  />
                  <span>{label}</span>
                </label>
              ))}
            </div>
          </div>

          {/* ── 영역 색상 ── */}
          <div className="ms-section">
            <div className="ms-label">영역 색상</div>
            {AREA_COLOR_INPUTS.map(({ key, label }) => (
              <div key={key} className="ms-color-row">
                <span>{label}</span>
                <input
                  type="color"
                  value={value[key] as string}
                  onChange={(e) => update(key, e.target.value as never)}
                  title={label}
                />
              </div>
            ))}
          </div>

          {/* ── 수심별 색상 ── */}
          <div className="ms-section">
            <div className="ms-label">수심 색상</div>
            {ENC_DEPTH_COLOR_TARGETS.map(({ key, label }) => (
              <div key={key} className="ms-color-row">
                <span>{label}</span>
                <input
                  type="color"
                  value={value[key] as string}
                  onChange={(e) => update(key, e.target.value as never)}
                  title={label}
                />
              </div>
            ))}
          </div>
        </div>
      )}
    </>
  );
}
