'use client'

import { FormEvent, useEffect, useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { ImagePlus } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { apiBase, backend, type BackendNewsArticle, type BackendNewsCategory } from '@/lib/backend'

function slugify(value: string) {
  return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
}

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

function emptyNewsDraft() {
  return {
    id: '',
    title: '',
    slug: '',
    category: '',
    summary: '',
    content: '',
    authorName: '大连市大数据研究院',
    coverUrl: '',
    status: 'draft' as BackendNewsArticle['status'],
    featuredPosition: null as number | null,
    relatedArticleIds: [] as string[],
    publishedAt: '',
  }
}

export function NewsArticleForm({ articleId }: { articleId?: string }) {
  const router = useRouter()
  const [form, setForm] = useState(emptyNewsDraft)
  const [articles, setArticles] = useState<BackendNewsArticle[]>([])
  const [categories, setCategories] = useState<BackendNewsCategory[]>([])
  const [preview, setPreview] = useState(false)
  const [error, setError] = useState('')
  const [uploading, setUploading] = useState('')

  useEffect(() => {
    void Promise.all([backend.adminNews(), backend.adminNewsCategories()]).then(([result, categoryResult]) => {
      setArticles(result.items)
      setCategories(categoryResult.items)
      const activeCategories = categoryResult.items.filter((item) => item.status === 'active')
      if (!articleId) {
        if (activeCategories[0]) setForm((current) => ({ ...current, category: current.category || activeCategories[0].name }))
        return
      }
      const item = result.items.find((current) => current.id === articleId)
      if (!item) {
        setError('资讯不存在')
        return
      }
      setForm({
        id: item.id,
        title: item.title,
        slug: item.slug,
        category: item.category,
        summary: item.summary,
        content: item.content || '',
        authorName: item.authorName || '大连市大数据研究院',
        coverUrl: item.coverUrl || '',
        status: item.status,
        featuredPosition: item.featuredPosition || null,
        relatedArticleIds: item.relatedArticleIds || [],
        publishedAt: item.publishedAt || '',
      })
    }).catch((err) => setError(err instanceof Error ? err.message : '资讯加载失败'))
  }, [articleId])

  async function uploadNewsImage(file: File) {
    if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) {
      setError('图片只支持 JPG、PNG、WebP。')
      return ''
    }
    setUploading(file.name)
    setError('')
    try {
      const uploaded = await backend.uploadAdminFile(file)
      return absoluteApiUrl(uploaded.url)
    } catch (err) {
      setError(err instanceof Error ? err.message : '上传失败')
      return ''
    } finally {
      setUploading('')
    }
  }

  function addImageToContent(url: string) {
    setForm((current) => ({
      ...current,
      content: `${current.content}\n<p><img src="${url}" alt="${current.title || '文章图片'}" /></p>`.trim(),
    }))
  }

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const slug = form.slug || slugify(form.title)
    if (!slug) return
    try {
      const payload = {
        slug,
        title: form.title,
        category: form.category,
        categoryCode: categories.find((item) => item.name === form.category || item.code === form.category)?.code,
        summary: form.summary,
        content: form.content,
        authorName: form.authorName,
        coverUrl: form.coverUrl || null,
        status: form.status,
        featuredPosition: form.featuredPosition,
        relatedArticleIds: form.relatedArticleIds,
        publishedAt: form.publishedAt || null,
      }
      if (articleId) {
        await backend.updateAdminNews(articleId, payload)
      } else {
        await backend.createAdminNews(payload)
      }
      router.push('/admin/news')
    } catch (err) {
      setError(err instanceof Error ? err.message : '资讯保存失败')
    }
  }

  return (
    <AdminShell title={articleId ? '编辑资讯' : '新增资讯'} description="新增和编辑都在独立页面完成；资讯列表只负责查看、精选、上下架和删除。">
      <form className="border border-line bg-white" onSubmit={submit}>
        <div className="flex flex-wrap items-center justify-between gap-3 border-b border-line px-4 py-3">
          <div>
            <div className="text-base font-extrabold text-ink">{form.title || (articleId ? '编辑资讯' : '新增资讯')}</div>
            {error && <div className="mt-1 text-sm font-bold text-red-700">{error}</div>}
          </div>
          <div className="flex gap-2">
            <Link href="/admin/news" className="h-9 rounded-[4px] border border-line px-3 pt-2 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">返回列表</Link>
            <button type="button" onClick={() => setPreview((value) => !value)} className="h-9 rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">{preview ? '编辑正文' : '预览 HTML'}</button>
            <button className="h-9 rounded-[4px] bg-brand px-4 text-xs font-extrabold text-white hover:bg-brand-dark">保存资讯</button>
          </div>
        </div>

        <div className="grid gap-0 lg:grid-cols-[minmax(0,1fr)_420px]">
          <section className="space-y-4 px-5 py-5">
            <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" />
              </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 }))} placeholder="不填按标题生成" className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
              </label>
            </div>

            <div className="grid gap-4 md:grid-cols-3">
              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">分类</span>
                <select required value={form.category} onChange={(event) => setForm((current) => ({ ...current, category: event.target.value as BackendNewsArticle['category'] }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                  <option value="" disabled>请选择分类</option>
                  {[
                    ...categories.filter((item) => item.status === 'active'),
                    ...(form.category && !categories.some((item) => item.name === form.category) ? [{ code: form.category, name: form.category, description: '', sortOrder: 999, status: 'active' as const }] : []),
                  ].map((item) => <option key={item.code} value={item.name}>{item.name}</option>)}
                </select>
              </label>
              <label className="block">
                <span className="mb-2 block text-sm font-bold text-ink">发布人</span>
                <input value={form.authorName} onChange={(event) => setForm((current) => ({ ...current, authorName: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
              </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 as BackendNewsArticle['status'] }))} 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="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>
              <input
                type="file"
                accept="image/*"
                onChange={async (event) => {
                  const file = event.target.files?.[0]
                  if (!file) return
                  const url = await uploadNewsImage(file)
                  if (url) setForm((current) => ({ ...current, coverUrl: url }))
                  event.target.value = ''
                }}
                className="block w-full rounded-[4px] border border-line px-3 py-2 text-sm"
              />
            </label>

            <div>
              <div className="mb-2 flex items-center justify-between gap-3">
                <span className="text-sm font-bold text-ink">正文 HTML</span>
                <label className="inline-flex h-8 cursor-pointer items-center gap-2 rounded-[4px] border border-line px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
                  <ImagePlus className="h-3.5 w-3.5" />
                  插入图片
                  <input
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={async (event) => {
                      const file = event.target.files?.[0]
                      if (!file) return
                      const url = await uploadNewsImage(file)
                      if (url) addImageToContent(url)
                      event.target.value = ''
                    }}
                  />
                </label>
              </div>
              <textarea value={form.content} onChange={(event) => setForm((current) => ({ ...current, content: event.target.value }))} rows={14} className="w-full rounded-[4px] border border-line p-3 font-mono text-xs leading-6" placeholder="<p>正文段落</p>" />
            </div>
          </section>

          <aside className="border-t border-line bg-bg/50 px-5 py-5 lg:border-l lg:border-t-0">
            <div className="text-sm font-extrabold text-ink">预览与关联</div>
            <div className="mt-4 overflow-hidden rounded-[4px] border border-line bg-white">
              {form.coverUrl ? <div className="h-40 bg-cover bg-center" style={{ backgroundImage: `url(${form.coverUrl})` }} /> : <div className="grid h-40 place-items-center bg-bg text-xs font-bold text-soft">封面预览</div>}
              <div className="p-4">
                <div className="text-xs font-bold text-brand">{form.category} · {form.authorName}</div>
                <div className="mt-2 text-base font-extrabold leading-6 text-ink">{form.title || '文章标题'}</div>
                <p className="mt-2 text-xs leading-5 text-muted">{form.summary || '文章摘要'}</p>
              </div>
            </div>
            {preview && <div className="prose prose-sm mt-4 max-w-none rounded-[4px] border border-line bg-white p-4 text-sm leading-7" dangerouslySetInnerHTML={{ __html: form.content || '<p>暂无正文</p>' }} />}
            <div className="mt-5 text-xs font-extrabold text-soft">可选相关文章（最多 3 篇已发布）</div>
            <div className="mt-3 max-h-[260px] space-y-2 overflow-auto">
              {articles.filter((item) => item.id !== form.id && item.status === 'published').map((item) => (
                <label key={item.id} className="flex gap-2 rounded-[4px] border border-line bg-white p-2 text-xs font-bold text-muted">
                  <input
                    type="checkbox"
                    checked={form.relatedArticleIds.includes(item.id)}
                    disabled={!form.relatedArticleIds.includes(item.id) && form.relatedArticleIds.length >= 3}
                    onChange={(event) => setForm((current) => ({
                      ...current,
                      relatedArticleIds: event.target.checked ? [...current.relatedArticleIds, item.id].slice(0, 3) : current.relatedArticleIds.filter((id) => id !== item.id),
                    }))}
                  />
                  <span>{item.title}</span>
                </label>
              ))}
            </div>
          </aside>
        </div>
      </form>
      {uploading && <div className="mt-3 text-xs font-bold text-brand">正在上传：{uploading}</div>}
    </AdminShell>
  )
}
