// FloatModalContent.tsx — Modal + Confirm 카탈로그

import { useState } from 'react';
import type { DesignTheme } from '../designTheme';

interface FloatModalContentProps {
  theme: DesignTheme;
}

type ModalSize = 'sm' | 'md' | 'lg' | 'full';

const SIZE_CONFIG: Record<ModalSize, { label: string; width: string; desc: string }> = {
  sm: { label: 'Small', width: '380px', desc: '입력 폼, 간단한 확인' },
  md: { label: 'Medium', width: '520px', desc: '상세 파라미터, 재계산' },
  lg: { label: 'Large', width: '720px', desc: '복잡한 폼, 미디어 뷰어' },
  full: { label: 'Full', width: '95vw', desc: '매뉴얼, 전체 화면 콘텐츠' },
};

const MODAL_INVENTORY = [
  {
    component: 'HNSRecalcModal',
    zIndex: 'z-[9999]',
    trigger: '버튼 클릭',
    source: 'tabs/hns/components/',
  },
  {
    component: 'RecalcModal',
    zIndex: 'z-[9999]',
    trigger: '재계산 버튼',
    source: 'tabs/prediction/components/',
  },
  {
    component: 'BacktrackModal',
    zIndex: 'z-[9999]',
    trigger: '역추적 분석',
    source: 'tabs/prediction/components/',
  },
  {
    component: 'MediaModal',
    zIndex: 'z-[10000]',
    trigger: '미디어 클릭',
    source: 'tabs/incidents/components/',
  },
  {
    component: 'SimulationErrorModal',
    zIndex: 'z-50 ⚠️',
    trigger: '오류 발생',
    source: 'tabs/prediction/components/',
  },
  {
    component: 'TemplateFormEditor',
    zIndex: 'z-50 ⚠️',
    trigger: '템플릿 편집',
    source: 'tabs/reports/components/',
  },
  {
    component: 'Admin 모달 (Layer/Map/Perm)',
    zIndex: 'z-50 ⚠️',
    trigger: '관리 작업',
    source: 'tabs/admin/components/',
  },
  {
    component: 'UserManualPopup',
    zIndex: 'z-[9999]',
    trigger: '도움말 버튼',
    source: 'common/components/ui/',
  },
];

