'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'
import type { FormEvent } from 'react'
import { useRouter } from 'next/navigation'
import { ArrowLeft } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, cents, type BackendExpert, type BackendExpertDirection, yuan } from '@/lib/backend'

type ExpertFormState = {
  passportNo: string
  phone: string
  createUser: boolean
  slug: string
  name: string
  title: string
  organization: string
  contactPhone: string
  photoUrl: string
  price: string
  shareRatio: string
  homepageIntro: string
  bio: string
  projectExperience: string
  representativeAchievements: string
  status: BackendExpert['status']
  availabilityStatus: BackendExpert['availabilityStatus']
  acceptingOrders: boolean
  rating: string
  consultationCount: string
}

const emptyForm: ExpertFormState = {
  passportNo: '',
  phone: '',
  createUser: false,
  slug: '',
  name: '',
  title: '',
  organization: '',
  contactPhone: '',
  photoUrl: '',
  price: '1200',
  shareRatio: '80',
  homepageIntro: '',
  bio: '',
  projectExperience: '',
  representativeAchievements: '',
  status: 'published',
  availabilityStatus: 'this-week',
  acceptingOrders: true,
  rating: '5',
  consultationCount: '0',
}

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

function formFromExpert(expert: BackendExpert): ExpertFormState {
  return {
    passportNo: expert.passportNo || expert.user?.passportNo || '',
    phone: expert.user?.phone || expert.contactPhone || '',
    createUser: false,
    slug: expert.slug || '',
    name: expert.name || '',
    title: expert.title || '',
    organization: expert.organization || '',
    contactPhone: expert.contactPhone || expert.user?.phone || '',
    photoUrl: expert.photoUrl || '',
    price: String(yuan(expert.priceAmount || 0)),
    shareRatio: String(expert.shareRatio ?? 80),
    homepageIntro: expert.homepageIntro || '',
    bio: expert.bio || '',
    projectExperience: expert.projectExperience || '',
    representativeAchievements: expert.representativeAchievements || '',
    status: expert.status || 'draft',
    availabilityStatus: expert.availabilityStatus || 'next-week',
    acceptingOrders: expert.acceptingOrders !== false,
    rating: String(expert.rating ?? 5),
    consultationCount: String(expert.consultationCount ?? 0),
  }
}

function safeNumber(value: string, fallback = 0) {
  const numberValue = Number(value)
  return Number.isFinite(numberValue) ? numberValue : fallback
}

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

