'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Upload } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { apiBase, backend } from '@/lib/backend'
import type { CourseAccessState } from '@/types'

const accessStateOptions: { value: CourseAccessState; label: string }[] = [
  { value: 'closed', label: '不可购买' },
  { value: 'free', label: '免费' },
  { value: 'paid', label: '收费' },
]

const accessRows: {
  key: 'registered' | 'junior' | 'senior'
  label: string
  accessKey: 'registeredAccess' | 'juniorAccess' | 'seniorAccess'
  priceKey: 'registeredPriceAmount' | 'juniorPriceAmount' | 'seniorPriceAmount'
}[] = [
  { key: 'registered', label: '注册用户', accessKey: 'registeredAccess', priceKey: 'registeredPriceAmount' },
  { key: 'junior', label: '初级会员', accessKey: 'juniorAccess', priceKey: 'juniorPriceAmount' },
  { key: 'senior', label: '高级会员', accessKey: 'seniorAccess', priceKey: 'seniorPriceAmount' },
]

function normalizeAccessState(value: unknown): CourseAccessState {
  if (value === 'closed' || value === 'free' || value === 'paid') return value
  return 'paid'
}

function toSafeNumber(value: unknown) {
  const next = Number(value)
  if (!Number.isFinite(next)) return 0
  return Math.max(0, Math.round(next))
}

function displayYuan(value: unknown) {
  return (toSafeNumber(value) / 100).toFixed(2).replace(/\.00$/, '')
}

function accessDisplay(accessState: CourseAccessState) {
  if (accessState === 'free') return '免费'
  if (accessState === 'closed') return '不可购买'
  return '收费'
}

const emptyAgent = {
  slug: '',
  title: '',
  summary: '',
  scenarioTags: '',
  detailDescription: '',
  deliveryNote: '',
  registeredAccess: 'paid' as CourseAccessState,
  juniorAccess: 'paid' as CourseAccessState,
  seniorAccess: 'paid' as CourseAccessState,
  registeredPriceAmount: 0,
  juniorPriceAmount: 0,
  seniorPriceAmount: 0,
  coverUrl: '',
  redeemableByMember: false,
  recommended: false,
  sortOrder: 10,
  status: 'draft',
  productStatus: 'draft',
}

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

function isSupportedCoverImage(file: File) {
  return ['image/jpeg', 'image/png', 'image/webp'].includes(file.type)
}

function FieldHelp({ children }: { children: string }) {
  return <span className="mt-1 block text-xs font-bold text-soft">{children}</span>
}

