import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './mobile.css';

/*
 * SCR-M1 장치업체 현장 체크리스트(모바일 390px). Stitch contractor_onsite_checklist 이식.
 * - 오프라인 배지 · 반입전/시공중/구조확인 아코디언 · 사진 첨부 · 높이 실측 입력
 * - 필수 항목 완료 시 "검수 요청 보내기" 활성. 오프라인 시 연결 후 동기화 고지.
 * ★ 계약에 현장 체크리스트 엔드포인트 부재 → 로컬 상태 시연.
 */
type Section = 'before' | 'building' | 'structure';

export function ContractorOnsiteChecklistPage() {
  const navigate = useNavigate();
  const [view, setView] = useState<'plan' | 'photo'>('plan');
  const [open, setOpen] = useState<Record<Section, boolean>>({
    before: true,
    building: true,
    structure: true,
  });
  const [checks, setChecks] = useState<Record<string, boolean>>({
    floor: false,
    elec: false,
  });
  const [height, setHeight] = useState('');

  const requiredDone =
    checks.floor && checks.elec && height !== '' && Number(height) <= 5 && Number(height) > 0;

  const toggle = (s: Section) => setOpen((o) => ({ ...o, [s]: !o[s] }));

  return (
    <div className="kx-m kx-m--checklist">
      {/* 헤더 */}
      <header className="kx-m__head">
        <div className="kx-m__head-row">
          <div className="kx-m__head-left">
            <button className="kx-m__back" aria-label="뒤로" onClick={() => navigate(-1)}>
              ←
            </button>
            <div>
              <h1>부스 A-102</h1>
              <div className="kx-m__sub">
                <span>홀7</span>
                <span className="kx-m__dot" aria-hidden="true" />
                <span className="kx-m__accent">장치 1일차</span>
              </div>
            </div>
          </div>
          <span className="kx-m__offline">● 오프라인</span>
        </div>
        <div className="kx-m__seg" role="tablist">
          <button
            role="tab"
            aria-selected={view === 'plan'}
            className={view === 'plan' ? 'is-active' : ''}
            onClick={() => setView('plan')}
          >
            도면
          </button>
          <button
            role="tab"
            aria-selected={view === 'photo'}
            className={view === 'photo' ? 'is-active' : ''}
            onClick={() => setView('photo')}
          >
            예상 사진
          </button>
        </div>
      </header>

      <main className="kx-m__body">
        <div className="kx-m__info">필수 항목 3개 남음</div>

        {/* 반입 전 (완료) */}
        <section className="kx-m__acc">
          <button className="kx-m__acc-head" onClick={() => toggle('before')} aria-expanded={open.before}>
            <span>반입 전</span>
            <span className="kx-m__acc-count">2/2</span>
          </button>
          {open.before && (
            <div className="kx-m__acc-body">
              <label className="kx-m__check is-done">
                <input type="checkbox" checked disabled />
                <span>방염 확인서 제출 확인</span>
              </label>
              <label className="kx-m__check is-done">
                <input type="checkbox" checked disabled />
                <span>안전모 및 보호장구 착용</span>
              </label>
            </div>
          )}
        </section>

        {/* 경고 카드 */}
        <div className="kx-m__warn">
          <h3>⚠ 장내 금지 작업 주의</h3>
          <ul>
            <li>금지: 전기톱, 용접, 페인트 작업</li>
            <li>소음 한도: 70~75dB 준수</li>
          </ul>
        </div>

        {/* 시공 중 */}
        <section className="kx-m__acc">
          <button className="kx-m__acc-head" onClick={() => toggle('building')} aria-expanded={open.building}>
            <span>시공 중</span>
            <span className="kx-m__acc-count">{Number(checks.floor) + Number(checks.elec)}/2</span>
          </button>
          {open.building && (
            <div className="kx-m__acc-body">
              <div className="kx-m__check-row">
                <label className="kx-m__check">
                  <input
                    type="checkbox"
                    checked={checks.floor}
                    onChange={(e) => setChecks((c) => ({ ...c, floor: e.target.checked }))}
                  />
                  <span className="kx-m__check-text">
                    바닥 마감 상태 양호
                    <small>테이핑 및 단차 확인</small>
                  </span>
                </label>
                <button className="kx-m__camera" aria-label="사진 첨부">📷</button>
              </div>
              <div className="kx-m__check-row">
                <label className="kx-m__check">
                  <input
                    type="checkbox"
                    checked={checks.elec}
                    onChange={(e) => setChecks((c) => ({ ...c, elec: e.target.checked }))}
                  />
                  <span className="kx-m__check-text">
                    전기 배선 안전 확인
                    <small>노출된 전선 정리</small>
                  </span>
                </label>
                <button className="kx-m__camera" aria-label="사진 첨부">📷</button>
              </div>
            </div>
          )}
        </section>

        {/* 구조 확인 */}
        <section className="kx-m__acc">
          <button className="kx-m__acc-head" onClick={() => toggle('structure')} aria-expanded={open.structure}>
            <span>구조 확인</span>
            <span className="kx-m__acc-count">{height && Number(height) <= 5 && Number(height) > 0 ? '1' : '0'}/1</span>
          </button>
          {open.structure && (
            <div className="kx-m__acc-body">
              <div className="kx-m__field">
                <label htmlFor="m-height">
                  장치물 최고 높이 실측
                  <span className="kx-m__rule">규정: 5m 이하</span>
                </label>
                <div className="kx-m__input-wrap">
                  <input
                    id="m-height"
                    type="number"
                    inputMode="decimal"
                    placeholder="4.2"
                    value={height}
                    onChange={(e) => setHeight(e.target.value)}
                  />
                  <span className="kx-m__unit">m</span>
                </div>
                {height !== '' && Number(height) > 5 && (
                  <p className="kx-m__field-err">5m 초과 — 규정 위반</p>
                )}
              </div>
            </div>
          )}
        </section>
      </main>

      {/* 하단 */}
      <footer className="kx-m__foot">
        <p className="kx-m__foot-note">↻ 오프라인 — 연결 시 동기화</p>
        <button className="kx-m__cta" disabled={!requiredDone}>
          검수 요청 보내기
        </button>
      </footer>
    </div>
  );
}
