'use client'

import { FormEvent, useMemo, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Building2 } from 'lucide-react'
import { useApp } from '@/components/providers/AppProvider'
import { backend } from '@/lib/backend'

export function AboutContactForm() {
  const router = useRouter()
  const { hydrated, requireLogin, token, user } = useApp()
  const [name, setName] = useState('')
  const [phone, setPhone] = useState('')
  const [organization, setOrganization] = useState('')
  const [demand, setDemand] = useState('')
  const [touched, setTouched] = useState(false)
  const [error, setError] = useState('')
  const [submitting, setSubmitting] = useState(false)

  const missing = useMemo(() => {
    const fields: string[] = []
    if (!name.trim()) fields.push('姓名')
    if (!phone.trim()) fields.push('联系方式')
    if (!organization.trim()) fields.push('所在机构')
    if (!demand.trim()) fields.push('合作需求')
    return fields
  }, [demand, name, organization, phone])

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    setTouched(true)
    setError('')
    if (!user || !token) {
      requireLogin()
      return
    }
    if (missing.length > 0) return

    setSubmitting(true)
    try {
      const request = await backend.createCooperationRequest(token, {
        name: name.trim(),
        phone: phone.trim(),
        organization: organization.trim(),
        demand: demand.trim(),
      })
      router.push(`/about/contact/success?id=${encodeURIComponent(request.requestNo || request.id)}`)
    } catch (err) {
      setError(err instanceof Error ? err.message : '合作需求提交失败')
    } finally {
      setSubmitting(false)
    }
  }

  function requireBeforeInput() {
    if (!hydrated || user) return
    requireLogin()
  }

  return (
    <form onSubmit={handleSubmit} data-reveal="right" className="rounded-[4px] border border-line bg-bg/70 p-6 lg:mt-0">
      <div className="mb-5 flex items-center gap-3">
        <Building2 className="h-5 w-5 text-brand" />
        <h3 className="text-xl font-extrabold text-ink">合作咨询</h3>
      </div>
      <div className="space-y-3">
        <div className="grid gap-3 md:grid-cols-2">
          <input value={name} onFocus={requireBeforeInput} onChange={(event) => setName(event.target.value)} placeholder="您的姓名" className="h-11 rounded-[4px] border border-line bg-white px-4 text-sm outline-none transition-colors focus:border-brand" />
          <input value={phone} onFocus={requireBeforeInput} onChange={(event) => setPhone(event.target.value)} placeholder="联系方式" className="h-11 rounded-[4px] border border-line bg-white px-4 text-sm outline-none transition-colors focus:border-brand" />
        </div>
        <input value={organization} onFocus={requireBeforeInput} onChange={(event) => setOrganization(event.target.value)} placeholder="所在机构" className="h-11 w-full rounded-[4px] border border-line bg-white px-4 text-sm outline-none transition-colors focus:border-brand" />
        <textarea
          value={demand}
          onFocus={requireBeforeInput}
          onChange={(event) => setDemand(event.target.value)}
          placeholder="请简述您的需求..."
          rows={5}
          className="w-full resize-none rounded-[4px] border border-line bg-white px-4 py-3 text-sm outline-none transition-colors focus:border-brand"
        />
        {touched && missing.length > 0 && (
          <div className="rounded-[4px] bg-white px-4 py-3 text-xs font-bold text-[#b45309]">
            请补充：{missing.join('、')}
          </div>
        )}
        {error && <div className="rounded-[4px] bg-red-50 px-4 py-3 text-xs font-bold text-red-700">{error}</div>}
        <button disabled={submitting} className="w-full rounded-[4px] bg-brand py-3 text-sm font-extrabold text-white transition-colors hover:bg-brand-dark disabled:bg-line-dark">
          {submitting ? '提交中...' : '提交需求'}
        </button>
      </div>
    </form>
  )
}
