import { useEffect, useMemo, useState } from "react"
import type { TaskPanelItem, TaskPanelStatus } from "@qjclaw/shared-types"
import { Panel } from "../../components/ui/Panel"
import { ScrollArea } from "../../components/ui/ScrollArea"
import { StatusChip, type StatusChipTone } from "../../components/ui/StatusChip"
import { getDefaultTaskPanelDate, loadTaskPanelItems } from "./taskPanelData"

const statusLabels: Record<TaskPanelStatus, string> = {
  pending: "待处理",
  running: "执行中",
  completed: "已完成",
  failed: "失败"
}

const statusTones: Record<TaskPanelStatus, StatusChipTone> = {
  pending: "warning",
  running: "info",
  completed: "positive",
  failed: "warning"
}

function TaskStatus({ item }: { item: TaskPanelItem }) {
  return (
    <div className="task-panel-status">
      <StatusChip tone={statusTones[item.status]}>
        <span className={"task-panel-status-dot task-panel-status-dot-" + item.status} aria-hidden="true" />
        {statusLabels[item.status]}
      </StatusChip>
      <span>{item.statusDetail}</span>
    </div>
  )
}

function TaskArtifacts({ item }: { item: TaskPanelItem }) {
  if (!item.artifacts.length) {
    return <span className="task-panel-muted">暂无产物</span>
  }

  return (
    <ul className="task-panel-artifact-list" aria-label={item.taskTitle + "产物清单"}>
      {item.artifacts.map((artifact) => (
        <li key={artifact.id}>
          <span className="task-panel-artifact-name">{artifact.name}</span>
          {artifact.kind ? <span className="task-panel-artifact-kind">{artifact.kind}</span> : null}
        </li>
      ))}
    </ul>
  )
}

export function TaskPanelView() {
  const [selectedDate, setSelectedDate] = useState(getDefaultTaskPanelDate)
  const [items, setItems] = useState<TaskPanelItem[]>([])
  const [loading, setLoading] = useState(true)
  const [errorText, setErrorText] = useState("")

  useEffect(() => {
    let active = true
    setLoading(true)
    setErrorText("")

    void loadTaskPanelItems(selectedDate)
      .then((nextItems) => {
        if (active) {
          setItems(nextItems)
        }
      })
      .catch((error: unknown) => {
        if (active) {
          setItems([])
          setErrorText(error instanceof Error ? error.message : "任务列表加载失败")
        }
      })
      .finally(() => {
        if (active) {
          setLoading(false)
        }
      })

    return () => {
      active = false
    }
  }, [selectedDate])

  const completedCount = useMemo(() => items.filter((item) => item.status === "completed").length, [items])

  return (
    <div className="page-stack task-panel-page-stack">
      <Panel className="task-panel-page" bodyClassName="task-panel-body">
        <div className="task-panel-header">
          <div className="task-panel-title-group">
            <h1>任务面板</h1>
            <p>{items.length ? `${items.length} 个任务，${completedCount} 个已完成` : "按日期查看专家任务与产物"}</p>
          </div>
          <label className="task-panel-date-field">
            <span>日期</span>
            <input
              type="date"
              value={selectedDate}
              onChange={(event) => setSelectedDate(event.currentTarget.value)}
            />
          </label>
        </div>

        <ScrollArea className="scroll-panel task-panel-scroll" aria-busy={loading}>
          {loading ? <div className="empty-state task-panel-state">任务列表加载中...</div> : null}
          {!loading && errorText ? <div className="notice error task-panel-state" role="alert">{errorText}</div> : null}
          {!loading && !errorText && !items.length ? <div className="empty-state task-panel-state">当天暂无任务</div> : null}
          {!loading && !errorText && items.length ? (
            <div className="task-panel-table" role="table" aria-label="任务面板">
              <div className="task-panel-row task-panel-row-head" role="row">
                <div role="columnheader">专家</div>
                <div role="columnheader">执行状态</div>
                <div role="columnheader">产物清单</div>
              </div>
              {items.map((item) => (
                <article key={item.id} className="task-panel-row" role="row">
                  <div className="task-panel-expert-cell" role="cell">
                    <strong>{item.expertName}</strong>
                    <span>{item.taskTitle}</span>
                  </div>
                  <div role="cell">
                    <TaskStatus item={item} />
                  </div>
                  <div role="cell">
                    <TaskArtifacts item={item} />
                  </div>
                </article>
              ))}
            </div>
          ) : null}
        </ScrollArea>
      </Panel>
    </div>
  )
}