export function ExpertForm({ expertId }: { expertId?: string }) {
  const router = useRouter()
  const [form, setForm] = useState<ExpertFormState>(emptyForm)
  const [directions, setDirections] = useState<BackendExpertDirection[]>([])
  const [selectedDirections, setSelectedDirections] = useState<string[]>([])
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(Boolean(expertId))
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    let cancelled = false
    async function load() {
      try {
        setLoading(Boolean(expertId))
        const [directionResult, expert] = await Promise.all([
          backend.adminExpertDirections(),
          expertId ? backend.adminExpert(expertId) : Promise.resolve(null),
        ])
        if (cancelled) return
        setDirections(directionResult.items)
        if (expert) {
          setForm(formFromExpert(expert))
          setSelectedDirections(expert.directions || expert.specialties || [])
        }
        setError('')
      } catch (err) {
        if (!cancelled) setError(err instanceof Error ? err.message : '专家信息加载失败')
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    void load()
    return () => { cancelled = true }
  }, [expertId])

  function toggleDirection(name: string) {
    setSelectedDirections((current) => {
      if (current.includes(name)) return current.filter((item) => item !== name)
      if (current.length >= 3) return current
      return [...current, name]
    })
  }

  async function saveExpert(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (selectedDirections.length === 0) {
      setError('请至少选择一个专家方向')
      return
    }

    setSaving(true)
    setError('')
    try {
      const payload = {
        passportNo: form.passportNo.trim(),
        phone: form.phone.trim(),
        createUser: form.createUser,
        slug: form.slug.trim() || slugify(form.name),
        name: form.name.trim(),
        title: form.title.trim(),
        organization: form.organization.trim(),
        contactPhone: form.contactPhone.trim() || form.phone.trim(),
        photoUrl: form.photoUrl.trim(),
        directions: selectedDirections,
        specialties: selectedDirections,
        priceAmount: cents(safeNumber(form.price)),
        shareRatio: Math.round(safeNumber(form.shareRatio, 80)),
        homepageIntro: form.homepageIntro.trim(),
        bio: form.bio.trim() || form.homepageIntro.trim(),
        projectExperience: form.projectExperience.trim(),
        representativeAchievements: form.representativeAchievements.trim(),
        status: form.status,
        availabilityStatus: form.availabilityStatus,
        acceptingOrders: form.acceptingOrders,
        rating: safeNumber(form.rating, 5),
        consultationCount: Math.max(0, Math.round(safeNumber(form.consultationCount, 0))),
      }
      if (expertId) {
        await backend.updateAdminExpert(expertId, payload)
      } else {
        await backend.createAdminExpert(payload)
      }
      router.push('/admin/experts')
    } catch (err) {
      setError(err instanceof Error ? err.message : '专家保存失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <AdminShell title={expertId ? '编辑专家' : '新增专家'} 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>
        <Link href="/admin/experts/directions" className="text-xs font-extrabold text-brand">方向管理</Link>
      </div>

      <form className="border border-line bg-white" onSubmit={saveExpert}>
        <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.name || (expertId ? '编辑专家' : '新增专家')}</div>
            <div className="mt-1 text-xs font-bold text-muted">{form.passportNo || '未绑定通行证'}</div>
          </div>
          <button disabled={saving || loading} 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>

        {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>}
        {loading && <div className="px-5 py-8 text-sm font-bold text-muted">正在加载专家信息...</div>}

        {!loading && (
          <div className="space-y-6 px-5 py-5">
            <section>
              <div className="mb-3 text-sm font-extrabold text-ink">账号与基础信息</div>
              <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">通行证编号</span>
                  <input value={form.passportNo} onChange={(event) => setForm((current) => ({ ...current, passportNo: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" placeholder="如 KQHVP-58209" />
                </label>
                {!expertId && (
                  <label className="flex items-end gap-2 pb-2 text-sm font-bold text-muted">
                    <input type="checkbox" checked={form.createUser} onChange={(event) => setForm((current) => ({ ...current, createUser: event.target.checked }))} className="accent-brand" />
                    通行证不存在时创建会员账号
                  </label>
                )}
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">会员手机号</span>
                  <input value={form.phone} onChange={(event) => setForm((current) => ({ ...current, phone: 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={form.name} onChange={(event) => setForm((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">Slug</span>
                  <input value={form.slug} onChange={(event) => setForm((current) => ({ ...current, slug: event.target.value }))} 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>
                  <input required value={form.contactPhone} onChange={(event) => setForm((current) => ({ ...current, contactPhone: 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={form.organization} onChange={(event) => setForm((current) => ({ ...current, organization: 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={form.title} onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                </label>
                <label className="block md:col-span-2 xl:col-span-3">
                  <span className="mb-2 block text-sm font-bold text-ink">头像 URL</span>
                  <input value={form.photoUrl} onChange={(event) => setForm((current) => ({ ...current, photoUrl: event.target.value }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                </label>
              </div>
            </section>

            <section>
              <div className="mb-3 flex items-center justify-between">
                <div className="text-sm font-extrabold text-ink">专家方向（最多 3 个）</div>
                <Link href="/admin/experts/directions" className="text-xs font-extrabold text-brand">编辑方向字典</Link>
              </div>
              <div className="grid gap-2 md:grid-cols-2 xl:grid-cols-3">
                {directions.map((item) => {
                  const checked = selectedDirections.includes(item.name)
                  const disabled = (!checked && selectedDirections.length >= 3) || (item.status === 'disabled' && !checked)
                  return (
                    <label key={item.id} className={`flex min-h-10 items-center gap-2 rounded-[4px] border px-3 py-2 text-sm font-bold ${checked ? 'border-brand bg-brand-light text-brand' : disabled ? 'border-line bg-bg text-soft' : 'border-line text-muted hover:border-brand'}`}>
                      <input type="checkbox" checked={checked} disabled={disabled} onChange={() => toggleDirection(item.name)} className="accent-brand" />
                      <span>{item.directionType || item.groupName} · {item.name}</span>
                    </label>
                  )
                })}
              </div>
            </section>

            <section>
              <div className="mb-3 text-sm font-extrabold text-ink">定价与发布</div>
              <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">价格（元/小时）</span>
                  <input value={form.price} onChange={(event) => setForm((current) => ({ ...current, price: event.target.value }))} type="number" min="0" step="0.01" 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={form.shareRatio} onChange={(event) => setForm((current) => ({ ...current, shareRatio: event.target.value }))} type="number" min="0" max="100" 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 BackendExpert['status'] }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                    <option value="published">已发布</option>
                    <option value="draft">草稿</option>
                    <option value="offline">已下线</option>
                  </select>
                </label>
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">可约状态</span>
                  <select value={form.availabilityStatus} onChange={(event) => setForm((current) => ({ ...current, availabilityStatus: event.target.value as BackendExpert['availabilityStatus'] }))} className="h-10 w-full rounded-[4px] border border-line px-3 text-sm">
                    <option value="this-week">本周可约</option>
                    <option value="next-week">下周可约</option>
                    <option value="unavailable">暂不可约</option>
                  </select>
                </label>
                <label className="flex items-center gap-2 text-sm font-bold text-muted">
                  <input type="checkbox" checked={form.acceptingOrders} onChange={(event) => setForm((current) => ({ ...current, acceptingOrders: event.target.checked }))} className="accent-brand" />
                  接受新订单
                </label>
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">评分</span>
                  <input value={form.rating} onChange={(event) => setForm((current) => ({ ...current, rating: event.target.value }))} type="number" min="0" max="5" step="0.1" 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={form.consultationCount} onChange={(event) => setForm((current) => ({ ...current, consultationCount: event.target.value }))} type="number" min="0" className="h-10 w-full rounded-[4px] border border-line px-3 text-sm" />
                </label>
              </div>
            </section>

            <section>
              <div className="mb-3 text-sm font-extrabold text-ink">主页内容</div>
              <div className="grid gap-4 lg:grid-cols-2">
                <label className="block">
                  <span className="mb-2 block text-sm font-bold text-ink">主页简介</span>
                  <textarea value={form.homepageIntro} onChange={(event) => setForm((current) => ({ ...current, homepageIntro: event.target.value }))} rows={4} 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.bio} onChange={(event) => setForm((current) => ({ ...current, bio: event.target.value }))} rows={4} 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.projectExperience} onChange={(event) => setForm((current) => ({ ...current, projectExperience: event.target.value }))} rows={5} 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.representativeAchievements} onChange={(event) => setForm((current) => ({ ...current, representativeAchievements: event.target.value }))} rows={5} className="w-full rounded-[4px] border border-line p-3 text-sm" />
                </label>
              </div>
            </section>
          </div>
        )}
      </form>
    </AdminShell>
  )
}
