'use client'

import { useEffect, useState } from 'react'
import { Plus, Upload } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { apiBase, backend, type BackendSiteAbout, type BackendSiteAboutItem } from '@/lib/backend'

type AboutListKey = 'workSteps' | 'serviceObjects' | 'representativeWork' | 'cooperationModes' | 'honors' | 'partners' | 'team'

const emptyAbout: BackendSiteAbout = {
  content: {
    heroTitle: '',
    heroDescription: '',
    heroExplanation: '',
    heroCoverUrl: '',
    workTitle: '',
    workDescription: '',
    workImageUrl: '',
    serviceTitle: '',
    serviceDescription: '',
    contactAddress: '',
    contactPhone: '',
    contactEmail: '',
    contactHours: '',
  },
  workSteps: [],
  serviceObjects: [],
  representativeWork: [],
  cooperationModes: [],
  honors: [],
  partners: [],
  team: [],
}

const sectionConfigs: { key: AboutListKey; payloadKey: string; title: string; description: string; withImage?: boolean; withRole?: boolean; compact?: boolean }[] = [
  { key: 'workSteps', payloadKey: 'work_steps', title: '工作方式四个步骤', description: '右侧 01-04 的标题和描述。' },
  { key: 'serviceObjects', payloadKey: 'service_objects', title: '服务对象标签', description: '服务与成果沉淀左侧标签。', compact: true },
  { key: 'representativeWork', payloadKey: 'representative_work', title: '代表成果', description: '服务与成果沉淀右侧第一组条目。' },
  { key: 'cooperationModes', payloadKey: 'cooperation_modes', title: '合作方式', description: '服务与成果沉淀右侧第二组条目。' },
  { key: 'honors', payloadKey: 'honors', title: '资质荣誉', description: '支持图片、标题、隐藏、删除和排序。', withImage: true, compact: true },
  { key: 'partners', payloadKey: 'partners', title: '合作伙伴', description: '支持 Logo/图片、标题、隐藏、删除和排序。', withImage: true, compact: true },
  { key: 'team', payloadKey: 'team', title: '核心团队', description: '支持增加行数，每项维护照片、姓名、职位和描述。', withImage: true, withRole: true },
]

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

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

