'use client'

import { useEffect, useState } from 'react'
import { Plus, Upload } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import {
  apiBase,
	  backend,
	  type BackendConsultingOptionSet,
	  type BackendOrgUnit,
	  type BackendSiteConsulting,
	  type BackendSiteConsultingCase,
	  type BackendSiteConsultingDirection,
	  type BackendSiteConsultingStep,
	  type BackendStaffAccount,
	} from '@/lib/backend'

type ListKey = 'directions' | 'cases' | 'steps'

const emptyConsulting: BackendSiteConsulting = {
  content: {
    heroTitle: '',
    heroDescription: '',
    heroExplanation: '',
    heroImageUrl: '',
    directionTitle: '',
    directionDescription: '',
    casesTitle: '',
    casesDescription: '',
    stepsTitle: '',
    stepsDescription: '',
  },
  directions: [],
  cases: [],
  steps: [],
  optionSets: [],
}

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)
}

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

export default function AdminSiteConsultingPage() {
  const [site, setSite] = useState<BackendSiteConsulting>(emptyConsulting)
  const [staff, setStaff] = useState<BackendStaffAccount[]>([])
  const [orgUnits, setOrgUnits] = useState<BackendOrgUnit[]>([])
  const [error, setError] = useState('')
  const [saving, setSaving] = useState(false)
  const [uploading, setUploading] = useState('')

  useEffect(() => {
    void Promise.all([
      backend.adminSiteConsulting(),
      backend.adminStaffAccounts({ status: 'active' }).catch(() => ({ items: [] as BackendStaffAccount[] })),
      backend.adminOrgTree().catch(() => ({ units: [] as BackendOrgUnit[], positions: [], assignments: [] })),
    ]).then(([result, staffResult, orgTree]) => {
      setSite({
        ...result,
        directions: sortItems(result.directions),
        cases: sortItems(result.cases),
        steps: sortItems(result.steps),
        optionSets: sortItems(result.optionSets || []),
      })
      setStaff(staffResult.items)
      setOrgUnits(sortItems(orgTree.units.filter((unit) => unit.status !== 'disabled')))
    }).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)
    setError('')
    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<BackendSiteConsulting['content']>) {
    setSite((current) => ({ ...current, content: { ...current.content, ...patch } }))
  }

  function updateDirection(index: number, patch: Partial<BackendSiteConsultingDirection>) {
    setSite((current) => ({
      ...current,
      directions: current.directions.map((item, itemIndex) => itemIndex === index ? { ...item, ...patch } : item),
    }))
  }

  function updateCase(index: number, patch: Partial<BackendSiteConsultingCase>) {
    setSite((current) => ({
      ...current,
      cases: current.cases.map((item, itemIndex) => itemIndex === index ? { ...item, ...patch } : item),
    }))
  }

  function updateStep(index: number, patch: Partial<BackendSiteConsultingStep>) {
    setSite((current) => ({
      ...current,
      steps: current.steps.map((item, itemIndex) => itemIndex === index ? { ...item, ...patch } : item),
    }))
  }

  function updateOptionSet(index: number, patch: Partial<BackendConsultingOptionSet>) {
    setSite((current) => ({
      ...current,
      optionSets: (current.optionSets || []).map((item, itemIndex) => itemIndex === index ? { ...item, ...patch } : item),
    }))
  }

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

  function addDirection() {
    setSite((current) => ({
      ...current,
      directions: [...current.directions, {
        id: `consulting-direction-${Date.now()}`,
        slug: `direction-${Date.now()}`,
        title: '',
        summary: '',
        description: '',
        note: '',
        imageUrl: '',
        scenarios: [],
        ownerDepartment: '',
        ownerOrgUnitId: null,
        defaultAssigneeId: null,
        sortOrder: (current.directions.length + 1) * 10,
        status: 'published',
      }],
    }))
  }

  function addCase() {
    setSite((current) => ({
      ...current,
      cases: [...current.cases, {
        id: `consulting-case-${Date.now()}`,
        type: '',
        title: '',
        summary: '',
        imageUrl: '',
        sortOrder: (current.cases.length + 1) * 10,
        status: 'published',
      }],
    }))
  }

  function addStep() {
    setSite((current) => ({
      ...current,
      steps: [...current.steps, {
        id: `consulting-step-${Date.now()}`,
        title: '',
        description: '',
        sortOrder: (current.steps.length + 1) * 10,
        status: 'published',
      }],
    }))
  }

  async function save() {
    setSaving(true)
    setError('')
    try {
      const saved = await backend.saveAdminSiteConsulting({
        ...site,
        directions: sortItems(site.directions).map((item) => ({ ...item, slug: item.slug || slugify(item.title) })),
        cases: sortItems(site.cases),
        steps: sortItems(site.steps),
        optionSets: sortItems(site.optionSets || []),
      })
      setSite({ ...saved, directions: sortItems(saved.directions), cases: sortItems(saved.cases), steps: sortItems(saved.steps), optionSets: sortItems(saved.optionSets || []) })
    } 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">
            <TextField label="顶部标题" value={site.content.heroTitle} onChange={(value) => updateContent({ heroTitle: value })} />
            <ImageUploadBox label="顶部配图" value={site.content.heroImageUrl} onUpload={(file) => uploadImage(file, (url) => updateContent({ heroImageUrl: url }))} />
            <TextAreaField label="顶部第一段介绍" value={site.content.heroDescription} onChange={(value) => updateContent({ heroDescription: value })} />
            <TextAreaField label="顶部第二段介绍" value={site.content.heroExplanation} onChange={(value) => updateContent({ heroExplanation: value })} />
            <TextField label="服务方向标题" value={site.content.directionTitle} onChange={(value) => updateContent({ directionTitle: value })} />
            <TextField label="过往案例标题" value={site.content.casesTitle} onChange={(value) => updateContent({ casesTitle: value })} />
            <TextAreaField label="服务方向说明" value={site.content.directionDescription} onChange={(value) => updateContent({ directionDescription: value })} />
            <TextAreaField label="过往案例说明" value={site.content.casesDescription} onChange={(value) => updateContent({ casesDescription: value })} />
            <TextField label="交付流程标题" value={site.content.stepsTitle} onChange={(value) => updateContent({ stepsTitle: value })} />
            <TextAreaField label="交付流程说明" value={site.content.stepsDescription} onChange={(value) => updateContent({ stepsDescription: value })} />
          </div>
        </section>

        <section 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">服务方向</div>
              <div className="mt-1 text-xs font-bold text-soft">方向会同步到 Web 下拉菜单、咨询详情和小程序入口。</div>
            </div>
            <button type="button" onClick={addDirection} 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">
            {site.directions.map((item, index) => (
              <div key={item.id} className="grid gap-3 px-4 py-4 lg:grid-cols-[100px_1fr_120px_100px_130px] lg:items-start">
                <PreviewImage value={item.imageUrl} />
                <div className="grid gap-2">
                  <div className="grid gap-2 md:grid-cols-2">
                    <input value={item.title} onChange={(event) => updateDirection(index, { title: event.target.value })} placeholder="方向标题" className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                    <input value={item.slug} onChange={(event) => updateDirection(index, { slug: event.target.value })} placeholder="slug" className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                  </div>
	                  <div className="grid gap-2 md:grid-cols-3">
	                    <input value={item.ownerDepartment || ''} onChange={(event) => updateDirection(index, { ownerDepartment: event.target.value })} placeholder="归属部门名称" className="h-9 rounded-[4px] border border-line px-3 text-sm" />
	                    <select
	                      value={item.ownerOrgUnitId || ''}
	                      onChange={(event) => {
	                        const orgUnit = orgUnits.find((unit) => unit.id === event.target.value)
	                        updateDirection(index, { ownerOrgUnitId: event.target.value || null, ownerDepartment: orgUnit?.name || item.ownerDepartment || '' })
	                      }}
	                      className="h-9 rounded-[4px] border border-line px-3 text-sm"
	                    >
	                      <option value="">选择归属组织</option>
	                      {orgUnits.map((unit) => <option key={unit.id} value={unit.id}>{`${'· '.repeat(Math.max(0, unit.depth))}${unit.name}`}</option>)}
	                    </select>
	                    <select value={item.defaultAssigneeId || ''} onChange={(event) => updateDirection(index, { defaultAssigneeId: event.target.value || null })} className="h-9 rounded-[4px] border border-line px-3 text-sm">
	                      <option value="">选择默认负责人</option>
	                      {staff.map((account) => <option key={account.id} value={account.id}>{account.displayName || account.phone || account.email}</option>)}
	                    </select>
	                  </div>
                  <textarea value={item.summary} onChange={(event) => updateDirection(index, { summary: event.target.value })} placeholder="列表摘要" rows={2} className="rounded-[4px] border border-line p-3 text-sm" />
                  <textarea value={item.note} onChange={(event) => updateDirection(index, { note: event.target.value })} placeholder="列表补充说明" rows={2} className="rounded-[4px] border border-line p-3 text-sm" />
                  <textarea value={item.description} onChange={(event) => updateDirection(index, { description: event.target.value })} placeholder="详情说明" rows={3} className="rounded-[4px] border border-line p-3 text-sm" />
                  <textarea value={item.scenarios.join('\n')} onChange={(event) => updateDirection(index, { scenarios: event.target.value.split('\n').map((value) => value.trim()).filter(Boolean) })} placeholder="适用场景，每行一个" rows={3} className="rounded-[4px] border border-line p-3 text-sm" />
                </div>
                <input value={item.sortOrder} onChange={(event) => updateDirection(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) => updateDirection(index, { status: event.target.value as BackendSiteConsultingDirection['status'] })} className="h-9 rounded-[4px] border border-line px-2 text-sm">
                  <option value="published">显示</option>
                  <option value="hidden">隐藏</option>
                </select>
                <RowActions onUpload={(file) => uploadImage(file, (url) => updateDirection(index, { imageUrl: url }))} onDelete={() => removeItem('directions', index)} />
              </div>
            ))}
          </div>
        </section>

        <section className="border border-line bg-white">
          <div className="flex items-center justify-between border-b border-line px-4 py-3">
            <div className="text-sm font-extrabold text-ink">过往案例</div>
            <button type="button" onClick={addCase} 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">
            {site.cases.map((item, index) => (
              <div key={item.id} className="grid gap-3 px-4 py-4 lg:grid-cols-[100px_1fr_120px_100px_130px] lg:items-start">
                <PreviewImage value={item.imageUrl} />
                <div className="grid gap-2">
                  <div className="grid gap-2 md:grid-cols-2">
                    <input value={item.type} onChange={(event) => updateCase(index, { type: event.target.value })} placeholder="案例类型" className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                    <input value={item.title} onChange={(event) => updateCase(index, { title: event.target.value })} placeholder="案例标题" className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                  </div>
                  <textarea value={item.summary} onChange={(event) => updateCase(index, { summary: event.target.value })} placeholder="案例摘要" rows={3} className="rounded-[4px] border border-line p-3 text-sm" />
                </div>
                <input value={item.sortOrder} onChange={(event) => updateCase(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) => updateCase(index, { status: event.target.value as BackendSiteConsultingCase['status'] })} className="h-9 rounded-[4px] border border-line px-2 text-sm">
                  <option value="published">显示</option>
                  <option value="hidden">隐藏</option>
                </select>
                <RowActions onUpload={(file) => uploadImage(file, (url) => updateCase(index, { imageUrl: url }))} onDelete={() => removeItem('cases', index)} />
              </div>
            ))}
          </div>
        </section>

        <section className="border border-line bg-white">
          <div className="flex items-center justify-between border-b border-line px-4 py-3">
            <div className="text-sm font-extrabold text-ink">交付流程</div>
            <button type="button" onClick={addStep} 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">
            {site.steps.map((item, index) => (
              <div key={item.id} className="grid gap-3 px-4 py-3 lg:grid-cols-[1fr_120px_100px_70px] lg:items-start">
                <div className="grid gap-2">
                  <input value={item.title} onChange={(event) => updateStep(index, { title: event.target.value })} placeholder="步骤标题" className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                  <textarea value={item.description} onChange={(event) => updateStep(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) => updateStep(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) => updateStep(index, { status: event.target.value as BackendSiteConsultingStep['status'] })} className="h-9 rounded-[4px] border border-line px-2 text-sm">
                  <option value="published">显示</option>
                  <option value="hidden">隐藏</option>
                </select>
                <button type="button" onClick={() => removeItem('steps', index)} className="text-xs font-extrabold text-red-600">删除</button>
              </div>
            ))}
          </div>
        </section>

        <section className="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="divide-y divide-line">
            {(site.optionSets || []).map((set, index) => (
              <div key={set.code} className="grid gap-3 px-4 py-4 lg:grid-cols-[180px_1fr_90px_100px] lg:items-start">
                <div>
                  <div className="text-sm font-extrabold text-ink">{set.name}</div>
                  <div className="mt-1 text-xs font-bold text-soft">{set.code}</div>
                </div>
                <textarea
                  value={(set.options || []).map((option) => option.label).join('\n')}
                  onChange={(event) => updateOptionSet(index, {
                    options: event.target.value.split('\n').map((label, optionIndex) => ({
                      code: (set.options?.[optionIndex]?.code || label.trim() || `option-${optionIndex + 1}`).toLowerCase().replace(/[^a-z0-9_-]+/g, '_'),
                      label: label.trim(),
                      description: set.options?.[optionIndex]?.description || '',
                      sortOrder: (optionIndex + 1) * 10,
                      status: 'active' as const,
                      metadata: set.options?.[optionIndex]?.metadata || {},
                    })).filter((option) => option.label),
                  })}
                  rows={Math.max(3, (set.options || []).length)}
                  className="w-full rounded-[4px] border border-line p-3 text-sm"
                  placeholder="每行一个选项"
                />
                <input value={set.sortOrder} onChange={(event) => updateOptionSet(index, { sortOrder: Number(event.target.value || 0) })} type="number" className="h-9 rounded-[4px] border border-line px-3 text-sm" />
                <select value={set.status} onChange={(event) => updateOptionSet(index, { status: event.target.value as BackendConsultingOptionSet['status'] })} className="h-9 rounded-[4px] border border-line px-2 text-sm">
                  <option value="active">启用</option>
                  <option value="disabled">禁用</option>
                </select>
              </div>
            ))}
          </div>
        </section>

        {uploading && <div className="text-xs font-bold text-brand">正在上传：{uploading}</div>}
      </div>
    </AdminShell>
  )
}

