import { useState } from 'react';
import type { OceanMapSettings, OceanLabelLanguage, OceanDepthLabelSize, OceanDepthStop } from '../model/types';
import { DEFAULT_OCEAN_MAP_SETTINGS, OCEAN_PRESET_DEPTH_STOPS } from '../model/types';

interface OceanMapSettingsPanelProps {
  value: OceanMapSettings;
  onChange: (next: OceanMapSettings) => void;
}

const LANGUAGES: { value: OceanLabelLanguage; label: string }[] = [
  { value: 'ko', label: '한국어' },
  { value: 'en', label: 'English' },
  { value: 'ja', label: '日本語' },
  { value: 'zh', label: '中文' },
  { value: 'local', label: '현지어' },
];

const FONT_SIZES: { value: OceanDepthLabelSize; label: string }[] = [
  { value: 'small', label: '소' },
  { value: 'medium', label: '중' },
  { value: 'large', label: '대' },
];

// 설정 패널에 표시할 주요 수심 구간 (전체 12개 중 6개만 UI 표시)
const DISPLAY_DEPTH_INDICES = [0, 2, 4, 6, 8, 11]; // -11000, -6000, -2000, -200, -50, 0

function depthLabel(depth: number): string {
  return `${Math.abs(depth).toLocaleString()}m`;
}

function hexToRgb(hex: string): [number, number, number] {
  return [
    parseInt(hex.slice(1, 3), 16),
    parseInt(hex.slice(3, 5), 16),
    parseInt(hex.slice(5, 7), 16),
  ];
}

function rgbToHex(r: number, g: number, b: number): string {
  return `#${[r, g, b].map((c) => Math.round(Math.max(0, Math.min(255, c))).toString(16).padStart(2, '0')).join('')}`;
}

function interpolateGradient(stops: OceanDepthStop[]): OceanDepthStop[] {
  if (stops.length < 2) return stops;
  const sorted = [...stops].sort((a, b) => a.depth - b.depth);
  const first = sorted[0];
  const last = sorted[sorted.length - 1];
  const [r1, g1, b1] = hexToRgb(first.color);
  const [r2, g2, b2] = hexToRgb(last.color);
  return sorted.map((stop, i) => {
    if (i === 0 || i === sorted.length - 1) return stop;
    const t = i / (sorted.length - 1);
    return {
      depth: stop.depth,
      color: rgbToHex(r1 + (r2 - r1) * t, g1 + (g2 - g1) * t, b1 + (b2 - b1) * t),
    };
  });
}

