'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import type { FormEvent } from 'react'
import { ArrowLeft, Pencil, Plus } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendExpertDirection } from '@/lib/backend'

type DirectionDraft = {
  directionType: string
  name: string
  description: string
  sortOrder: string
  status: BackendExpertDirection['status']
}

const emptyDraft: DirectionDraft = {
  directionType: '',
  name: '',
  description: '',
  sortOrder: '10',
  status: 'active',
}

function draftFromDirection(item: BackendExpertDirection): DirectionDraft {
  return {
    directionType: item.directionType || item.groupName || '',
    name: item.name || '',
    description: item.description || '',
    sortOrder: String(item.sortOrder ?? 0),
    status: item.status || 'active',
  }
}

function safeSort(value: string) {
  const numberValue = Number(value)
  return Number.isInteger(numberValue) ? numberValue : 0
}

export default function AdminExpertDirectionsPage() {
  const [items, setItems] = useState<BackendExpertDirection[]>([])
  const [draft, setDraft] = useState<DirectionDraft>(emptyDraft)
  const [editingId, setEditingId] = useState('')
  const [error, setError] = useState('')
  const [saved, setSaved] = useState('')
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)

  async function reload() {
    setLoading(true)
    try {
      const result = await backend.adminExpertDirections()
      setItems(result.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '专家方向加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    const timer = window.setTimeout(() => {
      void reload()
    }, 0)
    return () => window.clearTimeout(timer)
  }, [])

  function startCreate() {
    setEditingId('')
    setDraft(emptyDraft)
    setSaved('')
    setError('')
  }

  function startEdit(item: BackendExpertDirection) {
    setEditingId(item.id)
    setDraft(draftFromDirection(item))
    setSaved('')
    setError('')
  }

  async function saveDirection(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setSaving(true)
    setError('')
    try {
      const payload = {
        groupName: draft.directionType.trim(),
        directionType: draft.directionType.trim(),
        name: draft.name.trim(),
        description: draft.description.trim(),
        sortOrder: safeSort(draft.sortOrder),
        status: draft.status,
      }
      if (editingId) {
        await backend.updateAdminExpertDirection(editingId, payload)
        setSaved('专家方向已更新')
      } else {
        await backend.createAdminExpertDirection(payload)
        setSaved('专家方向已新增')
      }
      setEditingId('')
      setDraft(emptyDraft)
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '专家方向保存失败')
    } finally {
      setSaving(false)
    }
  }

  async function toggleDirection(item: BackendExpertDirection) {
    try {
      await backend.updateAdminExpertDirection(item.id, {
        groupName: item.groupName,
        directionType: item.directionType || item.groupName,
        name: item.name,
        description: item.description || '',
        sortOrder: item.sortOrder,
        status: item.status === 'disabled' ? 'active' : 'disabled',
      })
      setSaved(item.status === 'disabled' ? '专家方向已启用' : '专家方向已停用')
      await reload()
    } catch (err) {
      setError(err instanceof Error ? err.message : '专家方向状态更新失败')
    }
  }

  return (
    <AdminShell title="专家方向管理" description="维护专家方向字典的名称、类型、描述、排序和启停状态。">
      <div className="mb-3 flex items-center justify-between">
        <Link href="/admin/experts" className="inline-flex h-9 items-center gap-1.5 rounded-[4px] border border-line bg-white px-3 text-xs font-extrabold text-muted hover:border-brand hover:text-brand">
          <ArrowLeft className="h-3.5 w-3.5" />
          返回专家列表
        </Link>
        <button type="button" onClick={startCreate} className="inline-flex h-9 items-center gap-1.5 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white hover:bg-brand">
          <Plus className="h-3.5 w-3.5" />
          新增方向
        </button>
      </div>

      {(saved || error) && (
        <div className={`mb-3 rounded-[4px] px-4 py-3 text-sm font-bold ${error ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>
          {error || saved}
        </div>
      )}

      <form className="mb-4 border border-line bg-white" onSubmit={saveDirection}>
        <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">{editingId ? '编辑方向' : '新增方向'}</div>
            <div className="mt-1 text-xs font-bold text-muted">{draft.name || '方向名称'}</div>
          </div>
          <button disabled={saving} className="h-9 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white hover:bg-brand-dark disabled:opacity-60">
            {saving ? '保存中...' : '保存方向'}
          </button>
        </div>
        <div className="grid gap-4 px-5 py-5 md:grid-cols-2 xl:grid-cols-[180px_220px_minmax(260px,1fr)_110px_130px]">
          <label className="block">
            <span className="mb-2 block text-sm font-bold text-ink">类型/分组</span>
            <input required value={draft.directionType} onChange={(event) => setDraft((current) => ({ ...current, directionType: 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>
            <input required value={draft.name} onChange={(event) => setDraft((current) => ({ ...current, name: 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>
            <input value={draft.description} onChange={(event) => setDraft((current) => ({ ...current, description: 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>
            <input value={draft.sortOrder} onChange={(event) => setDraft((current) => ({ ...current, sortOrder: event.target.value }))} type="number" 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={draft.status} onChange={(event) => setDraft((current) => ({ ...current, status: event.target.value as BackendExpertDirection['status'] }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
              <option value="active">启用</option>
              <option value="disabled">停用</option>
            </select>
          </label>
        </div>
      </form>

      <section className="border border-line bg-white">
        <div className="grid grid-cols-[150px_190px_minmax(260px,1fr)_80px_90px_140px] border-b border-line px-4 py-3 text-xs font-extrabold text-soft">
          <span>类型/分组</span><span>方向名称</span><span>描述</span><span>排序</span><span>状态</span><span>操作</span>
        </div>
        {loading && <div className="px-5 py-8 text-sm font-bold text-muted">正在加载专家方向...</div>}
        {!loading && items.map((item) => (
          <div key={item.id} className="grid grid-cols-[150px_190px_minmax(260px,1fr)_80px_90px_140px] items-center border-b border-line px-4 py-3 text-sm hover:bg-bg">
            <span className="font-bold text-muted">{item.directionType || item.groupName}</span>
            <span className="font-extrabold text-ink">{item.name}</span>
            <span className="truncate font-bold text-muted">{item.description || '-'}</span>
            <span className="font-bold text-muted">{item.sortOrder}</span>
            <span className={`font-bold ${item.status === 'disabled' ? 'text-red-600' : 'text-green'}`}>{item.status === 'disabled' ? '停用' : '启用'}</span>
            <span className="flex gap-2">
              <button type="button" onClick={() => startEdit(item)} className="inline-flex items-center gap-1 text-xs font-extrabold text-brand">
                <Pencil className="h-3.5 w-3.5" />
                编辑
              </button>
              <button type="button" onClick={() => void toggleDirection(item)} className="text-xs font-extrabold text-ink">
                {item.status === 'disabled' ? '启用' : '停用'}
              </button>
            </span>
          </div>
        ))}
      </section>
    </AdminShell>
  )
}
