'use client'

import Link from 'next/link'
import { useParams, useRouter, useSearchParams } from 'next/navigation'
import { Suspense, useEffect, useState } from 'react'
import { ChevronRight, Upload } from 'lucide-react'
import { useApp } from '@/components/providers/AppProvider'
import { backend, mapBackendTask, yuan, type BackendTask, type UploadedFileSummary } from '@/lib/backend'
import type { AgentProduct } from '@/types'

function displayStatus(status: string) {
  if (status === '待提交资料' || status === '已完成') return status
  return `已提交 · ${status}`
}

function AccountDeliveryDetailContent() {
  const params = useParams<{ id: string }>()
  const searchParams = useSearchParams()
  const router = useRouter()
  const { user, token } = useApp()
  const [task, setTask] = useState<BackendTask | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [selectedFiles, setSelectedFiles] = useState<File[]>([])
  const taskView = task ? mapBackendTask(task) : null
  const isAgentTask = task?.type === 'agent'
  const isExpertTask = task?.type === 'expert'
  const showForm = searchParams.get('form') === '1'
  const productId = task?.productId || task?.id.split('-agent-')[1]
  const [agentProduct, setAgentProduct] = useState<AgentProduct | null>(null)
  const [form, setForm] = useState({
    organization: user?.organization || '',
    contact: user?.contactPhone || user?.phone || '',
    background: '',
  })

  useEffect(() => {
    if (!token || !params.id) return
    let mounted = true
    setLoading(true)
    backend.accountTask(token, params.id)
      .then((item) => {
        if (!mounted) return
        setTask(item)
        setError('')
        setForm({
          organization: String(item.materialPayload?.organization || user?.organization || ''),
          contact: String(item.materialPayload?.contact || user?.contactPhone || user?.phone || ''),
          background: String(item.materialPayload?.background || ''),
        })
      })
      .catch((err) => {
        if (mounted) setError(err instanceof Error ? err.message : '交付任务加载失败')
      })
      .finally(() => {
        if (mounted) setLoading(false)
      })
    return () => {
      mounted = false
    }
  }, [params.id, token, user?.contactPhone, user?.organization, user?.phone])

  useEffect(() => {
    if (!productId || !isAgentTask) return
    void backend.agentProduct(productId)
      .then((item) => setAgentProduct({
        id: item.id,
        slug: item.slug,
        title: item.title,
        scenarioTags: item.scenarioTags,
        registeredAccess: item.registeredAccess,
        juniorAccess: item.juniorAccess,
        seniorAccess: item.seniorAccess,
        registeredPriceAmount: item.registeredPriceAmount,
        juniorPriceAmount: item.juniorPriceAmount,
        seniorPriceAmount: item.seniorPriceAmount,
        price: yuan(item.priceAmount),
        detailDescription: item.detailDescription,
        summary: item.summary,
        deliveryNote: item.deliveryNote,
        coverUrl: item.coverUrl,
      }))
      .catch(() => setAgentProduct(null))
  }, [isAgentTask, productId])

  if (!user) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">尚未登录</h1>
          <Link href="/login?redirect=%2Faccount" className="mt-7 inline-flex rounded-[4px] bg-brand px-6 py-3 text-sm font-extrabold text-white">去登录</Link>
        </div>
      </section>
    )
  }

  if (loading) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center text-sm font-bold text-muted">
          正在加载交付任务...
        </div>
      </section>
    )
  }

  if (!task || !taskView) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] rounded-[4px] border border-line bg-white p-10 text-center">
          <h1 className="text-2xl font-extrabold text-ink">交付任务不存在</h1>
          {error && <p className="mt-3 text-sm font-bold text-muted">{error}</p>}
          <Link href="/account/agents" className="mt-7 inline-flex rounded-[4px] bg-brand px-6 py-3 text-sm font-extrabold text-white">返回我的智能体</Link>
        </div>
      </section>
    )
  }

  return (
    <section className="bg-bg py-8">
      <div className="mx-auto max-w-[1040px] px-6">
        <nav className="mb-5 flex items-center gap-2 text-sm font-bold text-soft">
          <Link href="/account" className="text-muted hover:text-brand">个人中心</Link>
          <ChevronRight className="h-4 w-4" />
          <Link href="/account/agents" className="text-muted hover:text-brand">我的智能体</Link>
          <ChevronRight className="h-4 w-4" />
          <span className="text-ink">{task.title}</span>
        </nav>

        <div className="grid gap-6">
          <div className="rounded-[4px] border border-line bg-white">
            {showForm ? (
              <form
                className="p-7"
	                onSubmit={async (event) => {
	                  event.preventDefault()
	                  if (!token) return
	                  setSubmitting(true)
	                  setError('')
	                  try {
	                    const uploaded: UploadedFileSummary[] = []
	                    for (const file of selectedFiles) {
	                      uploaded.push(await backend.uploadAccountFile(token, file))
	                    }
	                    const updated = await backend.submitAccountTaskMaterials(token, task.taskNo || task.id, {
	                      ...form,
	                      fileIds: uploaded.map((file) => file.id),
	                      files: uploaded,
	                    })
	                    setTask(updated)
	                    router.replace(`/account/delivery/${task.taskNo || task.id}`)
	                  } catch (err) {
	                    setError(err instanceof Error ? err.message : '资料提交失败')
	                  } finally {
	                    setSubmitting(false)
	                  }
	                }}
	              >
                <div className="mb-7 border-b border-line pb-5">
                  <h1 className="text-2xl font-extrabold text-ink">{isExpertTask ? '填写咨询背景' : '填写交付资料'}</h1>
                  <p className="mt-2 max-w-[680px] text-sm leading-7 text-muted">
                    补充项目背景、使用场景和交付要求后，团队会进入资料审核与配置确认。
                  </p>
                </div>

                <div className="grid gap-6 lg:grid-cols-[1fr_240px]">
                  <div className="grid gap-5">
                    <div className="grid gap-4 md:grid-cols-2">
                      <label className="block">
                        <span className="mb-2 block text-sm font-extrabold text-ink">{isAgentTask ? '使用机构' : isExpertTask ? '咨询单位' : '机构名称'}</span>
                        <input value={form.organization} onChange={(event) => setForm((current) => ({ ...current, organization: event.target.value }))} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm font-bold text-ink outline-none focus:border-brand" />
                      </label>
                      <label className="block">
                        <span className="mb-2 block text-sm font-extrabold text-ink">联系手机号</span>
                        <input value={form.contact} onChange={(event) => setForm((current) => ({ ...current, contact: event.target.value }))} className="h-11 w-full rounded-[4px] border border-line px-3 text-sm font-bold text-ink outline-none focus:border-brand" />
                      </label>
                    </div>

                    <label className="block">
                      <span className="mb-2 block text-sm font-extrabold text-ink">{isAgentTask ? '业务场景 / 配置要求' : isExpertTask ? '咨询背景补充' : '需求背景 / 补充资料'}</span>
                      <textarea
                        value={form.background}
                        onChange={(event) => setForm((current) => ({ ...current, background: event.target.value }))}
                        rows={7}
                        placeholder={isAgentTask ? '例如：使用部门、输入材料格式、希望生成的结果、是否需要人工复核。' : isExpertTask ? '例如：需要专家提前了解的项目背景、资料口径或重点问题。' : undefined}
                        className="w-full rounded-[4px] border border-line p-3 text-sm font-bold leading-7 text-ink outline-none focus:border-brand"
                      />
                    </label>
                  </div>

                  <label className="grid min-h-[180px] cursor-pointer place-items-center rounded-[4px] border border-dashed border-line-dark bg-bg/60 px-5 text-center transition hover:border-brand hover:bg-brand/5">
                    <span>
                      <Upload className="mx-auto h-6 w-6 text-brand" />
                      <span className="mt-3 block text-sm font-extrabold text-ink">上传补充材料</span>
                      <span className="mt-2 block text-xs leading-5 text-muted">支持需求文档、样表或业务说明，选填。</span>
                    </span>
	                    <input type="file" multiple onChange={(event) => setSelectedFiles(Array.from(event.target.files || []))} className="sr-only" />
	                  </label>
	                  {selectedFiles.length > 0 && (
	                    <div className="text-xs font-bold leading-6 text-muted lg:col-start-2">
	                      已选择 {selectedFiles.length} 个文件
	                    </div>
	                  )}
	                </div>

	                <div className="mt-7 flex gap-3 border-t border-line pt-5">
	                  <button disabled={submitting} className="rounded-[4px] bg-brand px-6 py-3 text-sm font-extrabold text-white hover:bg-brand-dark disabled:opacity-60">{submitting ? '提交中...' : isExpertTask ? '提交补充信息' : '提交资料'}</button>
	                  <Link href={`/account/delivery/${task.taskNo || task.id}`} className="rounded-[4px] border border-line px-6 py-3 text-sm font-bold text-text-body hover:border-brand hover:text-brand">取消</Link>
	                </div>
	              </form>
            ) : (
              <div className="p-6">
                {isAgentTask && (
                  <div className="grid gap-5 md:grid-cols-[180px_1fr] md:items-start">
                    <div
                      className="aspect-square rounded-[4px] bg-bg bg-cover bg-center"
                      style={{ backgroundImage: agentProduct?.coverUrl ? `url(${agentProduct.coverUrl})` : undefined }}
                    >
                      {!agentProduct?.coverUrl && <div className="grid h-full place-items-center px-3 text-center text-xs font-extrabold text-soft">暂无图片</div>}
                    </div>
                    <div>
	                      <h1 className="text-2xl font-extrabold text-ink">{task.title}</h1>
                      {agentProduct ? (
                        <p className="mt-3 text-sm leading-7 text-muted">{agentProduct.summary}</p>
                      ) : (
                        <p className="mt-3 text-sm leading-7 text-muted">该智能体服务已开通，可在这里查看交付进度和后续资料要求。</p>
                      )}
                    </div>
                  </div>
                )}

                <div className="mt-7 border-t border-line pt-6">
                  <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
                    <div>
                      <div className="text-lg font-extrabold text-ink">当前进度</div>
	                      <div className="mt-1 text-sm text-muted">{displayStatus(taskView.status)} · {taskView.steps[taskView.currentStep]}</div>
                    </div>
	                    {taskView.status === '待提交资料' && (
	                      <Link href={`/account/delivery/${task.taskNo || task.id}?form=1`} className="inline-flex items-center gap-2 rounded-[4px] bg-brand px-5 py-2.5 text-sm font-extrabold text-white hover:bg-brand-dark">
                        <Upload className="h-4 w-4" />
                        {isExpertTask ? '填写咨询背景' : '填写交付资料'}
                      </Link>
                    )}
                  </div>

	                  <div className="mt-7 grid gap-4 md:grid-cols-4">
	                    {taskView.steps.map((step, index) => (
                      <div
                        key={step}
                        className="relative"
                      >
	                        {index < taskView.steps.length - 1 && (
	                          <div className={`absolute left-3 top-3 hidden h-px w-[calc(100%+1rem)] md:block ${index < taskView.currentStep ? 'bg-brand/55' : 'bg-line-dark'}`} />
                        )}
                        <div className={`relative z-10 h-6 w-6 rounded-full border-2 bg-white ${
	                          index <= taskView.currentStep ? 'border-brand' : 'border-line-dark'
	                        }`}>
	                          {index < taskView.currentStep && <div className="m-1.5 h-2.5 w-2.5 rounded-full bg-brand" />}
	                          {index === taskView.currentStep && <div className="m-1 h-3 w-3 rounded-full bg-brand" />}
	                        </div>
	                        <div className={`mt-3 text-xs font-bold ${index === taskView.currentStep ? 'text-brand' : index < taskView.currentStep ? 'text-ink' : 'text-muted'}`}>
	                          0{index + 1}
	                        </div>
	                        <div className={`mt-1 text-sm font-extrabold ${index === taskView.currentStep ? 'text-brand' : index < taskView.currentStep ? 'text-ink' : 'text-muted'}`}>
	                          {step}
	                        </div>
	                      </div>
	                    ))}
	                  </div>
	                  {(task.materialPayload?.background || task.materialPayload?.files?.length || task.progressNote) && (
	                    <div className="mt-7 rounded-[4px] bg-bg p-4 text-sm leading-7 text-muted">
	                      <div className="font-extrabold text-ink">已提交资料</div>
	                      {task.materialPayload?.organization && <div className="mt-2">机构：{task.materialPayload.organization}</div>}
	                      {task.materialPayload?.contact && <div>联系：{task.materialPayload.contact}</div>}
	                      {task.materialPayload?.background && <div className="whitespace-pre-wrap">说明：{task.materialPayload.background}</div>}
	                      {(task.materialPayload?.files || []).length > 0 && (
	                        <div className="mt-2 grid gap-1">
	                          {(task.materialPayload?.files || []).map((file) => (
	                            <a key={file.id} href={file.url || `/api/files/${file.id}`} className="font-extrabold text-brand hover:text-brand-dark">
	                              {file.fileName || file.id}
	                            </a>
	                          ))}
	                        </div>
	                      )}
	                    </div>
	                  )}
	                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  )
}

export default function AccountDeliveryDetailPage() {
  return (
    <Suspense fallback={<section className="bg-bg py-16 text-center text-sm font-bold text-muted">正在加载交付任务...</section>}>
      <AccountDeliveryDetailContent />
    </Suspense>
  )
}