export function OceanMapSettingsPanel({ value, onChange }: OceanMapSettingsPanelProps) {
  const [open, setOpen] = useState(false);
  const [autoGradient, setAutoGradient] = useState(false);

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

  const updateDepthStop = (index: number, color: string) => {
    const next = value.depthStops.map((s, i) => (i === index ? { ...s, color } : s));
    if (autoGradient && (index === 0 || index === next.length - 1)) {
      update('depthStops', interpolateGradient(next));
    } else {
      update('depthStops', next);
    }
  };

  const toggleAutoGradient = () => {
    const next = !autoGradient;
    setAutoGradient(next);
    if (next) {
      update('depthStops', interpolateGradient(value.depthStops));
    }
  };

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

      {open && (
        <div className="map-settings-panel">
          <div className="ms-title">Ocean 지도 설정</div>

          {/* ── Language ──────────────────────────────── */}
          <div className="ms-section">
            <div className="ms-label">레이블 언어</div>
            <select
              value={value.labelLanguage}
              onChange={(e) => update('labelLanguage', e.target.value as OceanLabelLanguage)}
            >
              {LANGUAGES.map((l) => (
                <option key={l.value} value={l.value}>{l.label}</option>
              ))}
            </select>
          </div>

          {/* ── Depth gradient ────────────────────────── */}
          <div className="ms-section">
            <div className="ms-label" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              수심 구간 색상
              <span style={{ display: 'flex', gap: 4 }}>
                {value.depthStops.length > 0 && (
                  <span
                    className={`cursor-pointer rounded border px-1.5 py-px text-[8px] transition-all duration-150 select-none ${autoGradient ? 'border-wing-accent bg-wing-accent text-white' : 'border-wing-border bg-wing-card text-wing-muted'}`}
                    onClick={toggleAutoGradient}
                    title="최소/최대 색상 기준으로 중간 구간을 자동 보간합니다"
                  >
                    자동채우기
                  </span>
                )}
                <span
                  className={`cursor-pointer rounded border px-1.5 py-px text-[8px] transition-all duration-150 select-none ${value.depthStops.length > 0 ? 'border-wing-accent bg-wing-accent text-white' : 'border-wing-border bg-wing-card text-wing-muted'}`}
                  onClick={() => {
                    if (value.depthStops.length > 0) {
                      update('depthStops', []);
                      setAutoGradient(false);
                    } else {
                      update('depthStops', OCEAN_PRESET_DEPTH_STOPS);
                    }
                  }}
                  title={value.depthStops.length > 0 ? 'Ocean 스타일 네이티브 색상으로 복원' : '수심 구간별 색상을 직접 지정합니다'}
                >
                  {value.depthStops.length > 0 ? '기본값' : '커스텀'}
                </span>
              </span>
            </div>
            {value.depthStops.length === 0 ? (
              <div className="ms-row" style={{ fontSize: 9, color: 'var(--muted)' }}>
                기본 스타일 사용 중
              </div>
            ) : (
              DISPLAY_DEPTH_INDICES.map((idx) => {
                const stop = value.depthStops[idx];
                if (!stop) return null;
                const isEdge = idx === 0 || idx === value.depthStops.length - 1;
                const dimmed = autoGradient && !isEdge;
                return (
                  <div className="ms-row" key={stop.depth} style={dimmed ? { opacity: 0.5 } : undefined}>
                    <span className="ms-depth-label">{depthLabel(stop.depth)}</span>
                    <input
                      type="color"
                      className="ms-color-input"
                      value={stop.color}
                      onChange={(e) => updateDepthStop(idx, e.target.value)}
                      disabled={dimmed}
                    />
                    <span className="ms-hex">{stop.color}</span>
                  </div>
                );
              })
            )}
          </div>

          {/* ── Depth opacity ─────────────────────────── */}
          <div className="ms-section">
            <div className="ms-label">수심 투명도</div>
            <div className="ms-row">
              <input
                type="range"
                min={0}
                max={1}
                step={0.05}
                value={value.depthOpacity}
                onChange={(e) => update('depthOpacity', Number(e.target.value))}
                className="ms-slider"
              />
              <span className="ms-hex">{value.depthOpacity.toFixed(2)}</span>
            </div>
          </div>

          {/* ── Contour lines ─────────────────────────── */}
          <div className="ms-section">
            <div className="ms-label" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              등심선
              <span
                className={`cursor-pointer rounded border px-1.5 py-px text-[8px] transition-all duration-150 select-none ${value.contourVisible ? 'border-wing-accent bg-wing-accent text-white' : 'border-wing-border bg-wing-card text-wing-muted'}`}
                onClick={() => update('contourVisible', !value.contourVisible)}
              >
                {value.contourVisible ? 'ON' : 'OFF'}
              </span>
            </div>
            {value.contourVisible && (
              <>
                <div className="ms-row">
                  <span className="ms-depth-label">색상</span>
                  <input
                    type="color"
                    className="ms-color-input"
                    value={value.contourColor}
                    onChange={(e) => update('contourColor', e.target.value)}
                  />
                </div>
                <div className="ms-row">
                  <span className="ms-depth-label">투명도</span>
                  <input
                    type="range"
                    min={0}
                    max={1}
                    step={0.05}
                    value={value.contourOpacity}
                    onChange={(e) => update('contourOpacity', Number(e.target.value))}
                    className="ms-slider"
                  />
                  <span className="ms-hex">{value.contourOpacity.toFixed(2)}</span>
                </div>
                <div className="ms-row">
                  <span className="ms-depth-label">굵기</span>
                  <input
                    type="range"
                    min={0.5}
                    max={3}
                    step={0.1}
                    value={value.contourWidth}
                    onChange={(e) => update('contourWidth', Number(e.target.value))}
                    className="ms-slider"
                  />
                  <span className="ms-hex">{value.contourWidth.toFixed(1)}</span>
                </div>
              </>
            )}
          </div>

          {/* ── Depth labels ──────────────────────────── */}
          <div className="ms-section">
            <div className="ms-label" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              수심 라벨
              <span
                className={`cursor-pointer rounded border px-1.5 py-px text-[8px] transition-all duration-150 select-none ${value.depthLabelsVisible ? 'border-wing-accent bg-wing-accent text-white' : 'border-wing-border bg-wing-card text-wing-muted'}`}
                onClick={() => update('depthLabelsVisible', !value.depthLabelsVisible)}
              >
                {value.depthLabelsVisible ? 'ON' : 'OFF'}
              </span>
            </div>
            {value.depthLabelsVisible && (
              <>
                <div className="ms-row">
                  <span className="ms-depth-label">색상</span>
                  <input
                    type="color"
                    className="ms-color-input"
                    value={value.depthLabelColor}
                    onChange={(e) => update('depthLabelColor', e.target.value)}
                  />
                </div>
                <div className="ms-row">
                  <span className="ms-depth-label">크기</span>
                  <div className="flex flex-wrap gap-0.75">
                    {FONT_SIZES.map((fs) => (
                      <div
                        key={fs.value}
                        className={`cursor-pointer rounded border px-1.5 py-0.5 text-[8px] transition-all duration-150 select-none ${value.depthLabelSize === fs.value ? 'border-wing-accent bg-wing-accent text-white' : 'border-wing-border bg-wing-card text-wing-muted'}`}
                        onClick={() => update('depthLabelSize', fs.value)}
                      >
                        {fs.label}
                      </div>
                    ))}
                  </div>
                </div>
              </>
            )}
          </div>

          {/* ── Hillshade ─────────────────────────────── */}
          <div className="ms-section">
            <div className="ms-label" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              Hillshade
              <span
                className={`cursor-pointer rounded border px-1.5 py-px text-[8px] transition-all duration-150 select-none ${value.hillshadeVisible ? 'border-wing-accent bg-wing-accent text-white' : 'border-wing-border bg-wing-card text-wing-muted'}`}
                onClick={() => update('hillshadeVisible', !value.hillshadeVisible)}
              >
                {value.hillshadeVisible ? 'ON' : 'OFF'}
              </span>
            </div>
            {value.hillshadeVisible && (
              <>
                <div className="ms-row">
                  <span className="ms-depth-label">강도</span>
                  <input
                    type="range"
                    min={0}
                    max={1}
                    step={0.05}
                    value={value.hillshadeExaggeration}
                    onChange={(e) => update('hillshadeExaggeration', Number(e.target.value))}
                    className="ms-slider"
                  />
                  <span className="ms-hex">{value.hillshadeExaggeration.toFixed(2)}</span>
                </div>
                <div className="ms-row">
                  <span className="ms-depth-label">그림자 색</span>
                  <input
                    type="color"
                    className="ms-color-input"
                    value={value.hillshadeColor}
                    onChange={(e) => update('hillshadeColor', e.target.value)}
                  />
                </div>
              </>
            )}
          </div>

          {/* ── Landform labels ───────────────────────── */}
          <div className="ms-section">
            <div className="ms-label" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              해저 지형명
              <span
                className={`cursor-pointer rounded border px-1.5 py-px text-[8px] transition-all duration-150 select-none ${value.landformLabelsVisible ? 'border-wing-accent bg-wing-accent text-white' : 'border-wing-border bg-wing-card text-wing-muted'}`}
                onClick={() => update('landformLabelsVisible', !value.landformLabelsVisible)}
              >
                {value.landformLabelsVisible ? 'ON' : 'OFF'}
              </span>
            </div>
            {value.landformLabelsVisible && (
              <div className="ms-row">
                <span className="ms-depth-label">색상</span>
                <input
                  type="color"
                  className="ms-color-input"
                  value={value.landformLabelColor}
                  onChange={(e) => update('landformLabelColor', e.target.value)}
                />
              </div>
            )}
          </div>

          {/* ── Background ────────────────────────────── */}
          <div className="ms-section">
            <div className="ms-label">배경색</div>
            <div className="ms-row">
              <input
                type="color"
                className="ms-color-input"
                value={value.backgroundColor}
                onChange={(e) => update('backgroundColor', e.target.value)}
              />
              <span className="ms-hex">{value.backgroundColor}</span>
            </div>
          </div>

          {/* ── Reset ─────────────────────────────────── */}
          <button
            className="ms-reset"
            type="button"
            onClick={() => {
              onChange(DEFAULT_OCEAN_MAP_SETTINGS);
              setAutoGradient(false);
            }}
          >
            초기화
          </button>
        </div>
      )}
    </>
  );
}