export function AgentProductForm({ productId }: { productId?: string }) {
  const router = useRouter()
  const [form, setForm] = useState(emptyAgent)
  const [error, setError] = useState('')
  const [coverUploadStatus, setCoverUploadStatus] = useState('')

  function buildPayload() {
    const normalized = {
      registeredAccess: normalizeAccessState(form.registeredAccess),
      juniorAccess: normalizeAccessState(form.juniorAccess),
      seniorAccess: normalizeAccessState(form.seniorAccess),
      registeredPriceAmount: toSafeNumber(form.registeredPriceAmount),
      juniorPriceAmount: toSafeNumber(form.juniorPriceAmount),
      seniorPriceAmount: toSafeNumber(form.seniorPriceAmount),
    }
    const invalidPaidRow = accessRows.find((row) => normalized[row.accessKey] === 'paid' && normalized[row.priceKey] <= 0)
    if (invalidPaidRow) {
      throw new Error(`${invalidPaidRow.label}选择收费时，必须填写大于 0 的价格`)
    }

    return {
      ...form,
      ...normalized,
      registeredPriceAmount: normalized.registeredAccess === 'paid' ? normalized.registeredPriceAmount : 0,
      juniorPriceAmount: normalized.juniorAccess === 'paid' ? normalized.juniorPriceAmount : 0,
      seniorPriceAmount: normalized.seniorAccess === 'paid' ? normalized.seniorPriceAmount : 0,
      sortOrder: toSafeNumber(form.sortOrder),
    }
  }

  useEffect(() => {
    if (!productId) return
    void backend.adminAgentProducts().then((result) => {
      const item = result.items.find((current) => current.id === productId)
      if (!item) return
      setForm({
        slug: item.slug,
        title: item.title,
        summary: item.summary,
        scenarioTags: (item.scenarioTags || []).join('，'),
        detailDescription: item.detailDescription,
        deliveryNote: item.deliveryNote,
        registeredAccess: normalizeAccessState(item.registeredAccess),
        juniorAccess: normalizeAccessState(item.juniorAccess),
        seniorAccess: normalizeAccessState(item.seniorAccess),
        registeredPriceAmount: toSafeNumber(item.registeredPriceAmount ?? item.priceAmount),
        juniorPriceAmount: toSafeNumber(item.juniorPriceAmount ?? item.priceAmount),
        seniorPriceAmount: toSafeNumber(item.seniorPriceAmount ?? item.priceAmount),
        redeemableByMember: Boolean(item.redeemableByMember),
        recommended: item.recommended,
        sortOrder: toSafeNumber(item.sortOrder),
        status: item.status,
        productStatus: item.status,
        coverUrl: item.coverUrl,
      })
    }).catch((err) => setError(err instanceof Error ? err.message : '智能体加载失败'))
  }, [productId])

  return (
    <AdminShell title={productId ? '编辑智能体产品' : '新增智能体产品'} description="保存后用户端智能体列表、详情页和个人中心展示会全部同步更新。">
      <form
        className="border border-line bg-white"
        onSubmit={async (event) => {
          event.preventDefault()
          try {
            await backend.saveAdminAgentProduct(productId || null, buildPayload())
            router.push('/admin/products/agents')
          } catch (err) {
            setError(err instanceof Error ? err.message : '保存失败')
          }
        }}
      >
        <div className="grid gap-4 border-b border-line px-5 py-4 lg:grid-cols-[1fr_auto] lg:items-center">
          <div>
            <div className="text-base font-extrabold text-ink">{form.title || '智能体产品'}</div>
            <div className="mt-1 text-xs font-bold text-muted">每个身份可独立设置开放状态和价格，保存后用户端立即同步。</div>
          </div>
          <button className="h-9 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white hover:bg-brand-dark">保存智能体</button>
        </div>
        {error && <div className="mx-5 mt-4 border border-red-100 bg-red-50 px-3 py-2 text-sm font-bold text-red-700">{error}</div>}

        <div className="grid gap-0 lg:grid-cols-[minmax(0,1fr)_340px]">
          <section className="space-y-5 px-5 py-5">
            <div>
              <div className="mb-3 text-sm font-extrabold text-ink">基础信息</div>
              <div className="grid gap-4 md:grid-cols-2">
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">智能体标题</span>
                  <input value={form.title} onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))} required className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                  <FieldHelp>显示在列表、详情页和订单中。</FieldHelp>
                </label>
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">Slug</span>
                  <input value={form.slug} onChange={(event) => setForm((current) => ({ ...current, slug: event.target.value }))} required className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                  <FieldHelp>用于详情页路径，例如 /agents/&#123;slug&#125;。</FieldHelp>
                </label>
              </div>
            </div>

            <label className="block">
              <span className="mb-2 block text-sm font-bold text-ink">列表摘要</span>
              <textarea value={form.summary} onChange={(event) => setForm((current) => ({ ...current, summary: event.target.value }))} required rows={3} className="w-full rounded-[4px] border border-line p-3 text-sm" />
            </label>

            <label className="block">
              <span className="mb-2 block text-sm font-bold text-ink">产品描述</span>
              <textarea value={form.detailDescription} onChange={(event) => setForm((current) => ({ ...current, detailDescription: event.target.value }))} rows={4} placeholder="给用户展示的产品说明" className="w-full rounded-[4px] border border-line p-3 text-sm" />
              <FieldHelp>详情页会展示此文案。</FieldHelp>
            </label>

            <label className="block">
              <span className="mb-2 block text-sm font-bold text-ink">交付说明</span>
              <textarea value={form.deliveryNote} onChange={(event) => setForm((current) => ({ ...current, deliveryNote: event.target.value }))} required rows={3} placeholder="例如：购买后进入交付流程，提交业务信息并跟进。" className="w-full rounded-[4px] border border-line p-3 text-sm" />
            </label>

            <label className="block">
              <span className="mb-2 block text-sm font-bold text-ink">场景标签</span>
              <input value={form.scenarioTags} onChange={(event) => setForm((current) => ({ ...current, scenarioTags: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
              <FieldHelp>多个标签请用中文逗号、英文逗号分隔。</FieldHelp>
            </label>

            <div>
              <div className="mb-3 text-sm font-extrabold text-ink">访问权限和分层价格（元）</div>
              <div className="divide-y divide-line border border-line bg-white">
                {accessRows.map((row) => {
                  const accessState = normalizeAccessState(form[row.accessKey])
                  const isPaid = accessState === 'paid'
                  const priceValue = toSafeNumber(form[row.priceKey])
                  return (
                    <div key={row.key} className="grid gap-3 p-3 md:grid-cols-[100px_150px_1fr] md:items-center">
                      <div className="text-sm font-extrabold text-ink">{row.label}</div>
                      <select
                        value={accessState}
                        onChange={(event) => setForm((current) => ({ ...current, [row.accessKey]: event.target.value as CourseAccessState }))}
                        className="h-10 w-full rounded-[4px] border border-line px-3 text-sm font-bold"
                      >
                        {accessStateOptions.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
                      </select>
                      {isPaid ? (
                        <label className="block">
                          <span className="sr-only">{row.label}价格</span>
                          <input
                            value={displayYuan(priceValue)}
                            onChange={(event) => setForm((current) => ({ ...current, [row.priceKey]: toSafeNumber(event.target.value) * 100 }))}
                            type="number"
                            min="0"
                            placeholder="价格（元）"
                            className="h-10 w-full rounded-[4px] border border-line px-3 text-sm"
                          />
                          <FieldHelp>{priceValue > 0 ? `${row.label}购买金额为：¥${Math.max(0, Math.round(priceValue / 100))}` : '收费必须填写大于 0 的价格，否则不能保存。'}</FieldHelp>
                        </label>
                      ) : (
                        <div>
                          <div className="flex h-10 items-center rounded-[4px] border border-line bg-bg px-3 text-sm font-extrabold text-muted">
                            {accessDisplay(accessState)}
                          </div>
                          <FieldHelp>{accessState === 'free' ? `${row.label}免费使用，不进入付费价格。` : `${row.label}不可购买，结算会直接拒绝。`}</FieldHelp>
                        </div>
                      )}
                    </div>
                  )
                })}
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">排序</span>
                <input
                  value={form.sortOrder}
                  onChange={(event) => setForm((current) => ({ ...current, sortOrder: Number(event.target.value || 0) }))}
                  type="number"
                  min="0"
                  className="h-10 w-full rounded-[4px] border border-line px-3 text-sm"
                />
                <FieldHelp>保存后会占用这个排序号，已有同号和后续商品自动后移。</FieldHelp>
              </label>
              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">状态</span>
                <select value={form.status} onChange={(event) => setForm((current) => ({ ...current, status: event.target.value, productStatus: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                  <option value="draft">草稿</option>
                  <option value="published">发布</option>
                  <option value="offline">下架</option>
                </select>
              </label>
            </div>

            <label className="mt-1 flex items-center gap-2 text-sm font-bold text-ink">
              <input
                type="checkbox"
                checked={form.recommended}
                onChange={(event) => setForm((current) => ({ ...current, recommended: event.target.checked }))}
              />
              首页推荐卡片展示
            </label>

            <label className="mt-1 flex items-center gap-2 text-sm font-bold text-ink">
              <input
                type="checkbox"
                checked={form.redeemableByMember}
                onChange={(event) => setForm((current) => ({ ...current, redeemableByMember: event.target.checked }))}
              />
              允许使用会员智能体额度兑换
            </label>

          </section>

          <aside className="border-l border-line bg-bg/40 p-5">
            <div className="space-y-4">
              <div>
                <div className="text-sm font-extrabold text-ink">封面图（上传）</div>
                <div className="mt-2 text-xs text-muted">只支持 JPG、PNG、WebP，上传后数据库保存后端资源地址。</div>
                <label className="mt-3 inline-flex h-10 cursor-pointer items-center gap-2 rounded-[4px] border border-line bg-white px-4 text-sm font-extrabold text-ink hover:border-brand hover:text-brand">
                  <Upload className="h-4 w-4" />
                  {coverUploadStatus || (form.coverUrl ? '重新上传封面' : '上传封面')}
                  <input
                    type="file"
                    accept="image/jpeg,image/png,image/webp"
                    onChange={async (event) => {
                      const file = event.target.files?.[0]
                      if (!file) return
                      if (!isSupportedCoverImage(file)) {
                        setError('封面只支持 JPG、PNG 或 WebP。')
                        event.target.value = ''
                        return
                      }
                      setCoverUploadStatus('上传中...')
                      try {
                        const uploaded = await backend.uploadAdminFile(file)
                        setForm((current) => ({ ...current, coverUrl: absoluteApiUrl(uploaded.url) }))
                        setCoverUploadStatus(`已上传：${uploaded.fileName}`)
                      } catch (err) {
                        setCoverUploadStatus('')
                        setError(err instanceof Error ? err.message : '封面上传失败')
                      } finally {
                        event.target.value = ''
                      }
                    }}
                    className="sr-only"
                  />
                </label>
              </div>

              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">当前封面（预览）</span>
                <input value={form.coverUrl} readOnly className="h-10 w-full rounded-[4px] border border-line bg-bg px-3 text-xs text-muted" />
              </label>

              <div className="rounded-[4px] border border-line bg-white p-3">
                <div className="text-xs font-bold text-muted">当前配置</div>
                <div className="mt-2 text-sm text-ink">
                  注册用户：{accessDisplay(normalizeAccessState(form.registeredAccess))} /
                  初级会员：{accessDisplay(normalizeAccessState(form.juniorAccess))} /
                  高级会员：{accessDisplay(normalizeAccessState(form.seniorAccess))}
                </div>
                <div className="mt-2 text-xs text-muted">
                  价格（元）：¥{Math.max(0, Math.round(form.registeredPriceAmount / 100))} / ¥{Math.max(0, Math.round(form.juniorPriceAmount / 100))} / ¥{Math.max(0, Math.round(form.seniorPriceAmount / 100))}
                </div>
                <div className="mt-4 text-xs text-soft">保存后会同步到前端用户端、购物车和结算页面。</div>
              </div>
            </div>
          </aside>
        </div>
      </form>
    </AdminShell>
  )
}