function TextField({ label, value, onChange }: { label: string; value: string; onChange: (value: string) => void }) {
  return (
    <label className="block">
      <span className="mb-1 block text-xs font-extrabold text-soft">{label}</span>
      <input value={value} onChange={(event) => onChange(event.target.value)} className="h-9 w-full rounded-[4px] border border-line px-3 text-sm" />
    </label>
  )
}

function TextAreaField({ label, value, onChange }: { label: string; value: string; onChange: (value: string) => void }) {
  return (
    <label className="block">
      <span className="mb-1 block text-xs font-extrabold text-soft">{label}</span>
      <textarea value={value} onChange={(event) => onChange(event.target.value)} rows={3} className="w-full rounded-[4px] border border-line p-3 text-sm" />
    </label>
  )
}

function PreviewImage({ value }: { value?: string }) {
  return (
    <div className="h-16 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>
  )
}

function RowActions({ onUpload, onDelete }: { onUpload: (file: File) => void; onDelete: () => void }) {
  return (
    <div className="flex flex-wrap items-center gap-2">
      <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) onUpload(file)
          event.target.value = ''
        }} />
      </label>
      <button type="button" onClick={onDelete} className="text-xs font-extrabold text-red-600">删除</button>
    </div>
  )
}

function ImageUploadBox({ label, value, onUpload }: { label: string; value: string; onUpload: (file: File) => void }) {
  return (
    <div className="block">
      <span className="mb-1 block text-xs font-extrabold text-soft">{label}</span>
      <div className="grid gap-2 md:grid-cols-[120px_1fr] md:items-center">
        <PreviewImage value={value} />
        <label className="inline-flex h-9 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>
    </div>
  )
}
