import { Fragment, type ReactNode } from 'react'
import { Link } from 'react-router-dom'
import {
  copyMissionDetailPath,
  GENERATE_COPY_DRAFT_PIPELINE_STEPS,
  GENERATE_COPY_MATRIX_PIPELINE_STEPS,
  replicateJobScanPostId,
} from '../lib/copyFlow'
import type { JobData } from '../types/api'
import { Card } from './ui'
import { CopyMissionAnalyzeJobPanel } from './CopyMissionAnalyzeJobPanel'
import { CopyMissionJobPanel } from './CopyMissionJobPanel'
import { ViralScanJobPanel } from './ViralScanJobPanel'

type Props = {
  missionId: string
  analyzeJob: JobData | null
  scanJob: JobData | null
  matrixJob: JobData | null
  replicateJobs: JobData[]
}

function JobSectionHeader({
  title,
  hash,
  missionId,
}: {
  title: string
  hash: string
  missionId: string
}) {
  return (
    <div className="flex flex-wrap items-center justify-between gap-2">
      <p className="text-sm font-bold text-ink">{title}</p>
      <Link
        to={copyMissionDetailPath(missionId, hash)}
        className="text-xs font-semibold text-brand hover:underline"
      >
        查看區塊
      </Link>
    </div>
  )
}

function SectionDivider() {
  return <div className="border-t border-line pt-4" />
}

type Section = {
  key: string
  title: string
  hash: string
  content: ReactNode
}

export function CopyMissionActiveJobsCard({
  missionId,
  analyzeJob,
  scanJob,
  matrixJob,
  replicateJobs,
}: Props) {
  const sections: Section[] = []

  if (analyzeJob) {
    sections.push({
      key: 'analyze',
      title: '研究地圖',
      hash: '#copy-research',
      content: <CopyMissionAnalyzeJobPanel job={analyzeJob} />,
    })
  }
  if (scanJob) {
    sections.push({
      key: 'scan',
      title: '爆款海巡',
      hash: '#copy-output',
      content: <ViralScanJobPanel job={scanJob} />,
    })
  }
  if (matrixJob) {
    sections.push({
      key: 'matrix',
      title: '內容矩陣',
      hash: '#copy-output',
      content: (
        <CopyMissionJobPanel
          job={matrixJob}
          steps={GENERATE_COPY_MATRIX_PIPELINE_STEPS}
          fallbackSummary="內容矩陣產出中…"
        />
      ),
    })
  }
  for (const job of replicateJobs) {
    const postId = replicateJobScanPostId(job)
    const shortId = postId ? postId.slice(0, 8) : job.id.slice(0, 8)
    sections.push({
      key: `replicate-${job.id}`,
      title: `深仿寫 · ${shortId}`,
      hash: '#copy-output',
      content: (
        <CopyMissionJobPanel
          job={job}
          steps={GENERATE_COPY_DRAFT_PIPELINE_STEPS}
          fallbackSummary="深仿寫產出中…"
        />
      ),
    })
  }

  if (!sections.length) return null

  return (
    <div id="copy-mission-active-jobs">
      <Card className="hx-copy-active-jobs">
        <h2 className="hx-copy-section-title">進行中任務</h2>
        <p className="text-xs leading-relaxed text-muted">
          重新整理頁面後仍會從這裡追蹤進度；完成後此區塊會自動消失。
        </p>
        <div className="grid gap-4">
          {sections.map((section, index) => (
            <Fragment key={section.key}>
              {index > 0 ? <SectionDivider /> : null}
              <div className="space-y-3">
                <JobSectionHeader title={section.title} hash={section.hash} missionId={missionId} />
                {section.content}
              </div>
            </Fragment>
          ))}
        </div>
      </Card>
    </div>
  )
}