import { useState } from 'react';
import { CHAPTERS } from '@common/data/manualChapters';

interface UserManualPopupProps {
  isOpen: boolean;
  onClose: () => void;
}

const UserManualPopup = ({ isOpen, onClose }: UserManualPopupProps) => {
  const [selectedChapterId, setSelectedChapterId] = useState<string>('ch01');
  const [expandedScreenIds, setExpandedScreenIds] = useState<Set<string>>(new Set());
  const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);

  if (!isOpen) return null;

  const selectedChapter = CHAPTERS.find((ch) => ch.id === selectedChapterId) ?? CHAPTERS[0];

  const toggleScreen = (screenId: string) => {
    setExpandedScreenIds((prev) => {
      const next = new Set(prev);
      if (next.has(screenId)) {
        next.delete(screenId);
      } else {
        next.add(screenId);
      }
      return next;
    });
  };

  const expandAll = () => {
    setExpandedScreenIds(new Set(selectedChapter.screens.map((s) => s.id)));
  };

  const collapseAll = () => {
    setExpandedScreenIds(new Set());
  };

  const allExpanded =
    selectedChapter.screens.length > 0 &&
    selectedChapter.screens.every((s) => expandedScreenIds.has(s.id));

  return (
    <>
      <div
        className="fixed inset-0 z-[9999] flex items-center justify-center"
        style={{ background: 'rgba(0,0,0,0.65)' }}
        onClick={(e) => {
          if (e.target === e.currentTarget) onClose();
        }}
      >
        <div
          className="flex flex-col rounded-lg overflow-hidden"
          style={{
            width: '90vw',
            height: '85vh',
            background: '#0f1729',
            border: '1px solid #1e2a45',
            boxShadow: '0 24px 64px rgba(0,0,0,0.5)',
          }}
        >
          {/* Header */}
          <div
            className="flex items-center justify-between px-6 py-4 flex-shrink-0"
            style={{
              background: '#0b1120',
              borderBottom: '1px solid #1e2a45',
            }}
          >
            <div className="flex items-center gap-3">
              <span className="font-bold text-subtitle" style={{ color: '#e2e8f0' }}>
                Wing 사용자 매뉴얼
              </span>
              <span
                className="text-label-2 px-2 py-0.5 rounded font-mono"
                style={{
                  background: 'rgba(6,182,212,0.12)',
                  color: '#06b6d4',
                  border: '1px solid rgba(6,182,212,0.25)',
                }}
              >
                v0.5
              </span>
            </div>
            <button
              onClick={onClose}
              className="flex items-center justify-center w-7 h-7 rounded text-title-4 font-semibold transition-colors"
              style={{ color: '#94a3b8', background: 'transparent' }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = '#1a2540';
                e.currentTarget.style.color = '#e2e8f0';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = 'transparent';
                e.currentTarget.style.color = '#94a3b8';
              }}
            >
              X
            </button>
          </div>

          {/* Body */}
          <div className="flex flex-1 overflow-hidden">
            {/* Left Sidebar */}
            <div
              className="flex-shrink-0 overflow-y-auto py-3"
              style={{
                width: '240px',
                background: '#0b1120',
                borderRight: '1px solid #1e2a45',
              }}
            >
              {CHAPTERS.map((chapter) => {
                const isActive = chapter.id === selectedChapterId;
                return (
                  <button
                    key={chapter.id}
                    onClick={() => {
                      setSelectedChapterId(chapter.id);
                      setExpandedScreenIds(new Set());
                    }}
                    className="w-full text-left px-4 py-3 transition-colors"
                    style={{
                      background: isActive ? 'rgba(6,182,212,0.08)' : 'transparent',
                      borderLeft: isActive ? '2px solid #06b6d4' : '2px solid transparent',
                    }}
                    onMouseEnter={(e) => {
                      if (!isActive) {
                        e.currentTarget.style.background = '#1a2540';
                      }
                    }}
                    onMouseLeave={(e) => {
                      if (!isActive) {
                        e.currentTarget.style.background = 'transparent';
                      }
                    }}
                  >
                    <div className="flex items-center gap-2.5">
                      <span
                        className="flex-shrink-0 w-7 h-7 rounded flex items-center justify-center text-caption font-bold font-mono"
                        style={{
                          background: isActive ? 'rgba(6,182,212,0.18)' : 'rgba(255,255,255,0.05)',
                          color: isActive ? '#06b6d4' : '#64748b',
                          border: isActive ? '1px solid rgba(6,182,212,0.3)' : '1px solid #1e2a45',
                        }}
                      >
                        {chapter.number}
                      </span>
                      <div className="min-w-0">
                        <div
                          className="text-label-1 font-medium leading-tight truncate"
                          style={{ color: isActive ? '#06b6d4' : '#cbd5e1' }}
                        >
                          {chapter.title}
                        </div>
                        <div
                          className="text-caption leading-tight mt-0.5 truncate"
                          style={{ color: '#475569' }}
                        >
                          {chapter.subtitle}
                        </div>
                      </div>
                    </div>
                  </button>
                );
              })}
            </div>

            {/* Right Content */}
            <div className="flex-1 overflow-y-auto p-6">
              {/* Chapter heading */}
              <div className="mb-5 pb-4" style={{ borderBottom: '1px solid #1e2a45' }}>
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <span
                      className="text-label-2 font-mono px-2 py-0.5 rounded font-bold"
                      style={{
                        background: 'rgba(6,182,212,0.12)',
                        color: '#06b6d4',
                        border: '1px solid rgba(6,182,212,0.2)',
                      }}
                    >
                      CH {selectedChapter.number}
                    </span>
                    <h2 className="text-title-2 font-semibold" style={{ color: '#e2e8f0' }}>
                      {selectedChapter.title}
                    </h2>
                    <span className="text-label-1" style={{ color: '#475569' }}>
                      {selectedChapter.subtitle}
                    </span>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="text-label-2 mr-1" style={{ color: '#64748b' }}>
                      {selectedChapter.screens.length}개 화면
                    </span>
                    <button
                      onClick={allExpanded ? collapseAll : expandAll}
                      className="text-label-2 px-3 py-1 rounded transition-colors"
                      style={{
                        background: 'rgba(6,182,212,0.08)',
                        color: '#06b6d4',
                        border: '1px solid rgba(6,182,212,0.2)',
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.background = 'rgba(6,182,212,0.16)';
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.background = 'rgba(6,182,212,0.08)';
                      }}
                    >
                      {allExpanded ? '전체 닫기' : '전체 열기'}
                    </button>
                    <a
                      href={`/manual/pdfs/${selectedChapter.id}.pdf`}
                      download={`${selectedChapter.number}_${selectedChapter.title}.pdf`}
                      className="text-label-2 px-3 py-1 rounded transition-colors inline-flex items-center"
                      style={{
                        background: 'rgba(6,182,212,0.08)',
                        color: '#06b6d4',
                        border: '1px solid rgba(6,182,212,0.2)',
                        textDecoration: 'none',
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.background = 'rgba(6,182,212,0.16)';
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.background = 'rgba(6,182,212,0.08)';
                      }}
                    >
                      PDF 다운로드
                    </a>
                  </div>
                </div>
              </div>

              {/* Screen cards */}
              <div className="flex flex-col gap-2">
                {selectedChapter.screens.map((screen) => {
                  const isExpanded = expandedScreenIds.has(screen.id);
                  const imageSrc = `/manual/image${screen.imageIndex}.png`;
                  return (
                    <div
                      key={screen.id}
                      className="rounded-lg overflow-hidden"
                      style={{
                        background: '#141d33',
                        border: '1px solid #1e2a45',
                      }}
                    >
                      {/* Screen header (toggle) */}
                      <button
                        onClick={() => toggleScreen(screen.id)}
                        className="w-full text-left flex items-center gap-3 px-4 py-3 transition-colors"
                        style={{ background: 'transparent' }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.background = '#1a2540';
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.background = 'transparent';
                        }}
                      >
                        <span
                          className="flex-shrink-0 text-caption font-mono font-bold px-1.5 py-0.5 rounded"
                          style={{
                            background: 'rgba(6,182,212,0.1)',
                            color: '#06b6d4',
                            border: '1px solid rgba(6,182,212,0.2)',
                            minWidth: '36px',
                            textAlign: 'center',
                          }}
                        >
                          {screen.id}
                        </span>
                        <span
                          className="flex-1 text-title-4 font-medium"
                          style={{ color: '#cbd5e1' }}
                        >
                          {screen.name}
                        </span>
                        <span
                          className="flex-shrink-0 text-caption font-mono"
                          style={{
                            color: '#475569',
                            transition: 'transform 0.2s',
                            display: 'inline-block',
                            transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
                          }}
                        >
                          v
                        </span>
                      </button>

                      {/* Screen detail (expanded) */}
                      {isExpanded && (
                        <div className="px-4 pb-5" style={{ borderTop: '1px solid #1e2a45' }}>
                          {/* Screenshot image */}
                          <div className="mt-4 mb-4">
                            <img
                              src={imageSrc}
                              alt={screen.name}
                              loading="lazy"
                              onClick={() => setLightboxSrc(imageSrc)}
                              style={{
                                width: '100%',
                                borderRadius: '6px',
                                border: '1px solid #1e2a45',
                                cursor: 'zoom-in',
                                display: 'block',
                              }}
                            />
                            <p
                              className="mt-1 text-caption text-right"
                              style={{ color: '#475569' }}
                            >
                              이미지를 클릭하면 크게 볼 수 있다
                            </p>
                          </div>

                          {/* Menu path breadcrumb */}
                          <div
                            className="mb-3 text-label-2 font-mono px-2 py-1 rounded inline-block"
                            style={{
                              background: 'rgba(71,85,105,0.15)',
                              color: '#64748b',
                              border: '1px solid #1e2a45',
                            }}
                          >
                            {screen.menuPath}
                          </div>

                          {/* Overview */}
                          <div className="mt-2">
                            <p
                              className="text-label-1 leading-relaxed"
                              style={{ color: '#94a3b8' }}
                            >
                              {screen.overview}
                            </p>
                          </div>

                          {/* Description */}
                          {screen.description && (
                            <div
                              className="mt-3 px-3 py-2.5 rounded"
                              style={{
                                background: 'rgba(30,42,69,0.6)',
                                border: '1px solid #1e2a45',
                              }}
                            >
                              <div
                                className="text-label-2 font-semibold mb-1.5 uppercase tracking-wide"
                                style={{ color: '#475569' }}
                              >
                                화면 설명
                              </div>
                              <p
                                className="text-label-1 leading-relaxed"
                                style={{ color: '#7f8ea3' }}
                              >
                                {screen.description}
                              </p>
                            </div>
                          )}

                          {/* Procedure */}
                          {screen.procedure && screen.procedure.length > 0 && (
                            <div className="mt-4">
                              <div
                                className="text-label-2 font-semibold mb-2 uppercase tracking-wide"
                                style={{ color: '#475569' }}
                              >
                                사용 절차
                              </div>
                              <ol className="flex flex-col gap-1.5">
                                {screen.procedure.map((step, idx) => (
                                  <li key={idx} className="flex items-start gap-2.5">
                                    <span
                                      className="flex-shrink-0 w-5 h-5 rounded-full flex items-center justify-center text-caption font-bold mt-0.5"
                                      style={{
                                        background: 'rgba(6,182,212,0.12)',
                                        color: '#06b6d4',
                                        border: '1px solid rgba(6,182,212,0.2)',
                                      }}
                                    >
                                      {idx + 1}
                                    </span>
                                    <span
                                      className="text-label-1 leading-relaxed"
                                      style={{ color: '#94a3b8' }}
                                    >
                                      {step}
                                    </span>
                                  </li>
                                ))}
                              </ol>
                            </div>
                          )}

                          {/* Inputs */}
                          {screen.inputs && screen.inputs.length > 0 && (
                            <div className="mt-4">
                              <div
                                className="text-label-2 font-semibold mb-2 uppercase tracking-wide"
                                style={{ color: '#475569' }}
                              >
                                입력 항목
                              </div>
                              <div
                                className="rounded overflow-hidden"
                                style={{ border: '1px solid #1e2a45' }}
                              >
                                <table className="w-full text-label-1">
                                  <thead>
                                    <tr style={{ background: '#0f1729' }}>
                                      <th
                                        className="text-left px-3 py-2 font-medium"
                                        style={{ color: '#64748b', width: '22%' }}
                                      >
                                        항목
                                      </th>
                                      <th
                                        className="text-left px-3 py-2 font-medium"
                                        style={{ color: '#64748b', width: '18%' }}
                                      >
                                        유형
                                      </th>
                                      <th
                                        className="text-left px-3 py-2 font-medium"
                                        style={{ color: '#64748b', width: '12%' }}
                                      >
                                        필수
                                      </th>
                                      <th
                                        className="text-left px-3 py-2 font-medium"
                                        style={{ color: '#64748b' }}
                                      >
                                        설명
                                      </th>
                                    </tr>
                                  </thead>
                                  <tbody>
                                    {screen.inputs.map((input, idx) => (
                                      <tr
                                        key={idx}
                                        style={{
                                          borderTop: '1px solid #1e2a45',
                                          background:
                                            idx % 2 === 0
                                              ? 'transparent'
                                              : 'rgba(255,255,255,0.01)',
                                        }}
                                      >
                                        <td
                                          className="px-3 py-2 font-medium"
                                          style={{ color: '#cbd5e1' }}
                                        >
                                          {input.label}
                                        </td>
                                        <td className="px-3 py-2" style={{ color: '#64748b' }}>
                                          {input.type}
                                        </td>
                                        <td className="px-3 py-2">
                                          {input.required ? (
                                            <span
                                              className="text-caption font-bold px-1.5 py-0.5 rounded"
                                              style={{
                                                background: 'rgba(239,68,68,0.1)',
                                                color: '#f87171',
                                                border: '1px solid rgba(239,68,68,0.2)',
                                              }}
                                            >
                                              필수
                                            </span>
                                          ) : (
                                            <span
                                              className="text-caption px-1.5 py-0.5 rounded"
                                              style={{
                                                background: 'rgba(100,116,139,0.1)',
                                                color: '#64748b',
                                                border: '1px solid rgba(100,116,139,0.2)',
                                              }}
                                            >
                                              선택
                                            </span>
                                          )}
                                        </td>
                                        <td className="px-3 py-2" style={{ color: '#7f8ea3' }}>
                                          {input.desc}
                                        </td>
                                      </tr>
                                    ))}
                                  </tbody>
                                </table>
                              </div>
                            </div>
                          )}

                          {/* Notes */}
                          {screen.notes && screen.notes.length > 0 && (
                            <div className="mt-4">
                              <div
                                className="text-label-2 font-semibold mb-2 uppercase tracking-wide"
                                style={{ color: '#475569' }}
                              >
                                유의사항
                              </div>
                              <ul className="flex flex-col gap-1.5">
                                {screen.notes.map((note, idx) => (
                                  <li key={idx} className="flex items-start gap-2">
                                    <span
                                      className="flex-shrink-0 mt-1.5 w-1.5 h-1.5 rounded-full"
                                      style={{ background: '#f59e0b' }}
                                    />
                                    <span
                                      className="text-label-1 leading-relaxed"
                                      style={{ color: '#94a3b8' }}
                                    >
                                      {note}
                                    </span>
                                  </li>
                                ))}
                              </ul>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Lightbox */}
      {lightboxSrc !== null && (
        <div
          className="fixed inset-0 z-[10000] flex items-center justify-center"
          style={{ background: 'rgba(0,0,0,0.88)' }}
          onClick={() => setLightboxSrc(null)}
        >
          <div
            className="relative"
            style={{ maxWidth: '92vw', maxHeight: '90vh' }}
            onClick={(e) => e.stopPropagation()}
          >
            <img
              src={lightboxSrc}
              alt="확대 이미지"
              style={{
                maxWidth: '92vw',
                maxHeight: '88vh',
                borderRadius: '8px',
                border: '1px solid #1e2a45',
                display: 'block',
              }}
            />
            <button
              onClick={() => setLightboxSrc(null)}
              className="absolute top-2 right-2 w-8 h-8 rounded flex items-center justify-center text-title-4 font-bold"
              style={{
                background: 'rgba(15,23,41,0.85)',
                color: '#94a3b8',
                border: '1px solid #1e2a45',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.color = '#e2e8f0';
                e.currentTarget.style.background = '#1a2540';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.color = '#94a3b8';
                e.currentTarget.style.background = 'rgba(15,23,41,0.85)';
              }}
            >
              X
            </button>
          </div>
        </div>
      )}
    </>
  );
};

export default UserManualPopup;