export const FloatModalContent = ({ theme }: FloatModalContentProps) => {
  const t = theme;
  const isDark = t.mode === 'dark';

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [activeSize, setActiveSize] = useState<ModalSize>('md');
  const [isConfirmOpen, setIsConfirmOpen] = useState(false);

  const overlayBg = isDark ? 'rgba(0,0,0,0.65)' : 'rgba(0,0,0,0.45)';
  const modalBg = isDark ? '#1b1f2c' : '#ffffff';
  const modalBorder = isDark ? 'rgba(66,71,84,0.30)' : '#e2e8f0';
  const modalWidth = activeSize === 'full' ? '95vw' : SIZE_CONFIG[activeSize].width;
  const modalHeight = activeSize === 'full' ? '92vh' : 'auto';

  return (
    <div className="px-8 py-10 flex flex-col gap-12 max-w-[1200px]">
      {/* ── 개요 ── */}
      <div className="flex flex-col gap-3">
        <h2 className="font-sans text-xl font-bold" style={{ color: t.textPrimary }}>
          Modal
        </h2>
        <p className="font-korean text-body-2 leading-6" style={{ color: t.textSecondary }}>
          <code
            className="font-mono text-caption px-1.5 py-0.5 rounded"
            style={{
              backgroundColor: isDark ? 'rgba(76,215,246,0.08)' : 'rgba(6,182,212,0.06)',
              color: t.textAccent,
            }}
          >
            fixed inset-0
          </code>{' '}
          백드롭 위에 중앙 정렬된 다이얼로그. 사용자 확인·입력이 필요한 중요 작업에 사용한다.
          크기(size)와 용도(variant)로 변형하며, <strong>Confirm</strong>은 Modal의 서브컴포넌트다.
        </p>
      </div>

      {/* ── Live Preview ── */}
      <div className="flex flex-col gap-4">
        <div className="flex items-center gap-2">
          <h3 className="font-sans text-base font-bold" style={{ color: t.textPrimary }}>
            Live Preview
          </h3>
          <span
            className="font-mono text-caption px-2 py-0.5 rounded"
            style={{
              backgroundColor: isDark ? 'rgba(34,197,94,0.10)' : 'rgba(34,197,94,0.08)',
              color: '#22c55e',
            }}
          >
            interactive
          </span>
        </div>

        {/* 컨트롤 */}
        <div
          className="rounded-lg border border-solid p-5 flex flex-col gap-4"
          style={{ backgroundColor: t.cardBg, borderColor: t.cardBorder }}
        >
          {/* 사이즈 선택 */}
          <div className="flex flex-col gap-2">
            <span
              className="font-mono text-caption uppercase"
              style={{ letterSpacing: '1px', color: t.textMuted }}
            >
              Size Variant
            </span>
            <div className="flex gap-2 flex-wrap">
              {(Object.keys(SIZE_CONFIG) as ModalSize[]).map((size) => (
                <button
                  key={size}
                  type="button"
                  onClick={() => setActiveSize(size)}
                  className="px-3 py-1.5 rounded border border-solid font-mono text-caption transition-colors"
                  style={{
                    backgroundColor:
                      activeSize === size
                        ? isDark
                          ? 'rgba(76,215,246,0.15)'
                          : 'rgba(6,182,212,0.10)'
                        : 'transparent',
                    borderColor: activeSize === size ? t.textAccent : t.cardBorder,
                    color: activeSize === size ? t.textAccent : t.textMuted,
                  }}
                >
                  {SIZE_CONFIG[size].label}
                  <span className="ml-1.5 opacity-60">{SIZE_CONFIG[size].width}</span>
                </button>
              ))}
            </div>
            <span className="font-korean text-caption" style={{ color: t.textMuted }}>
              {SIZE_CONFIG[activeSize].desc}
            </span>
          </div>

          {/* 버튼 그룹 */}
          <div className="flex gap-3 flex-wrap">
            <button
              type="button"
              onClick={() => setIsModalOpen(true)}
              className="px-4 py-2 rounded border border-solid font-korean text-body-2 font-medium transition-opacity hover:opacity-80"
              style={{
                backgroundColor: isDark ? 'rgba(76,215,246,0.15)' : 'rgba(6,182,212,0.12)',
                borderColor: t.textAccent,
                color: t.textAccent,
              }}
            >
              모달 열기
            </button>
            <button
              type="button"
              onClick={() => setIsConfirmOpen(true)}
              className="px-4 py-2 rounded border border-solid font-korean text-body-2 font-medium transition-opacity hover:opacity-80"
              style={{
                backgroundColor: isDark ? 'rgba(239,68,68,0.10)' : 'rgba(239,68,68,0.06)',
                borderColor: 'rgba(239,68,68,0.40)',
                color: '#ef4444',
              }}
            >
              Confirm (삭제 확인)
            </button>
          </div>
        </div>
      </div>

      {/* ── Confirm 서브컴포넌트 ── */}
      <div className="flex flex-col gap-4">
        <h3 className="font-sans text-base font-bold" style={{ color: t.textPrimary }}>
          Confirm — Modal 서브컴포넌트
        </h3>
        <div
          className="rounded-lg border border-solid p-5 flex flex-col gap-3"
          style={{ backgroundColor: t.cardBg, borderColor: t.cardBorder }}
        >
          <p className="font-korean text-body-2 leading-6" style={{ color: t.textSecondary }}>
            Confirm은 독립 컴포넌트가 아닌 <strong>Modal의 variant</strong>다. 타이틀 + 단문 메시지
            + 취소/확인 2버튼 구성. 파괴적 작업(삭제, 초기화) 전 사용자 의도를 확인한다.
          </p>
          <div
            className="rounded border border-solid px-4 py-3"
            style={{
              backgroundColor: isDark ? 'rgba(239,68,68,0.06)' : 'rgba(239,68,68,0.04)',
              borderColor: 'rgba(239,68,68,0.20)',
            }}
          >
            <p className="font-mono text-caption" style={{ color: '#ef4444' }}>
              ⚠️ window.confirm 대체 — admin, board 4건에서 OS 레벨 confirm 사용 중 → 커스텀
              ConfirmDialog로 전환 필요
            </p>
          </div>
          <div className="flex flex-col gap-1.5">
            {[
              { label: 'variant', value: '"confirm"', desc: 'Modal 컴포넌트의 prop으로 전달' },
              { label: 'title', value: '"항목을 삭제하시겠습니까?"', desc: '액션을 명확히 서술' },
              {
                label: 'message',
                value: '"삭제된 데이터는 복구할 수 없습니다."',
                desc: '부가 설명 (선택)',
              },
              { label: 'onConfirm', value: '() => handleDelete()', desc: '확인 버튼 콜백' },
            ].map((row) => (
              <div key={row.label} className="flex items-start gap-3">
                <span
                  className="font-mono text-caption rounded px-1.5 py-0.5 shrink-0"
                  style={{
                    backgroundColor: isDark ? 'rgba(76,215,246,0.08)' : 'rgba(6,182,212,0.06)',
                    color: t.textAccent,
                  }}
                >
                  {row.label}
                </span>
                <span className="font-mono text-caption" style={{ color: t.textPrimary }}>
                  {row.value}
                </span>
                <span className="font-korean text-caption ml-auto" style={{ color: t.textMuted }}>
                  {row.desc}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ── Anatomy ── */}
      <div className="flex flex-col gap-4">
        <h3 className="font-sans text-base font-bold" style={{ color: t.textPrimary }}>
          Anatomy
        </h3>
        <div className="grid grid-cols-2 gap-6">
          {/* 구조 다이어그램 */}
          <div
            className="rounded-lg border border-solid p-4 flex flex-col gap-3"
            style={{ backgroundColor: t.cardBg, borderColor: t.cardBorder }}
          >
            <span
              className="font-mono text-caption uppercase"
              style={{ letterSpacing: '1px', color: t.textMuted }}
            >
              Structure
            </span>
            <div
              className="rounded flex items-center justify-center p-4"
              style={{
                backgroundColor: isDark ? 'rgba(0,0,0,0.50)' : 'rgba(0,0,0,0.06)',
                minHeight: '200px',
              }}
            >
              <div
                className="rounded-lg border border-solid flex flex-col overflow-hidden w-full"
                style={{ backgroundColor: modalBg, borderColor: modalBorder }}
              >
                <div
                  className="flex items-center justify-between px-3 py-2 border-b border-solid"
                  style={{ borderColor: modalBorder }}
                >
                  <span className="font-korean text-caption" style={{ color: t.textPrimary }}>
                    다이얼로그 타이틀
                  </span>
                  <div
                    className="w-4 h-4 rounded flex items-center justify-center"
                    style={{ backgroundColor: isDark ? 'rgba(66,71,84,0.25)' : '#f1f5f9' }}
                  >
                    <span className="font-mono text-caption" style={{ color: t.textMuted }}>
                      ✕
                    </span>
                  </div>
                </div>
                <div className="flex flex-col gap-1.5 px-3 py-3">
                  {[75, 100, 60].map((w, i) => (
                    <div
                      key={i}
                      className="rounded"
                      style={{
                        height: '7px',
                        width: `${w}%`,
                        backgroundColor: isDark ? 'rgba(66,71,84,0.30)' : '#e2e8f0',
                      }}
                    />
                  ))}
                </div>
                <div
                  className="flex items-center justify-end gap-2 px-3 py-2 border-t border-solid"
                  style={{ borderColor: modalBorder }}
                >
                  <div
                    className="rounded px-2 py-1"
                    style={{ backgroundColor: isDark ? 'rgba(66,71,84,0.20)' : '#f1f5f9' }}
                  >
                    <span className="font-korean text-caption" style={{ color: t.textMuted }}>
                      취소
                    </span>
                  </div>
                  <div
                    className="rounded px-2 py-1"
                    style={{
                      backgroundColor: isDark ? 'rgba(76,215,246,0.18)' : 'rgba(6,182,212,0.12)',
                    }}
                  >
                    <span className="font-korean text-caption" style={{ color: t.textAccent }}>
                      확인
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* CSS 클래스 레퍼런스 */}
          <div
            className="rounded-lg border border-solid p-4 flex flex-col gap-3"
            style={{ backgroundColor: t.cardBg, borderColor: t.cardBorder }}
          >
            <span
              className="font-mono text-caption uppercase"
              style={{ letterSpacing: '1px', color: t.textMuted }}
            >
              CSS Classes
            </span>
            <div className="flex flex-col gap-2">
              {[
                {
                  cls: '.wing-overlay',
                  styles: 'fixed inset-0, z-index: 10000',
                  desc: '백드롭 오버레이',
                },
                {
                  cls: '.wing-modal',
                  styles: 'rounded-xl, bg-surface, border + shadow',
                  desc: '다이얼로그 컨테이너',
                },
                {
                  cls: '.wing-modal-header',
                  styles: 'flex justify-between, px-5, py-[14px], border-b',
                  desc: '헤더 (타이틀 + 닫기)',
                },
              ].map((item) => (
                <div
                  key={item.cls}
                  className="rounded border border-solid px-3 py-2"
                  style={{ borderColor: t.cardBorder }}
                >
                  <div className="flex items-center gap-2 mb-1">
                    <span
                      className="font-mono text-caption rounded px-1.5 py-0.5"
                      style={{
                        backgroundColor: isDark ? 'rgba(76,215,246,0.08)' : 'rgba(6,182,212,0.06)',
                        color: t.textAccent,
                      }}
                    >
                      {item.cls}
                    </span>
                    <span className="font-korean text-caption" style={{ color: t.textMuted }}>
                      {item.desc}
                    </span>
                  </div>
                  <span className="font-mono text-caption" style={{ color: t.textSecondary }}>
                    {item.styles}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* ── Z-Index 규칙 ── */}
      <div className="flex flex-col gap-4">
        <h3 className="font-sans text-base font-bold" style={{ color: t.textPrimary }}>
          Z-Index 규칙
        </h3>
        <div className="flex flex-col gap-2">
          {[
            {
              range: 'z-[9999]',
              status: '표준',
              desc: '일반 Modal — 표준값, 신규 Modal은 이 값 사용',
              color: '#22c55e',
            },
            {
              range: 'z-[10000]',
              status: '허용',
              desc: '모달 위 모달 (MediaModal, IncidentsView) — 필요 시만',
              color: '#eab308',
            },
            {
              range: 'z-50',
              status: '비표준 ⚠️',
              desc: 'SimulationErrorModal, Admin 모달, TemplateFormEditor — z-[9999]로 통일 필요',
              color: '#ef4444',
            },
          ].map((row) => (
            <div
              key={row.range}
              className="flex items-start gap-4 rounded border border-solid px-4 py-3"
              style={{ backgroundColor: t.cardBg, borderColor: t.cardBorder }}
            >
              <span
                className="font-mono text-body-2 rounded border border-solid px-2 py-0.5 shrink-0"
                style={{ color: t.textAccent, borderColor: t.cardBorder }}
              >
                {row.range}
              </span>
              <span
                className="font-mono text-caption rounded px-1.5 py-0.5 shrink-0"
                style={{ color: row.color, backgroundColor: `${row.color}15` }}
              >
                {row.status}
              </span>
              <span
                className="font-korean text-caption leading-5"
                style={{ color: t.textSecondary }}
              >
                {row.desc}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* ── 인벤토리 ── */}
      <div className="flex flex-col gap-4">
        <h3 className="font-sans text-base font-bold" style={{ color: t.textPrimary }}>
          현재 사용 사례
        </h3>
        <div
          className="rounded-lg border border-solid overflow-hidden"
          style={{ backgroundColor: t.tableContainerBg, borderColor: t.cardBorder }}
        >
          <div
            className="grid"
            style={{
              gridTemplateColumns: '1fr 120px 130px 1fr',
              backgroundColor: t.tableHeaderBg,
              borderBottom: `1px solid ${t.tableRowBorder}`,
            }}
          >
            {['Component', 'Z-Index', 'Trigger', 'Source'].map((col) => (
              <div key={col} className="py-2.5 px-4">
                <span
                  className="font-mono text-caption uppercase"
                  style={{ letterSpacing: '1px', color: t.textMuted }}
                >
                  {col}
                </span>
              </div>
            ))}
          </div>
          {MODAL_INVENTORY.map((item, idx) => (
            <div
              key={item.component}
              className="grid items-center"
              style={{
                gridTemplateColumns: '1fr 120px 130px 1fr',
                borderTop: idx === 0 ? 'none' : `1px solid ${t.tableRowBorder}`,
              }}
            >
              <div className="py-2.5 px-4">
                <span className="font-mono text-caption" style={{ color: t.textPrimary }}>
                  {item.component}
                </span>
              </div>
              <div className="py-2.5 px-4">
                <span
                  className="font-mono text-caption rounded border border-solid px-1.5 py-0.5"
                  style={{
                    color: item.zIndex.includes('⚠️') ? '#ef4444' : t.textAccent,
                    borderColor: item.zIndex.includes('⚠️') ? 'rgba(239,68,68,0.30)' : t.cardBorder,
                  }}
                >
                  {item.zIndex}
                </span>
              </div>
              <div className="py-2.5 px-4">
                <span className="font-korean text-caption" style={{ color: t.textSecondary }}>
                  {item.trigger}
                </span>
              </div>
              <div className="py-2.5 px-4">
                <span className="font-mono text-caption" style={{ color: t.textMuted }}>
                  {item.source}
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── 실제 Modal 렌더링 ── */}
      {isModalOpen && (
        <div
          className="fixed inset-0 flex items-center justify-center z-[9999]"
          style={{ backgroundColor: overlayBg, backdropFilter: 'blur(4px)' }}
          onClick={(e) => {
            if (e.target === e.currentTarget) setIsModalOpen(false);
          }}
        >
          <div
            className="flex flex-col rounded-xl border border-solid overflow-hidden"
            style={{
              width: modalWidth,
              maxHeight: modalHeight,
              backgroundColor: modalBg,
              borderColor: modalBorder,
              boxShadow: '0 20px 60px rgba(0,0,0,0.5)',
            }}
          >
            <div
              className="flex items-center justify-between px-5 py-4 border-b border-solid shrink-0"
              style={{ borderColor: modalBorder }}
            >
              <span
                className="font-korean text-body-2 font-medium"
                style={{ color: t.textPrimary }}
              >
                Modal Preview — {SIZE_CONFIG[activeSize].label} ({SIZE_CONFIG[activeSize].width})
              </span>
              <button
                type="button"
                onClick={() => setIsModalOpen(false)}
                className="w-7 h-7 rounded flex items-center justify-center hover:opacity-70 transition-opacity"
                style={{ backgroundColor: isDark ? 'rgba(66,71,84,0.25)' : '#f1f5f9' }}
              >
                <span className="font-mono text-body-2" style={{ color: t.textMuted }}>
                  ✕
                </span>
              </button>
            </div>
            <div className="px-5 py-5 flex flex-col gap-3 overflow-y-auto">
              <p className="font-korean text-body-2 leading-6" style={{ color: t.textSecondary }}>
                이 모달은{' '}
                <code
                  className="font-mono text-caption px-1 rounded"
                  style={{
                    backgroundColor: isDark ? 'rgba(76,215,246,0.08)' : 'rgba(6,182,212,0.06)',
                    color: t.textAccent,
                  }}
                >
                  fixed inset-0, z-[9999]
                </code>{' '}
                백드롭 위에 렌더링됩니다. 백드롭 클릭 또는 닫기 버튼으로 닫을 수 있습니다.
              </p>
              <div className="flex flex-col gap-2">
                {['파라미터 입력 필드', '선택 항목', '추가 설정값'].map((label) => (
                  <div
                    key={label}
                    className="rounded border border-solid px-3 py-2.5"
                    style={{ borderColor: t.cardBorder }}
                  >
                    <span className="font-korean text-caption" style={{ color: t.textMuted }}>
                      {label}
                    </span>
                  </div>
                ))}
              </div>
            </div>
            <div
              className="flex items-center justify-end gap-2 px-5 py-4 border-t border-solid shrink-0"
              style={{ borderColor: modalBorder }}
            >
              <button
                type="button"
                onClick={() => setIsModalOpen(false)}
                className="px-4 py-2 rounded border border-solid font-korean text-body-2 transition-opacity hover:opacity-70"
                style={{ borderColor: t.cardBorder, color: t.textMuted }}
              >
                취소
              </button>
              <button
                type="button"
                onClick={() => setIsModalOpen(false)}
                className="px-4 py-2 rounded font-korean text-body-2 font-medium transition-opacity hover:opacity-80"
                style={{
                  backgroundColor: isDark ? 'rgba(76,215,246,0.18)' : 'rgba(6,182,212,0.14)',
                  color: t.textAccent,
                }}
              >
                확인
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── 실제 Confirm 렌더링 ── */}
      {isConfirmOpen && (
        <div
          className="fixed inset-0 flex items-center justify-center z-[9999]"
          style={{ backgroundColor: overlayBg, backdropFilter: 'blur(4px)' }}
        >
          <div
            className="flex flex-col rounded-xl border border-solid overflow-hidden"
            style={{
              width: '360px',
              backgroundColor: modalBg,
              borderColor: modalBorder,
              boxShadow: '0 20px 60px rgba(0,0,0,0.5)',
            }}
          >
            <div
              className="flex items-center justify-between px-5 py-4 border-b border-solid"
              style={{ borderColor: modalBorder }}
            >
              <div className="flex items-center gap-2">
                <span style={{ color: '#ef4444', fontSize: '16px' }}>⚠</span>
                <span
                  className="font-korean text-body-2 font-medium"
                  style={{ color: t.textPrimary }}
                >
                  항목을 삭제하시겠습니까?
                </span>
              </div>
            </div>
            <div className="px-5 py-4">
              <p className="font-korean text-body-2 leading-6" style={{ color: t.textSecondary }}>
                삭제된 데이터는 복구할 수 없습니다. 계속 진행하시겠습니까?
              </p>
            </div>
            <div
              className="flex items-center justify-end gap-2 px-5 py-4 border-t border-solid"
              style={{ borderColor: modalBorder }}
            >
              <button
                type="button"
                onClick={() => setIsConfirmOpen(false)}
                className="px-4 py-2 rounded border border-solid font-korean text-body-2 transition-opacity hover:opacity-70"
                style={{ borderColor: t.cardBorder, color: t.textMuted }}
              >
                취소
              </button>
              <button
                type="button"
                onClick={() => setIsConfirmOpen(false)}
                className="px-4 py-2 rounded font-korean text-body-2 font-medium transition-opacity hover:opacity-80"
                style={{
                  backgroundColor: isDark ? 'rgba(239,68,68,0.18)' : 'rgba(239,68,68,0.12)',
                  color: '#ef4444',
                }}
              >
                삭제
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default FloatModalContent;
