import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useParams, useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import { Badge } from '@/components/Badge'
import { useState } from 'react'
import { ArrowLeft, CheckCircle, RotateCcw, Clock, User, Target, AlertCircle, FileText, History } from 'lucide-react'

export function TaskDetailPage() {
  const { id } = useParams()
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [executeText, setExecuteText] = useState('')
  const [verifyResult, setVerifyResult] = useState('改善中')
  const [verifyActual, setVerifyActual] = useState('')
  const [showFormula, setShowFormula] = useState(false)

  const { data } = useQuery({
    queryKey: ['task', id],
    queryFn: () => api.get(`/tasks/${id}`),
  })

  const { data: indicatorsData } = useQuery({
    queryKey: ['indicators'],
    queryFn: () => api.get('/tasks/indicators'),
  })

  const td = (data as any)?.data
  const task = td?.task
  const logs = td?.logs || []
  const indicators = (indicatorsData as any)?.data || []
  const indicator = indicators.find((i: any) => i.indicator_name === task?.problem_indicator)
  const executeMutation = useMutation({
    mutationFn: (text: string) => api.put(`/tasks/${id}/execute`, { process_evidence: text }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['task', id] }),
  })

  const verifyMutation = useMutation({
    mutationFn: (data: any) => api.put(`/tasks/${id}/verify`, data),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['task', id] }),
  })

  const rollbackMutation = useMutation({
    mutationFn: (reason: string) => api.post(`/tasks/${id}/rollback`, { reason }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['task', id] }),
  })

  if (!task) return <div className="flex items-center justify-center py-20 text-muted-foreground">加载中...</div>

  const fmt = (v: any) => v === null || v === undefined || v === '' ? '-' : Number(v).toFixed(2)
  const hasNumericValues = task.current_value !== null && task.current_value !== undefined
  const isOverTarget = hasNumericValues && task.target_value !== null && Number(task.current_value) <= Number(task.target_value)

  return (
    <div className="space-y-5">
      {/* 返回按钮 */}
      <button
        onClick={() => navigate(-1)}
        className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
      >
        <ArrowLeft size={16} /> 返回列表
      </button>

      {/* 头部卡片 */}
      <div className="rounded-xl border bg-card p-5 shadow-sm">
        <div className="flex items-start justify-between">
          <div>
            <h1 className="text-xl font-bold">{task.store_name}</h1>
            <p className="mt-1 text-sm text-muted-foreground">{task.problem_indicator}</p>
          </div>
          <div className="flex gap-2">
            <Badge type="priority" text={task.priority} />
            <Badge type="status" text={task.status} />
          </div>
        </div>
      </div>

      {/* 指标卡 — 数值型指标显示三卡，非数值型显示验收标准 */}
      {hasNumericValues ? (
        <div className="grid gap-3 md:grid-cols-3">
          {/* 当前值 */}
          <div className={`rounded-xl border p-4 ${isOverTarget ? 'border-green-300 bg-green-50/50' : 'border-orange-300 bg-orange-50/50'}`}>
            <p className="text-xs font-medium text-muted-foreground">当前值</p>
            <div className="mt-1.5 flex items-baseline gap-1">
              <span className={`text-2xl font-bold ${isOverTarget ? 'text-green-700' : 'text-orange-700'}`}>{fmt(task.current_value)}</span>
              {indicator?.update_frequency && <span className="text-xs text-muted-foreground">/ {indicator.update_frequency}</span>}
            </div>
          </div>
          {/* 基准值 */}
          <div className="rounded-xl border bg-card p-4 shadow-sm">
            <p className="text-xs font-medium text-muted-foreground">基准值（4月）</p>
            <div className="mt-1.5 flex items-baseline gap-1">
              <span className="text-2xl font-bold text-muted-foreground">{fmt(task.benchmark_value)}</span>
            </div>
          </div>
          {/* 目标值 */}
          <div className="rounded-xl border border-blue-200 bg-blue-50/50 p-4">
            <p className="text-xs font-medium text-muted-foreground">目标值</p>
            <div className="mt-1.5 flex items-baseline gap-1">
              <span className="text-2xl font-bold text-blue-700">{fmt(task.target_value)}</span>
            </div>
          </div>
        </div>
      ) : (
        <div className="rounded-xl border border-blue-200 bg-blue-50/50 p-4">
          <p className="text-xs font-medium text-muted-foreground">验收标准</p>
          <p className="mt-1.5 text-sm font-medium text-blue-700">{task.verification_indicator || '-'}</p>
          <p className="mt-1 text-xs text-muted-foreground">此任务为定性指标，按验收标准衡量完成情况</p>
        </div>
      )}

      {/* 指标计算说明 — 可折叠 */}
      {indicator && (
        <div className="rounded-xl border bg-card overflow-hidden">
          <button
            onClick={() => setShowFormula(!showFormula)}
            className="flex w-full items-center justify-between px-4 py-3 text-sm font-medium hover:bg-muted/40 transition-colors"
          >
            <span className="flex items-center gap-2">
              <Target size={16} className="text-muted-foreground" />
              {indicator.indicator_name} — 指标说明
            </span>
            <span className="text-xs text-muted-foreground">{showFormula ? '收起 ▲' : '展开 ▼'}</span>
          </button>
          {showFormula && (
            <div className="border-t px-4 py-3 space-y-2 text-sm">
              <div><span className="text-muted-foreground">业务定义：</span>{indicator.business_definition}</div>
              <div className="flex items-start gap-2">
                <span className="text-muted-foreground whitespace-nowrap">计算公式：</span>
                <code className="rounded bg-muted px-2 py-0.5 text-xs font-mono">{indicator.formula}</code>
              </div>
              <div className="flex flex-wrap gap-4 text-xs text-muted-foreground">
                <span>数据来源：{indicator.data_source || '-'}</span>
                <span>更新频率：{indicator.update_frequency}</span>
              </div>
              <div className="flex gap-4 text-xs">
                <span className="rounded bg-yellow-100 px-2 py-0.5 text-yellow-800">黄线 {indicator.yellow_threshold ?? '-'}</span>
                <span className="rounded bg-red-100 px-2 py-0.5 text-red-800">红线 {indicator.red_threshold ?? '-'}</span>
              </div>
              <div className="border-t pt-2 text-xs text-muted-foreground">
                当前值 = 4月实际值 | 基准值 = 4月基线值 | 目标值 = 需改善到的目标值
              </div>
            </div>
          )}
        </div>
      )}

      {/* 任务详情卡片 */}
      <div className="rounded-xl border bg-card p-5 space-y-3">
        <h2 className="flex items-center gap-2 text-sm font-bold">
          <FileText size={16} className="text-muted-foreground" /> 任务详情
        </h2>
        <div className="grid gap-3 md:grid-cols-2">
          <div className="flex items-start gap-2">
            <AlertCircle size={16} className="mt-0.5 shrink-0 text-muted-foreground" />
            <div>
              <p className="text-xs text-muted-foreground">问题描述</p>
              <p className="text-sm">{task.problem_description || '-'}</p>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <Target size={16} className="mt-0.5 shrink-0 text-muted-foreground" />
            <div>
              <p className="text-xs text-muted-foreground">验收指标</p>
              <p className="text-sm">{task.verification_indicator || '-'}</p>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <FileText size={16} className="mt-0.5 shrink-0 text-muted-foreground" />
            <div>
              <p className="text-xs text-muted-foreground">行动要求</p>
              <p className="text-sm">{task.action_required || '-'}</p>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <User size={16} className="mt-0.5 shrink-0 text-muted-foreground" />
            <div>
              <p className="text-xs text-muted-foreground">负责人</p>
              <p className="text-sm">{task.owner}</p>
            </div>
          </div>
          <div className="flex items-start gap-2">
            <Clock size={16} className="mt-0.5 shrink-0 text-muted-foreground" />
            <div>
              <p className="text-xs text-muted-foreground">截止日</p>
              <p className="text-sm">{task.deadline?.substring(0, 10)}</p>
            </div>
          </div>
          {task.process_evidence && (
            <div className="flex items-start gap-2">
              <FileText size={16} className="mt-0.5 shrink-0 text-muted-foreground" />
              <div>
                <p className="text-xs text-muted-foreground">过程证据</p>
                <p className="text-sm">{task.process_evidence}</p>
              </div>
            </div>
          )}
          {task.incomplete_reason && (
            <div className="flex items-start gap-2">
              <AlertCircle size={16} className="mt-0.5 shrink-0 text-red-500" />
              <div>
                <p className="text-xs text-muted-foreground">未完成原因</p>
                <p className="text-sm text-red-600">{task.incomplete_reason}</p>
              </div>
            </div>
          )}
          {task.verification_result && (
            <div className="flex items-start gap-2">
              <CheckCircle size={16} className="mt-0.5 shrink-0 text-muted-foreground" />
              <div>
                <p className="text-xs text-muted-foreground">验收结果</p>
                <div className="mt-0.5"><Badge type="status" text={task.verification_result} /></div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* 执行反馈 */}
      {task.status === '待启动' && (
        <div className="rounded-xl border bg-card p-5">
          <h2 className="mb-3 flex items-center gap-2 text-sm font-bold">
            <FileText size={16} className="text-muted-foreground" /> 执行反馈
          </h2>
          <textarea
            value={executeText}
            onChange={(e) => setExecuteText(e.target.value)}
            placeholder="填写执行结果和过程证据..."
            className="mb-3 w-full rounded-lg border p-3 text-sm focus:ring-2 focus:ring-primary/20 focus:outline-none"
            rows={3}
          />
          <button
            onClick={() => executeMutation.mutate(executeText)}
            disabled={!executeText || executeMutation.isPending}
            className="rounded-lg bg-primary px-5 py-2 text-sm font-medium text-primary-foreground disabled:opacity-50 hover:bg-primary/90 transition-colors"
          >
            {executeMutation.isPending ? '提交中...' : '提交执行反馈'}
          </button>
        </div>
      )}

      {/* 月度验收 */}
      {task.status === '进行中' && (
        <div className="rounded-xl border bg-card p-5">
          <h2 className="mb-3 flex items-center gap-2 text-sm font-bold">
            <CheckCircle size={16} className="text-muted-foreground" /> 月度验收
          </h2>
          <div className="flex flex-wrap gap-2 mb-3">
            {['达标', '改善中', '未改善'].map((r) => (
              <button
                key={r}
                onClick={() => setVerifyResult(r)}
                className={`rounded-lg border px-4 py-2 text-sm transition-colors ${verifyResult === r
                  ? r === '达标' ? 'border-green-500 bg-green-500 text-white'
                  : r === '未改善' ? 'border-red-500 bg-red-500 text-white'
                  : 'border-primary bg-primary text-primary-foreground'
                  : 'hover:bg-muted'}`}
              >
                {r}
              </button>
            ))}
          </div>
          <input
            type="number"
            value={verifyActual}
            onChange={(e) => setVerifyActual(e.target.value)}
            placeholder="实际值"
            className="mb-3 block w-48 rounded-lg border p-2 text-sm focus:ring-2 focus:ring-primary/20 focus:outline-none"
          />
          <div className="flex gap-2">
            <button
              onClick={() => verifyMutation.mutate({
                review_result: verifyResult,
                actual_value: parseFloat(verifyActual),
                revenue_stable: true,
                margin_improved: verifyResult === '达标',
                customer_stable: true,
                anomaly_decreased: verifyResult !== '未改善',
              })}
              disabled={verifyMutation.isPending}
              className="flex items-center gap-1.5 rounded-lg bg-green-600 px-5 py-2 text-sm font-medium text-white disabled:opacity-50 hover:bg-green-700 transition-colors"
            >
              <CheckCircle size={16} /> 确认验收
            </button>
            <button
              onClick={() => { if (confirm('确认回滚此任务？')) rollbackMutation.mutate('指标改善但收入/顾客恶化') }}
              disabled={rollbackMutation.isPending}
              className="flex items-center gap-1.5 rounded-lg border border-red-300 px-5 py-2 text-sm font-medium text-red-600 disabled:opacity-50 hover:bg-red-50 transition-colors"
            >
              <RotateCcw size={16} /> 回滚
            </button>
          </div>
        </div>
      )}

      {/* 操作日志 */}
      <div className="rounded-xl border bg-card p-5">
        <h2 className="mb-3 flex items-center gap-2 text-sm font-bold">
          <History size={16} className="text-muted-foreground" /> 操作日志
        </h2>
        {logs.length === 0 ? (
          <p className="text-sm text-muted-foreground">暂无操作记录</p>
        ) : (
          <div className="space-y-0">
            {logs.map((log: any, idx: number) => (
              <div key={log.log_id} className="flex items-center gap-3 py-2.5 border-b last:border-0">
                <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground">
                  {idx + 1}
                </div>
                <div className="flex-1 flex flex-wrap items-center gap-2">
                  <Badge text={log.action} />
                  {log.new_status && <Badge type="status" text={log.new_status} />}
                  <span className="text-xs text-muted-foreground">{log.operator}</span>
                  {log.comment && <span className="text-xs text-muted-foreground">— {log.comment.substring(0, 80)}</span>}
                </div>
                <span className="text-xs text-muted-foreground whitespace-nowrap">{log.created_at?.substring(0, 19)}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
