'use client'

import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import type { FormEvent } from 'react'
import { Check, ChevronRight, Loader2, Search } from 'lucide-react'
import { useApp } from '@/components/providers/AppProvider'
import { backend, type BackendExpertApplication, type BackendExpertDirection, type BackendSiteAgreement } from '@/lib/backend'

const inputClass = 'h-10 w-full rounded-[4px] border border-line bg-white px-3 text-sm font-bold text-ink outline-none placeholder:font-medium placeholder:text-muted/70 focus:border-brand'
const areaClass = 'min-h-28 w-full resize-none rounded-[4px] border border-line bg-white px-3 py-3 text-sm font-bold leading-6 text-ink outline-none placeholder:font-medium placeholder:text-muted/70 focus:border-brand'

function statusTitle(status?: BackendExpertApplication['status']) {
  if (status === 'pending') return '专家申请审核中'
  if (status === 'approved') return '专家申请已通过'
  if (status === 'rejected') return '专家申请未通过'
  return ''
}

export default function ExpertJoinPage() {
  const { hydrated, user, token } = useApp()
  const [directions, setDirections] = useState<BackendExpertDirection[]>([])
  const [agreement, setAgreement] = useState<BackendSiteAgreement | null>(null)
  const [application, setApplication] = useState<BackendExpertApplication | null>(null)
  const [showForm, setShowForm] = useState(false)
  const [acceptedRules, setAcceptedRules] = useState(false)
  const [showRules, setShowRules] = useState(false)
  const [directionSearch, setDirectionSearch] = useState('')
  const [selectedDirections, setSelectedDirections] = useState<string[]>([])
  const [photoFile, setPhotoFile] = useState<File | null>(null)
  const [attachmentFiles, setAttachmentFiles] = useState<File[]>([])
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    void backend.expertDirections().then((result) => setDirections(result.items)).catch(() => setDirections([]))
    void backend.siteAgreement().then(setAgreement).catch(() => setAgreement(null))
  }, [])

  useEffect(() => {
    if (!token) return
    void backend.accountExpertApplication(token).then((item) => {
      setApplication(item)
      if (item?.status === 'rejected') {
        setShowForm(true)
        setSelectedDirections(item.directions || [])
      }
    }).catch(() => setApplication(null))
  }, [token])

  const groupedDirections = useMemo(() => {
    const keyword = directionSearch.trim().toLowerCase()
    const visible = directions.filter((item) => !keyword || item.name.toLowerCase().includes(keyword) || item.groupName.toLowerCase().includes(keyword))
    return visible.reduce<Record<string, BackendExpertDirection[]>>((result, item) => {
      result[item.groupName] = [...(result[item.groupName] || []), item]
      return result
    }, {})
  }, [directionSearch, directions])

  async function uploadFile(file: File) {
    if (!token) throw new Error('请先登录')
    return backend.uploadAccountFile(token, file)
  }

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!user || !token) return
    if (!acceptedRules) {
      setError('请先阅读并同意专家合作规则。')
      return
    }
    if (selectedDirections.length === 0 || selectedDirections.length > 3) {
      setError('专家方向需要选择 1-3 个。')
      return
    }
    if (!photoFile && !application?.photoUrl) {
      setError('请上传专业照片。')
      return
    }

    setSubmitting(true)
    setError('')
    const form = new FormData(event.currentTarget)
    try {
      const photo = photoFile ? await uploadFile(photoFile) : null
      const attachments = []
      for (const file of attachmentFiles) {
        attachments.push(await uploadFile(file))
      }
      const saved = await backend.submitExpertApplication(token, {
        name: String(form.get('name') || ''),
        contactPhone: String(form.get('contactPhone') || ''),
        organization: String(form.get('organization') || ''),
        title: String(form.get('title') || ''),
        directions: selectedDirections,
        photoFileId: photo?.id || application?.photoFileId || null,
        photoUrl: photo?.url || application?.photoUrl || '',
        projectExperience: String(form.get('projectExperience') || ''),
        representativeAchievements: String(form.get('representativeAchievements') || ''),
        homepageIntro: String(form.get('homepageIntro') || ''),
        attachmentFileIds: attachments.map((item) => item.id),
      })
      setApplication(saved)
      setShowForm(false)
    } catch (err) {
      setError(err instanceof Error ? err.message : '专家申请提交失败')
    } finally {
      setSubmitting(false)
    }
  }

  if (!hydrated) {
    return <section className="grid min-h-[calc(100vh-70px)] place-items-center bg-bg text-sm font-extrabold text-muted">正在加载申请入口...</section>
  }

  if (!user) {
    return (
      <section className="grid min-h-[calc(100vh-70px)] place-items-center bg-bg px-6 py-12">
        <div className="w-full max-w-[720px] border border-line bg-white p-8 text-center">
          <h1 className="text-3xl font-extrabold text-ink">登录后申请成为专家</h1>
          <p className="mt-4 text-sm leading-7 text-muted">专家申请会自动绑定你的会员通行证编号，无需管理员再次绑定。</p>
          <Link href={`/login-required?redirect=${encodeURIComponent('/experts/join')}&action=expert`} className="mt-7 inline-flex h-10 items-center rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white">去登录</Link>
        </div>
      </section>
    )
  }

  const status = application?.status
  const readonlyState = application && status !== 'rejected' && !showForm

  return (
    <section className="bg-white">
      <div className="mx-auto max-w-[1280px] px-6 py-8">
        <nav className="mb-8 flex flex-wrap items-center gap-2 text-sm text-muted">
          <Link href="/experts" className="hover:text-brand">专家平台</Link>
          <ChevronRight className="h-4 w-4 text-soft" />
          <span className="font-bold text-ink">加入我们</span>
        </nav>

        {readonlyState ? (
          <section className="grid min-h-[520px] place-items-center bg-bg px-6 py-14">
            <div className="w-full max-w-[760px] bg-white p-9 shadow-[0_18px_60px_rgba(15,23,42,0.1)]">
              <div className="text-sm font-extrabold text-brand">会员通行证 {user.passportNo || '-'}</div>
              <h1 className="mt-3 text-4xl font-extrabold text-ink">{statusTitle(status)}</h1>
              <p className="mt-4 text-sm leading-7 text-muted">
                {status === 'approved' ? '管理员已通过你的专家申请，专家档案会自动绑定当前账号。' : '运营团队会查看你的方向、项目经验、代表成果和附件材料。'}
              </p>
              <div className="mt-8 grid gap-3 border-y border-line py-5 text-sm">
                <div><span className="font-extrabold text-ink">姓名：</span>{application.name}</div>
                <div><span className="font-extrabold text-ink">专家方向：</span>{application.directions.join('、')}</div>
                {status === 'approved' && <div><span className="font-extrabold text-ink">审核价格：</span>¥{Math.round(application.reviewPriceAmount / 100).toLocaleString()}/小时</div>}
              </div>
              <div className="mt-7 flex flex-wrap gap-3">
                <Link href="/account/expert-home" className="inline-flex h-10 items-center rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white">查看专家工作台</Link>
                <Link href="/experts" className="inline-flex h-10 items-center rounded-[4px] border border-line px-5 text-sm font-extrabold text-muted hover:border-brand hover:text-brand">返回专家平台</Link>
              </div>
            </div>
          </section>
        ) : showForm ? (
          <section className="grid gap-8 py-8 lg:grid-cols-[360px_1fr] lg:items-start">
            <div className="lg:sticky lg:top-28">
              <div className="text-sm font-extrabold text-brand">会员通行证 {user.passportNo || '-'}</div>
              <h1 className="mt-3 text-4xl font-extrabold leading-tight text-ink">{status === 'rejected' ? '重新提交专家申请' : '填写专家申请'}</h1>
              <p className="mt-5 text-sm leading-8 text-muted">申请通过后会自动绑定当前登录账号。专家方向最多选择 3 个。</p>
              {status === 'rejected' && (
                <div className="mt-5 border border-red-100 bg-red-50 px-4 py-3 text-sm font-bold leading-6 text-red-700">
                  未通过原因：{application?.rejectReason || '请补充资料后重新提交。'}
                </div>
              )}
            </div>
            <form onSubmit={submit} className="grid gap-6">
              <div className="grid gap-5 sm:grid-cols-2">
                <label className="grid gap-2">
                  <span className="text-sm font-extrabold text-ink">姓名</span>
                  <input name="name" defaultValue={application?.name || user.name || ''} required className={inputClass} />
                </label>
                <label className="grid gap-2">
                  <span className="text-sm font-extrabold text-ink">联系电话</span>
                  <input name="contactPhone" defaultValue={application?.contactPhone || user.contactPhone || user.phone || ''} required className={inputClass} />
                </label>
                <label className="grid gap-2">
                  <span className="text-sm font-extrabold text-ink">所属机构</span>
                  <input name="organization" defaultValue={application?.organization || user.organization || ''} required className={inputClass} />
                </label>
                <label className="grid gap-2">
                  <span className="text-sm font-extrabold text-ink">职务/职称</span>
                  <input name="title" defaultValue={application?.title || user.title || ''} required className={inputClass} />
                </label>
              </div>

              <section className="border-y border-line py-5">
                <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
                  <div>
                    <h2 className="text-lg font-extrabold text-ink">专家方向</h2>
                    <p className="mt-1 text-sm text-muted">从预设方向中最多选择 3 个。</p>
                  </div>
                  <label className="flex h-10 items-center gap-2 border border-line px-3 text-sm text-muted focus-within:border-brand">
                    <Search className="h-4 w-4" />
                    <input value={directionSearch} onChange={(event) => setDirectionSearch(event.target.value)} placeholder="搜索方向" className="h-full border-0 bg-transparent outline-none" />
                  </label>
                </div>
                <div className="mt-4 grid gap-5">
                  {Object.entries(groupedDirections).map(([group, items]) => (
                    <div key={group}>
                      <div className="text-sm font-extrabold text-brand">{group}</div>
                      <div className="mt-2 flex flex-wrap gap-2">
                        {items.map((item) => {
                          const checked = selectedDirections.includes(item.name)
                          const disabled = !checked && selectedDirections.length >= 3
                          return (
                            <button
                              key={item.id}
                              type="button"
                              disabled={disabled}
                              onClick={() => setSelectedDirections((current) => checked ? current.filter((name) => name !== item.name) : [...current, item.name])}
                              className={`inline-flex h-9 items-center gap-1 rounded-[4px] border px-3 text-xs font-extrabold ${
                                checked ? 'border-brand bg-brand text-white' : disabled ? 'border-line bg-bg text-soft' : 'border-line bg-white text-text-body hover:border-brand hover:text-brand'
                              }`}
                            >
                              {checked && <Check className="h-3.5 w-3.5" />}
                              {item.name}
                            </button>
                          )
                        })}
                      </div>
                    </div>
                  ))}
                </div>
              </section>

              <div className="grid gap-5 sm:grid-cols-2">
                <label className="grid gap-2">
                  <span className="text-sm font-extrabold text-ink">专业照片</span>
                  <input type="file" accept="image/*,.heic" onChange={(event) => setPhotoFile(event.target.files?.[0] || null)} className="w-full rounded-[4px] border border-line bg-white px-3 py-2 text-sm font-bold text-muted file:mr-3 file:rounded-[4px] file:border-0 file:bg-brand-light file:px-3 file:py-1.5 file:text-sm file:font-extrabold file:text-brand" />
                </label>
                <label className="grid gap-2">
                  <span className="text-sm font-extrabold text-ink">附件材料</span>
                  <input type="file" multiple accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.zip,image/*,.heic" onChange={(event) => setAttachmentFiles(Array.from(event.target.files || []))} className="w-full rounded-[4px] border border-line bg-white px-3 py-2 text-sm font-bold text-muted file:mr-3 file:rounded-[4px] file:border-0 file:bg-brand-light file:px-3 file:py-1.5 file:text-sm file:font-extrabold file:text-brand" />
                </label>
              </div>
              <label className="grid gap-2">
                <span className="text-sm font-extrabold text-ink">项目经验</span>
                <textarea name="projectExperience" defaultValue={application?.projectExperience || ''} required className={areaClass} />
              </label>
              <label className="grid gap-2">
                <span className="text-sm font-extrabold text-ink">代表成果</span>
                <textarea name="representativeAchievements" defaultValue={application?.representativeAchievements || ''} required className={areaClass} />
              </label>
              <label className="grid gap-2">
                <span className="text-sm font-extrabold text-ink">专家主页展示简介</span>
                <textarea name="homepageIntro" defaultValue={application?.homepageIntro || ''} required className={areaClass} />
              </label>
              <label className="flex items-start gap-2 text-xs font-bold leading-6 text-muted">
                <input type="checkbox" checked={acceptedRules} onChange={(event) => setAcceptedRules(event.target.checked)} required className="mt-1 accent-brand" />
                <span>
                  我同意
                  <button type="button" onClick={() => setShowRules(true)} className="mx-1 font-extrabold text-brand hover:text-brand-dark">
                    《大连市大数据研究院专家合作规则》
                  </button>
                </span>
              </label>
              {error && <div className="border border-red-100 bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}
              <div className="flex justify-end gap-3">
                <button type="button" onClick={() => setShowForm(false)} className="h-10 rounded-[4px] border border-line bg-white px-5 text-sm font-bold text-text-body hover:border-brand hover:text-brand">取消</button>
                <button disabled={submitting || !acceptedRules} className="inline-flex h-10 items-center gap-2 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white hover:bg-brand-dark disabled:cursor-not-allowed disabled:bg-line-dark">
                  {submitting && <Loader2 className="h-4 w-4 animate-spin" />}
                  提交申请
                </button>
              </div>
            </form>
          </section>
        ) : (
          <section className="grid min-h-[620px] items-center bg-ink px-8 py-14 text-white md:px-12">
            <div className="max-w-[780px]">
              <div className="text-sm font-extrabold text-white/70">成为专家</div>
              <h1 className="mt-5 text-[46px] font-extrabold leading-[1.08] md:text-[68px]">把你的专业判断接入真实项目现场</h1>
              <p className="mt-8 text-base leading-9 text-white/72">平台会审核你的专家方向、项目经验、代表成果和展示简介。通过后，专家档案会自动绑定当前会员通行证。</p>
              <button type="button" onClick={() => setShowForm(true)} className="mt-10 inline-flex h-11 items-center rounded-[4px] bg-white px-6 text-sm font-extrabold text-brand hover:bg-brand-light">
                填写专家申请
              </button>
            </div>
          </section>
        )}
      </div>

      {showRules && (
        <div className="fixed inset-0 z-[80] grid place-items-center bg-ink/36 px-6">
          <div className="w-full max-w-[760px] rounded-[4px] bg-white p-6 shadow-[0_24px_80px_rgba(15,23,42,0.22)]">
            <div className="flex items-start justify-between gap-4 border-b border-line pb-4">
              <h2 className="text-2xl font-extrabold text-ink">{agreement?.title || '大连市大数据研究院专家合作规则'}</h2>
              <button type="button" onClick={() => setShowRules(false)} className="text-sm font-extrabold text-muted hover:text-brand">关闭</button>
            </div>
            <div className="mt-5 max-h-[56vh] overflow-y-auto whitespace-pre-line pr-2 text-sm leading-7 text-muted">
              {agreement?.content || '规则加载中。'}
            </div>
            <button type="button" onClick={() => setShowRules(false)} className="mt-6 h-10 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white">我已阅读</button>
          </div>
        </div>
      )}
    </section>
  )
}
