import { useState, useMemo } from 'react'
import { Link } from 'react-router-dom'
import GlobalCTA from '@/components/Layout/GlobalCTA'
import { useCMS, getCMSSelfCheck } from '@/services/cms'

type CheckItem = { id: string; question: string; dimension: string; options?: string[] }

const CHECK_ITEMS: CheckItem[] = [
  { id: 'q1', question: '战略方向在团队中是否清晰一致？', dimension: '战略价值' },
  { id: 'q2', question: '组织协同是否顺畅、职责是否清晰？', dimension: '组织价值' },
  { id: 'q3', question: '经营机制（目标/复盘/数据）是否闭环？', dimension: '经营价值' },
  { id: 'q4', question: '团队是否具备经营意识与成长机制？', dimension: '人的价值' },
]

export default function SelfCheck() {
  const { data: cmsCheck } = useCMS(getCMSSelfCheck, null)
  const items = useMemo(() => {
    try {
      const parsed = JSON.parse(cmsCheck?.questions || '[]')
      if (!Array.isArray(parsed) || !parsed.length) return CHECK_ITEMS
      return parsed.map((item: any, index: number) => ({ id: item.id || `q${index + 1}`, question: item.q || item.question || '', dimension: item.dimension || `价值维度 ${index + 1}`, options: item.options }))
    } catch { return CHECK_ITEMS }
  }, [cmsCheck])
  const [answers, setAnswers] = useState<Record<string, string>>({})
  const [showResult, setShowResult] = useState(false)

  const set = (id: string, val: string) => setAnswers(prev => ({ ...prev, [id]: val }))

  return (
    <div>
      <div className="page-header">
        <div className="container">
          <div className="breadcrumb">
            <Link to="/" style={{ color: 'rgba(255,255,255,0.8)' }}>
              首页
            </Link>{' '}
            / 看看你的企业
          </div>
          <h1>看看你的企业</h1>
          <p>
            {cmsCheck?.guide || '轻量自我对照工具，帮助你快速定位在四大价值 × A/M/B 的大致位置。'}
            <br />
            <strong style={{ color: '#fde68a' }}>一期禁止长问卷、复杂评分、自动诊断报告。</strong>仅做轻量对照，深度诊断需线下陪跑。
          </p>
        </div>
      </div>

      <section className="section">
        <div className="container" style={{ maxWidth: 720 }}>
          <div className="card">
            <h3>轻量对照（{items.length} 题）</h3>
            <p style={{ fontSize: 13, color: '#64748b' }}>每题选择最贴近现状的选项，结果仅作自我对照参考，不生成诊断报告。</p>
            <div style={{ marginTop: 16, display: 'grid', gap: 16 }}>
              {items.map(item => (
                <div key={item.id} style={{ border: '1px solid #e2e8f0', borderRadius: 10, padding: 16 }}>
                  <div style={{ fontSize: 12, color: '#0f6b5b', fontWeight: 800 }}>{item.dimension}</div>
                  <div style={{ fontWeight: 700, marginTop: 4 }}>{item.question}</div>
                  <div style={{ display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' }}>
                    {(item.options || ['A 较清晰/顺畅', 'M 部分卡点', 'B 待构建']).map((opt: any) => {
                      const label = typeof opt === 'string' ? opt : opt.label
                      return (
                      <label
                        key={label}
                        style={{
                          border: answers[item.id] === opt ? '1px solid #163E70' : '1px solid #e2e8f0',
                          background: answers[item.id] === opt ? '#eff6ff' : '#fff',
                          padding: '8px 12px',
                          borderRadius: 999,
                          fontSize: 13,
                          cursor: 'pointer',
                        }}
                      >
                        <input type="radio" name={item.id} value={label} checked={answers[item.id] === label} onChange={() => set(item.id, label)} style={{ marginRight: 6 }} />
                        {label}
                      </label>
                      )
                    })}
                  </div>
                </div>
              ))}
            </div>

            <button className="btn btn-primary" style={{ width: '100%', marginTop: 20 }} onClick={() => setShowResult(true)}>
              查看轻量对照结果
            </button>
            <p style={{ fontSize: 11, color: '#94a3b8', marginTop: 8, textAlign: 'center' }}>一期不做自动诊断报告，结果仅本地展示，不存储。</p>
          </div>

          {showResult && (
            <div className="card" style={{ marginTop: 16, background: '#f8fafc' }}>
              <h3>对照结果（占位示意）</h3>
              <p style={{ fontSize: 13, color: '#475569' }}>
                {cmsCheck?.logic_text || '基于你的选择，系统提示关注维度：'}
                <br />
                {Object.entries(answers)
                  .map(([k, v]) => `${items.find(i => i.id === k)?.dimension}：${v}`)
                  .join('；') || '（请选择后再查看）'}
              </p>
              <div className="placeholder" style={{ marginTop: 10 }}>
                {cmsCheck?.next_guide || '此处仅为轻量对照提示，不生成诊断报告。深度诊断请预约陪跑。'}
              </div>
              <div style={{ display: 'flex', gap: 10, marginTop: 12, flexWrap: 'wrap' }}>
                <Link to="/contact" className="btn btn-primary">
                  预约深度诊断
                </Link>
                <Link to="/evolution" className="btn btn-ghost">
                  了解进化坐标
                </Link>
              </div>
            </div>
          )}

          <div className="placeholder" style={{ marginTop: 16 }}>
            快速路径：看看你的企业 → 轻量对照 → 预约咨询 / 深度路径：企业进化 → 四大价值 → A/M/B → 联系我们（全链路已打通）
          </div>
        </div>
      </section>

      <GlobalCTA />
    </div>
  )
}
