import React, { useCallback, useMemo, useState } from 'react'
import { motion } from 'framer-motion'
import { FileText, Download, Lock, CheckCircle2 } from 'lucide-react'
import { Header } from '../components/Header'
import { Footer } from '../components/Footer'
import { usePageMeta } from '../hooks/usePageMeta'
import { getLocaleFromPathname, withLocalePath } from '../lib/i18n'
import { hasDownloadAccess } from '../lib/downloadGate'
import { PaymentQrModal } from '../components/PaymentQrModal'

const DOWNLOAD_KEY = 'htech-application-2026'
const FILE_NAME = '2026年高新技术企业认定申请表.pdf'
const FILE_PATH = '/downloads/2026-high-tech-enterprise-application-form.pdf'

function startFileDownload(absoluteOrPublicPath: string, fileName?: string) {
  const a = document.createElement('a')
  a.href = absoluteOrPublicPath
  if (fileName) a.download = fileName
  a.rel = 'noopener'
  document.body.appendChild(a)
  a.click()
  a.remove()
}

export const HighTechEnterprise: React.FC = () => {
  const locale = getLocaleFromPathname(window.location.pathname)
  const [payOpen, setPayOpen] = useState(false)
  const [downloadUnlocked, setDownloadUnlocked] = useState(() => hasDownloadAccess(DOWNLOAD_KEY))

  usePageMeta({
    title: locale === 'en' ? 'High-tech enterprise certification' : '高新技术企业认定要求',
    description:
      locale === 'en'
        ? 'High-tech enterprise certification requirements and download of the 2026 application form.'
        : '高新技术企业认定的核心要求说明，并提供 2026 年申请表下载入口。',
    locale,
  })

  const alreadyPaid = downloadUnlocked

  const handleDownloadClick = useCallback(() => {
    if (hasDownloadAccess(DOWNLOAD_KEY)) {
      setDownloadUnlocked(true)
      startFileDownload(FILE_PATH, FILE_NAME)
      return
    }

    setPayOpen(true)
  }, [])

  const breadcrumbHref = useMemo(() => withLocalePath(locale, '/services'), [locale])

  return (
    <motion.div className="min-h-screen bg-background" initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
      <Header />

      <main>
        <section className="pt-32 pb-10 bg-white border-b border-gray-100">
          <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
            <a href={breadcrumbHref} className="text-sm text-gray-500 hover:text-primary">
              {locale === 'en' ? 'Back to Services' : '返回服务范围'}
            </a>
            <h1 className="mt-3 text-3xl md:text-4xl font-semibold text-primary-dark">
              {locale === 'en' ? 'High-tech enterprise certification requirements' : '高新技术企业认定要求'}
            </h1>
            <p className="mt-4 text-gray-600 leading-relaxed">
              {locale === 'en'
                ? 'This page provides a simplified overview. Replace with official materials later.'
                : '本页为精简版概览，便于用户快速理解核心要求；后续可替换为完整政策解读与本地政策细则。'}
            </p>
          </div>
        </section>

        <section className="py-12">
          <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="grid lg:grid-cols-[1fr_360px] gap-8 items-start">
              <article className="bg-white rounded-2xl border border-gray-100 p-6 md:p-8">
                <h2 className="text-xl font-semibold text-primary-dark">{locale === 'en' ? 'Key points' : '核心要点（示例）'}</h2>

                <div className="mt-5 space-y-4 text-sm text-gray-700 leading-relaxed">
                  <div className="flex gap-3">
                    <CheckCircle2 className="mt-0.5 text-accent-dark" size={18} />
                    <p>
                      {locale === 'en'
                        ? 'Intellectual property, R&D activity, and revenue structure are commonly reviewed items.'
                        : '常见审核关注：知识产权布局、研发活动真实性、收入结构与高新产品（服务）比例等。'}
                    </p>
                  </div>
                  <div className="flex gap-3">
                    <CheckCircle2 className="mt-0.5 text-accent-dark" size={18} />
                    <p>
                      {locale === 'en'
                        ? 'R&D expense accounting should be consistent and traceable.'
                        : '研发费用归集口径需一致、可追溯，建议提前建立台账与证据链。'}
                    </p>
                  </div>
                  <div className="flex gap-3">
                    <CheckCircle2 className="mt-0.5 text-accent-dark" size={18} />
                    <p>
                      {locale === 'en'
                        ? 'Policies differ by region; always follow the latest local rules.'
                        : '各地细则可能存在差异，实际申报以最新的本地政策与平台要求为准。'}
                    </p>
                  </div>
                </div>

                <hr className="my-8 border-gray-100" />

                <h3 className="text-lg font-semibold text-primary-dark">{locale === 'en' ? 'Downloads' : '资料下载'}</h3>
                <p className="mt-2 text-sm text-gray-600">
                  {locale === 'en'
                    ? 'Download requires a 1 CNY payment via WeChat/Alipay.'
                    : '下载需支付 1 元（微信/支付宝均可）。'}
                </p>

                <div className="mt-4 rounded-2xl border border-gray-100 bg-background p-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                  <div className="flex items-start gap-3">
                    <div className="w-10 h-10 rounded-xl bg-white border border-gray-100 flex items-center justify-center">
                      <FileText size={20} className="text-primary" />
                    </div>
                    <div>
                      <div className="text-sm font-semibold text-primary-dark">{FILE_NAME}</div>
                      <div className="mt-1 text-xs text-gray-500">PDF · {locale === 'en' ? 'Form template' : '申请表模板'}</div>
                    </div>
                  </div>

                  <button
                    type="button"
                    onClick={handleDownloadClick}
                    className="inline-flex items-center justify-center gap-2 px-5 py-3 rounded-xl text-sm font-medium text-white bg-primary hover:bg-primary-light transition-colors"
                    aria-label="下载申请表"
                  >
                    {alreadyPaid ? <Download size={18} /> : <Lock size={18} />}
                    {alreadyPaid ? (locale === 'en' ? 'Download' : '下载') : locale === 'en' ? 'Pay & download' : '付费下载'}
                  </button>
                </div>
              </article>

              <aside className="bg-white rounded-2xl border border-gray-100 p-6">
                <div className="text-sm font-semibold text-primary-dark">{locale === 'en' ? 'Service scope' : '对应服务'}</div>
                <p className="mt-2 text-sm text-gray-600 leading-relaxed">
                  {locale === 'en'
                    ? 'Tech services: certification guidance, R&D accounting, and application material preparation.'
                    : '科技服务：认定辅导、研发费用归集、申报材料梳理与答疑支持。'}
                </p>
                <div className="mt-4 rounded-xl bg-background border border-gray-100 p-4 text-xs text-gray-500 leading-relaxed">
                  {locale === 'en'
                    ? 'Note: Payment is a front-end placeholder for now and does not verify actual payment.'
                    : '提示：当前“支付”仅为前端占位演示，不具备真实收款与到账校验能力。上线真实付费需对接支付回调与服务端验签。'}
                </div>
              </aside>
            </div>
          </div>
        </section>
      </main>

      <Footer />

      <PaymentQrModal
        open={payOpen}
        onClose={() => setPayOpen(false)}
        downloadKey={DOWNLOAD_KEY}
        title={FILE_NAME}
        amountCny={1}
        onPaid={() => {
          setDownloadUnlocked(true)
          setPayOpen(false)
          startFileDownload(FILE_PATH, FILE_NAME)
        }}
      />
    </motion.div>
  )
}

export default HighTechEnterprise
