'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { ExternalLink, FileText, RefreshCw, Save, SlidersHorizontal, Upload } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { apiBase, backend, type BackendDataServiceCase, type BackendDataServicePage, type BackendSiteHomeAsset, type BackendSitePageBlock } from '@/lib/backend'

const emptyPage: BackendDataServicePage = { blocks: [], assets: [] }
const heroKeys = ['data_service_hero_1', 'data_service_hero_2', 'data_service_hero_3']

function absoluteApiUrl(path: string) {
  if (/^https?:\/\//.test(path) || path.startsWith('data:')) return path
  return `${apiBase.replace(/\/api$/, '')}${path}`
}

function sortByOrder<T extends { sortOrder: number }>(items: T[]) {
  return [...items].sort((a, b) => a.sortOrder - b.sortOrder)
}

function blockByKey(page: BackendDataServicePage, key: string) {
  return page.blocks.find((block) => block.blockKey === key)
}

function summarizeCases(items: BackendDataServiceCase[]) {
  return {
    total: items.length,
    published: items.filter((item) => item.status === 'published').length,
    draft: items.filter((item) => item.status === 'draft').length,
    offline: items.filter((item) => item.status === 'offline').length,
  }
}

export default function AdminDataServicePageConfigPage() {
  const [page, setPage] = useState<BackendDataServicePage>(emptyPage)
  const [caseSummary, setCaseSummary] = useState(() => summarizeCases([]))
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [uploading, setUploading] = useState('')
  const [error, setError] = useState('')
  const [message, setMessage] = useState('')

  async function reload() {
    setLoading(true)
    setError('')
    try {
      const [result, cases] = await Promise.all([
        backend.adminDataServicePage(),
        backend.adminDataServiceCases().catch(() => ({ items: [] as BackendDataServiceCase[] })),
      ])
      setPage({ blocks: sortByOrder(result.blocks || []), assets: sortByOrder(result.assets || []) })
      setCaseSummary(summarizeCases(cases.items || []))
    } catch (err) {
      setError(err instanceof Error ? err.message : '数据服务页面配置加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { void reload() }, [])

  const pageBlock = useMemo(() => blockByKey(page, 'data_service_page'), [page])
  const applyBlock = useMemo(() => blockByKey(page, 'data_service_apply'), [page])
  const heroAssets = useMemo<BackendSiteHomeAsset[]>(() => heroKeys.map((key, index) => {
    const asset = page.assets.find((item) => item.key === key)
    return asset || {
      key,
      label: `数据服务主视觉 ${index + 1}`,
      title: `数据服务主视觉 ${index + 1}`,
      description: '',
      imageUrl: '',
      sortOrder: (index + 1) * 10,
      status: index === 0 ? 'published' : 'hidden',
    }
  }), [page.assets])

  function updateBlock(blockKey: string, patch: Partial<BackendSitePageBlock>) {
    setPage((current) => ({
      ...current,
      blocks: current.blocks.map((block) => block.blockKey === blockKey ? { ...block, ...patch } : block),
    }))
  }

  function updateBlockMetadata(blockKey: string, key: string, value: string) {
    setPage((current) => ({
      ...current,
      blocks: current.blocks.map((block) => block.blockKey === blockKey
        ? { ...block, metadata: { ...(block.metadata || {}), [key]: value } }
        : block),
    }))
  }

  function updateApplyCta(value: string) {
    setPage((current) => ({
      ...current,
      blocks: current.blocks.map((block) => block.blockKey === 'data_service_apply'
        ? {
          ...block,
          items: (block.items?.length ? block.items : [{
            itemKey: 'primary_cta',
            title: '数据服务申请',
            subtitle: '',
            description: '',
            imageUrl: '',
            href: '/data/apply',
            ctaLabel: value,
            status: 'published' as const,
            sortOrder: 10,
            metadata: {},
          }]).map((item, index) => index === 0 ? { ...item, ctaLabel: value, href: '/data/apply' } : item),
        }
        : block),
    }))
  }

  function updateAsset(assetKey: string, patch: Partial<BackendSiteHomeAsset>) {
    setPage((current) => {
      const exists = current.assets.some((asset) => asset.key === assetKey)
      const nextAssets = exists
        ? current.assets.map((asset) => asset.key === assetKey ? { ...asset, ...patch } : asset)
        : [...current.assets, { ...(heroAssets.find((asset) => asset.key === assetKey) as BackendSiteHomeAsset), ...patch }]
      return { ...current, assets: nextAssets }
    })
  }

  async function uploadHero(file: File, assetKey: string) {
    if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) {
      setError('主视觉只支持 JPG、PNG、WebP。')
      return
    }
    setUploading(assetKey)
    setError('')
    try {
      const uploaded = await backend.uploadAdminFile(file)
      updateAsset(assetKey, { imageUrl: absoluteApiUrl(uploaded.url), status: 'published' })
    } catch (err) {
      setError(err instanceof Error ? err.message : '上传失败')
    } finally {
      setUploading('')
    }
  }

  async function save() {
    setSaving(true)
    setError('')
    setMessage('')
    try {
      const saved = await backend.saveAdminDataServicePage({
        blocks: sortByOrder(page.blocks || []),
        assets: sortByOrder(heroAssets),
      })
      setPage({ blocks: sortByOrder(saved.blocks || []), assets: sortByOrder(saved.assets || []) })
      setMessage('数据服务页面已保存，用户端 /data 会读取这份配置。')
    } catch (err) {
      setError(err instanceof Error ? err.message : '保存失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <AdminShell title="数据页面维护" description="维护用户端 /data 的主视觉、页面文案、案例区标题和申请 CTA。">
      <div className="flex h-[calc(100vh-178px)] min-h-[620px] flex-col overflow-hidden">
        <div className="mb-3 flex shrink-0 flex-wrap items-center justify-between gap-2 border border-line bg-white px-3 py-2">
          <div className="text-xs font-bold text-muted">
            页面只做案例参考和需求申请，不提供现货售卖；保存后直接影响用户端 `/data`。
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <Link href="/data" target="_blank" className="inline-flex h-8 items-center gap-1.5 rounded-[4px] border border-line px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">
              <ExternalLink className="h-3.5 w-3.5" />
              预览
            </Link>
            <Link href="/admin/data-service/cases" className="inline-flex h-8 items-center gap-1.5 rounded-[4px] border border-line px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">
              <FileText className="h-3.5 w-3.5" />
              案例维护
            </Link>
            <button type="button" onClick={() => void reload()} className="inline-flex h-8 items-center gap-1.5 rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
              <RefreshCw className="h-3.5 w-3.5" />
              {loading ? '刷新中' : '刷新'}
            </button>
            <button type="button" onClick={() => void save()} disabled={saving} className="inline-flex h-8 items-center gap-1.5 rounded-[4px] bg-brand px-3 text-xs font-extrabold text-white hover:bg-brand-dark disabled:bg-line-dark">
              <Save className="h-3.5 w-3.5" />
              {saving ? '保存中' : '保存'}
            </button>
          </div>
        </div>
        {(error || message) && (
          <div className={`mb-3 shrink-0 border px-3 py-2 text-xs font-bold ${error ? 'border-red-200 bg-red-50 text-red-700' : 'border-green-100 bg-green-50 text-green'}`}>
            {error || message}
          </div>
        )}

        <div className="grid min-h-0 flex-1 gap-3 lg:grid-cols-[minmax(0,1fr)_360px]">
          <div className="min-h-0 overflow-y-auto border border-line bg-white">
            <div className="border-b border-line px-4 py-3">
              <div className="text-sm font-extrabold text-ink">页面内容</div>
              <div className="mt-1 text-xs font-bold text-soft">维护首屏文案、案例区说明和底部申请卡片。</div>
            </div>
            <div className="grid gap-4 p-4">
              <section className="grid gap-3">
                <div className="text-xs font-extrabold text-brand">首屏</div>
                <label className="grid gap-1">
                  <span className="text-xs font-bold text-muted">页面标题</span>
                  <input value={pageBlock?.title || ''} onChange={(event) => updateBlock('data_service_page', { title: event.target.value })} className="h-9 rounded-[4px] border border-line px-3 text-sm font-bold" />
                </label>
                <label className="grid gap-1">
                  <span className="text-xs font-bold text-muted">一句话说明</span>
                  <input value={pageBlock?.subtitle || ''} onChange={(event) => updateBlock('data_service_page', { subtitle: event.target.value })} className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                </label>
                <label className="grid gap-1">
                  <span className="text-xs font-bold text-muted">页面解释</span>
                  <textarea value={pageBlock?.body || ''} onChange={(event) => updateBlock('data_service_page', { body: event.target.value })} rows={4} className="rounded-[4px] border border-line p-3 text-sm leading-6" />
                </label>
              </section>

              <section className="grid gap-3 border-t border-line pt-4">
                <div className="text-xs font-extrabold text-brand">案例区</div>
                <div className="grid gap-3 md:grid-cols-2">
                  <label className="grid gap-1">
                    <span className="text-xs font-bold text-muted">案例区标题</span>
                    <input value={String(pageBlock?.metadata?.casesTitle || '')} onChange={(event) => updateBlockMetadata('data_service_page', 'casesTitle', event.target.value)} className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                  </label>
                  <label className="grid gap-1">
                    <span className="text-xs font-bold text-muted">显示状态</span>
                    <select value={pageBlock?.status || 'published'} onChange={(event) => updateBlock('data_service_page', { status: event.target.value as BackendSitePageBlock['status'] })} className="h-9 rounded-[4px] border border-line px-3 text-sm">
                      <option value="published">显示</option>
                      <option value="hidden">隐藏</option>
                    </select>
                  </label>
                </div>
                <label className="grid gap-1">
                  <span className="text-xs font-bold text-muted">案例区说明</span>
                  <textarea value={String(pageBlock?.metadata?.casesDescription || '')} onChange={(event) => updateBlockMetadata('data_service_page', 'casesDescription', event.target.value)} rows={3} className="rounded-[4px] border border-line p-3 text-sm leading-6" />
                </label>
                <div className="border border-line bg-bg/60 px-3 py-2">
                  <div className="flex flex-wrap items-center justify-between gap-2">
                    <div>
                      <div className="text-xs font-extrabold text-ink">案例维护概览</div>
                      <div className="mt-1 text-[11px] font-bold text-soft">用户端案例区读取已发布案例；草稿和下线不会展示。</div>
                    </div>
                    <Link href="/admin/data-service/cases" className="inline-flex h-8 items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">
                      <FileText className="h-3.5 w-3.5" />
                      管理案例
                    </Link>
                  </div>
                  <div className="mt-2 grid grid-cols-4 gap-2 text-center text-[11px] font-bold">
                    <div className="border border-line bg-white py-2"><span className="block text-base font-extrabold text-ink">{caseSummary.total}</span>全部</div>
                    <div className="border border-line bg-white py-2"><span className="block text-base font-extrabold text-green">{caseSummary.published}</span>已发布</div>
                    <div className="border border-line bg-white py-2"><span className="block text-base font-extrabold text-muted">{caseSummary.draft}</span>草稿</div>
                    <div className="border border-line bg-white py-2"><span className="block text-base font-extrabold text-soft">{caseSummary.offline}</span>下线</div>
                  </div>
                </div>
              </section>

              <section className="grid gap-3 border-t border-line pt-4">
                <div className="text-xs font-extrabold text-brand">申请 CTA</div>
                <div className="grid gap-3 md:grid-cols-2">
                  <label className="grid gap-1">
                    <span className="text-xs font-bold text-muted">CTA 标题</span>
                    <input value={applyBlock?.title || ''} onChange={(event) => updateBlock('data_service_apply', { title: event.target.value })} className="h-9 rounded-[4px] border border-line px-3 text-sm font-bold" />
                  </label>
                  <label className="grid gap-1">
                    <span className="text-xs font-bold text-muted">按钮文案</span>
                    <input value={applyBlock?.items?.[0]?.ctaLabel || ''} onChange={(event) => updateApplyCta(event.target.value)} className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                  </label>
                </div>
                <label className="grid gap-1">
                  <span className="text-xs font-bold text-muted">CTA 说明</span>
                  <textarea value={applyBlock?.body || ''} onChange={(event) => updateBlock('data_service_apply', { body: event.target.value })} rows={3} className="rounded-[4px] border border-line p-3 text-sm leading-6" />
                </label>
                <label className="grid gap-1">
                  <span className="text-xs font-bold text-muted">CTA 备注</span>
                  <input value={applyBlock?.subtitle || ''} onChange={(event) => updateBlock('data_service_apply', { subtitle: event.target.value })} className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                </label>
              </section>
            </div>
          </div>

          <aside className="grid min-h-0 grid-rows-[minmax(0,1fr)_auto] gap-3">
            <section className="min-h-0 overflow-y-auto border border-line bg-white">
              <div className="border-b border-line px-4 py-3">
                <div className="text-sm font-extrabold text-ink">主视觉</div>
                <div className="mt-1 text-xs font-bold text-soft">最多三张，用户端按排序轮播；隐藏图不会显示。</div>
              </div>
              <div className="grid gap-3 p-4">
                {heroAssets.map((asset) => (
                  <div key={asset.key} className="border border-line bg-bg/60 p-3">
                    <div className="h-28 rounded-[4px] border border-line bg-white bg-cover bg-center" style={{ backgroundImage: asset.imageUrl ? `url(${asset.imageUrl})` : undefined }}>
                      {!asset.imageUrl && <div className="grid h-full place-items-center text-xs font-bold text-soft">暂无图片</div>}
                    </div>
                    <div className="mt-3 grid gap-2">
                      <input value={asset.title} onChange={(event) => updateAsset(asset.key, { title: event.target.value, label: event.target.value })} className="h-8 rounded-[4px] border border-line px-2 text-xs font-bold" />
                      <div className="grid grid-cols-[1fr_86px] gap-2">
                        <select value={asset.status} onChange={(event) => updateAsset(asset.key, { status: event.target.value as BackendSiteHomeAsset['status'] })} className="h-8 rounded-[4px] border border-line px-2 text-xs">
                          <option value="published">显示</option>
                          <option value="hidden">隐藏</option>
                        </select>
                        <input value={asset.sortOrder} onChange={(event) => updateAsset(asset.key, { sortOrder: Number(event.target.value || 0) })} type="number" className="h-8 rounded-[4px] border border-line px-2 text-xs" />
                      </div>
                      <label className="inline-flex h-8 cursor-pointer items-center justify-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">
                        <Upload className="h-3.5 w-3.5" />
                        {uploading === asset.key ? '上传中' : asset.imageUrl ? '重传图片' : '上传图片'}
                        <input type="file" accept="image/jpeg,image/png,image/webp" className="sr-only" onChange={(event) => {
                          const file = event.target.files?.[0]
                          if (file) void uploadHero(file, asset.key)
                          event.target.value = ''
                        }} />
                      </label>
                    </div>
                  </div>
                ))}
              </div>
            </section>

            <section className="border border-line bg-white p-3">
              <div className="grid grid-cols-2 gap-2">
                <Link href="/admin/data-service/cases" className="inline-flex h-8 items-center justify-center gap-1.5 rounded-[4px] border border-line text-xs font-extrabold text-ink hover:border-brand hover:text-brand">
                  <FileText className="h-3.5 w-3.5" />
                  案例
                </Link>
                <Link href="/admin/data-service/options" className="inline-flex h-8 items-center justify-center gap-1.5 rounded-[4px] border border-line text-xs font-extrabold text-ink hover:border-brand hover:text-brand">
                  <SlidersHorizontal className="h-3.5 w-3.5" />
                  选项
                </Link>
              </div>
            </section>
          </aside>
        </div>
      </div>
    </AdminShell>
  )
}