export default function AdminSiteAboutPage() {
  const [about, setAbout] = useState<BackendSiteAbout>(emptyAbout)
  const [error, setError] = useState('')
  const [saving, setSaving] = useState(false)
  const [uploading, setUploading] = useState('')

  useEffect(() => {
    void backend.adminSiteAbout().then((result) => setAbout({
      ...result,
      workSteps: sortItems(result.workSteps),
      serviceObjects: sortItems(result.serviceObjects),
      representativeWork: sortItems(result.representativeWork),
      cooperationModes: sortItems(result.cooperationModes),
      honors: sortItems(result.honors),
      partners: sortItems(result.partners),
      team: sortItems(result.team),
    })).catch((err) => setError(err instanceof Error ? err.message : '关于我们配置加载失败'))
  }, [])

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

  function updateContent(patch: Partial<BackendSiteAbout['content']>) {
    setAbout((current) => ({ ...current, content: { ...current.content, ...patch } }))
  }

  function updateItem(key: AboutListKey, index: number, patch: Partial<BackendSiteAboutItem>) {
    setAbout((current) => ({
      ...current,
      [key]: current[key].map((item, itemIndex) => itemIndex === index ? { ...item, ...patch } : item),
    }))
  }

  function addItem(key: AboutListKey, section: string) {
    setAbout((current) => ({
      ...current,
      [key]: [
        ...current[key],
        {
          id: `${section}-${Date.now()}`,
          section,
          title: '',
          description: '',
          imageUrl: '',
          sortOrder: (current[key].length + 1) * 10,
          status: 'published',
          role: '',
          metadata: {},
        },
      ],
    }))
  }

  function removeItem(key: AboutListKey, index: number) {
    setAbout((current) => ({
      ...current,
      [key]: current[key].filter((_, itemIndex) => itemIndex !== index),
    }))
  }

  async function save() {
    setSaving(true)
    setError('')
    try {
      const payload = {
        ...about,
        work_steps: sortItems(about.workSteps),
        service_objects: sortItems(about.serviceObjects),
        representative_work: sortItems(about.representativeWork),
        cooperation_modes: sortItems(about.cooperationModes),
        honors: sortItems(about.honors),
        partners: sortItems(about.partners),
        team: sortItems(about.team),
      }
      const saved = await backend.saveAdminSiteAbout(payload as unknown as BackendSiteAbout)
      setAbout(saved)
    } catch (err) {
      setError(err instanceof Error ? err.message : '保存失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <AdminShell title="关于我们配置" description="维护关于我们页全部文字、图片、荣誉、伙伴、团队和联系方式，前台排版保持不变。">
      <div className="space-y-4">
        <div className="flex items-center justify-between border border-line bg-white px-4 py-3">
          <div className="text-sm font-extrabold text-ink">关于我们页面配置</div>
          <button type="button" onClick={save} disabled={saving} className="h-8 rounded-[4px] bg-brand px-4 text-xs font-extrabold text-white disabled:bg-line-dark">
            {saving ? '保存中...' : '保存关于我们'}
          </button>
        </div>
        {error && <div className="border border-red-100 bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}

        <section className="border border-line bg-white">
          <div className="border-b border-line px-4 py-3 text-sm font-extrabold text-ink">基础内容</div>
          <div className="grid gap-4 px-4 py-4 lg:grid-cols-2">
            <label className="block">
              <span className="mb-1 block text-xs font-extrabold text-soft">第一部分标题</span>
              <input value={about.content.heroTitle} onChange={(event) => updateContent({ heroTitle: event.target.value })} className="h-9 w-full rounded-[4px] border border-line px-3 text-sm" />
            </label>
            <label className="block">
              <span className="mb-1 block text-xs font-extrabold text-soft">服务成果标题</span>
              <input value={about.content.serviceTitle} onChange={(event) => updateContent({ serviceTitle: event.target.value })} className="h-9 w-full rounded-[4px] border border-line px-3 text-sm" />
            </label>
            <label className="block lg:col-span-2">
              <span className="mb-1 block text-xs font-extrabold text-soft">第一部分描述</span>
              <textarea value={about.content.heroDescription} onChange={(event) => updateContent({ heroDescription: event.target.value })} rows={3} className="w-full rounded-[4px] border border-line p-3 text-sm" />
            </label>
            <label className="block lg:col-span-2">
              <span className="mb-1 block text-xs font-extrabold text-soft">第一部分解释</span>
              <textarea value={about.content.heroExplanation} onChange={(event) => updateContent({ heroExplanation: event.target.value })} rows={3} className="w-full rounded-[4px] border border-line p-3 text-sm" />
            </label>
            <label className="block">
              <span className="mb-1 block text-xs font-extrabold text-soft">工作方式标题</span>
              <input value={about.content.workTitle} onChange={(event) => updateContent({ workTitle: event.target.value })} className="h-9 w-full rounded-[4px] border border-line px-3 text-sm" />
            </label>
            <label className="block">
              <span className="mb-1 block text-xs font-extrabold text-soft">工作方式描述</span>
              <input value={about.content.workDescription} onChange={(event) => updateContent({ workDescription: event.target.value })} className="h-9 w-full rounded-[4px] border border-line px-3 text-sm" />
            </label>
            <label className="block lg:col-span-2">
              <span className="mb-1 block text-xs font-extrabold text-soft">服务成果描述</span>
              <textarea value={about.content.serviceDescription} onChange={(event) => updateContent({ serviceDescription: event.target.value })} rows={3} className="w-full rounded-[4px] border border-line p-3 text-sm" />
            </label>
            <ImageUploadRow label="第一部分封面图片" value={about.content.heroCoverUrl} uploading={uploading} onUpload={(file) => uploadImage(file, (url) => updateContent({ heroCoverUrl: url }))} />
            <ImageUploadRow label="工作方式图片" value={about.content.workImageUrl} uploading={uploading} onUpload={(file) => uploadImage(file, (url) => updateContent({ workImageUrl: url }))} />
          </div>
        </section>

        <section className="border border-line bg-white">
          <div className="border-b border-line px-4 py-3 text-sm font-extrabold text-ink">联系信息</div>
          <div className="grid gap-4 px-4 py-4 md:grid-cols-2">
            {[
              ['地址', 'contactAddress'],
              ['电话', 'contactPhone'],
              ['邮箱', 'contactEmail'],
              ['工作时间', 'contactHours'],
            ].map(([label, key]) => (
              <label key={key} className="block">
                <span className="mb-1 block text-xs font-extrabold text-soft">{label}</span>
                <input value={String(about.content[key as keyof typeof about.content] || '')} onChange={(event) => updateContent({ [key]: event.target.value })} className="h-9 w-full rounded-[4px] border border-line px-3 text-sm" />
              </label>
            ))}
          </div>
        </section>

        {sectionConfigs.map((section) => (
          <section key={section.key} className="border border-line bg-white">
            <div className="flex items-center justify-between border-b border-line px-4 py-3">
              <div>
                <div className="text-sm font-extrabold text-ink">{section.title}</div>
                <div className="mt-1 text-xs font-bold text-soft">{section.description}</div>
              </div>
              <button type="button" onClick={() => addItem(section.key, section.payloadKey)} 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">
                <Plus className="h-3.5 w-3.5" />
                添加
              </button>
            </div>
            <div className="divide-y divide-line">
              {about[section.key].map((item, index) => (
                <div key={item.id} className={`grid gap-3 px-4 py-3 ${section.withImage ? 'lg:grid-cols-[88px_1fr_110px_100px_130px]' : 'lg:grid-cols-[1fr_110px_100px_70px]'} lg:items-start`}>
                  {section.withImage && (
                    <div className="h-16 rounded-[4px] border border-line bg-cover bg-center" style={{ backgroundImage: item.imageUrl ? `url(${item.imageUrl})` : undefined }}>
                      {!item.imageUrl && <div className="grid h-full place-items-center text-[11px] font-bold text-soft">暂无图片</div>}
                    </div>
                  )}
                  <div className="grid gap-2">
                    <input value={item.title} onChange={(event) => updateItem(section.key, index, { title: event.target.value })} placeholder={section.withRole ? '姓名' : '标题'} className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                    {section.withRole && <input value={item.role || ''} onChange={(event) => updateItem(section.key, index, { role: event.target.value, metadata: { ...(item.metadata || {}), role: event.target.value } })} placeholder="职位" className="h-9 rounded-[4px] border border-line px-3 text-sm" />}
                    {!section.compact && <textarea value={item.description} onChange={(event) => updateItem(section.key, index, { description: event.target.value })} placeholder="描述" rows={2} className="rounded-[4px] border border-line p-3 text-sm" />}
                  </div>
                  <input value={item.sortOrder} onChange={(event) => updateItem(section.key, index, { sortOrder: Number(event.target.value || 0) })} type="number" className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                  <select value={item.status} onChange={(event) => updateItem(section.key, index, { status: event.target.value as BackendSiteAboutItem['status'] })} className="h-9 rounded-[4px] border border-line px-2 text-sm">
                    <option value="published">显示</option>
                    <option value="hidden">隐藏</option>
                  </select>
                  {section.withImage && (
                    <label className="inline-flex h-8 cursor-pointer items-center justify-center gap-1.5 rounded-[4px] border border-line px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">
                      <Upload className="h-3.5 w-3.5" />
                      上传图片
                      <input type="file" accept="image/jpeg,image/png,image/webp" className="sr-only" onChange={(event) => {
                        const file = event.target.files?.[0]
                        if (file) void uploadImage(file, (url) => updateItem(section.key, index, { imageUrl: url }))
                        event.target.value = ''
                      }} />
                    </label>
                  )}
                  <button type="button" onClick={() => removeItem(section.key, index)} className="text-xs font-extrabold text-red-600">删除</button>
                </div>
              ))}
            </div>
          </section>
        ))}
      </div>
    </AdminShell>
  )
}

function ImageUploadRow({
  label,
  value,
  onUpload,
}: {
  label: string
  value: string
  uploading: string
  onUpload: (file: File) => void
}) {
  return (
    <div className="grid gap-3 rounded-[4px] border border-line p-3 md:grid-cols-[120px_1fr_auto] md:items-center">
      <div className="h-20 rounded-[4px] border border-line bg-cover bg-center" style={{ backgroundImage: value ? `url(${value})` : undefined }}>
        {!value && <div className="grid h-full place-items-center text-[11px] font-bold text-soft">暂无图片</div>}
      </div>
      <div>
        <div className="text-sm font-extrabold text-ink">{label}</div>
        <div className="mt-1 truncate text-xs font-bold text-soft">{value || '未上传'}</div>
      </div>
      <label className="inline-flex h-8 cursor-pointer items-center justify-center gap-1.5 rounded-[4px] border border-line px-3 text-xs font-extrabold text-ink hover:border-brand hover:text-brand">
        <Upload className="h-3.5 w-3.5" />
        {value ? '重新上传' : '上传'}
        <input type="file" accept="image/jpeg,image/png,image/webp" className="sr-only" onChange={(event) => {
          const file = event.target.files?.[0]
          if (file) onUpload(file)
          event.target.value = ''
        }} />
      </label>
    </div>
  )
}
