import { useQuery } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import { Badge } from '@/components/Badge'
import { DataTable } from '@/components/DataTable'
import { Pagination } from '@/components/Pagination'
import { formatCurrency, formatPercent } from '@/lib/utils'
import { useState, useMemo } from 'react'

const PAGE_SIZE = 5

export function TasksPage() {
  const navigate = useNavigate()
  const [month, setMonth] = useState('2026-05')
  const [priority, setPriority] = useState('')
  const [status, setStatus] = useState('')
  const [page, setPage] = useState(1)

  const { data } = useQuery({
    queryKey: ['tasks', month, priority, status],
    queryFn: () => api.get('/tasks', { params: { month, priority, status, page_size: 200 } }),
  })

  const tasks = (data as any)?.data || []
  const total = (data as any)?.meta?.total || 0

  const statusCounts = tasks.reduce((acc: any, t: any) => {
    acc[t.status] = (acc[t.status] || 0) + 1
    return acc
  }, {})

  const groups = useMemo(() =>
    Array.from(
      tasks.reduce((acc: Map<string, any>, t: any) => {
        const key = t.store_code
        if (!acc.has(key)) acc.set(key, { store_name: t.store_name, store_code: t.store_code, priority: t.priority, tasks: [] })
        acc.get(key).tasks.push(t)
        return acc
      }, new Map()).values()
    ), [tasks])

  const totalGroups = groups.length
  const pagedGroups = groups.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE)

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold">任务管理</h1>
        <span className="text-sm text-muted-foreground">共 {total} 条任务</span>
      </div>

      {/* 筛选器 */}
      <div className="flex flex-wrap gap-2">
        <input
          type="month"
          value={month}
          onChange={(e) => setMonth(e.target.value)}
          className="rounded-md border px-3 py-1.5 text-sm"
        />
        <select value={priority} onChange={(e) => setPriority(e.target.value)} className="rounded-md border px-3 py-1.5 text-sm">
          <option value="">全部优先级</option>
          <option value="P0-修复数据口径">P0-修复数据口径</option>
          <option value="P0-综合专项整改">P0-综合专项整改</option>
          <option value="P1-重点整改">P1-重点整改</option>
          <option value="P2-单项改善">P2-单项改善</option>
          <option value="标杆候选">标杆候选</option>
          <option value="持续跟踪">持续跟踪</option>
        </select>
        <select value={status} onChange={(e) => setStatus(e.target.value)} className="rounded-md border px-3 py-1.5 text-sm">
          <option value="">全部状态</option>
          <option value="待启动">待启动</option>
          <option value="进行中">进行中</option>
          <option value="已验收">已验收</option>
          <option value="已回滚">已回滚</option>
        </select>
      </div>

      {/* 状态汇总 */}
      <div className="flex gap-2">
        {Object.entries(statusCounts).map(([s, c]: any) => (
          <Badge key={s} type="status" text={`${s}: ${c}`} />
        ))}
      </div>

      {/* 分页 */}
      <Pagination page={page} pageSize={PAGE_SIZE} total={totalGroups} onPageChange={setPage} />

      {/* 任务列表 — 按门店分组 */}
      <div className="space-y-3">
        {pagedGroups.map((group: any) => (
          <div key={group.store_code} className="rounded-lg border bg-card overflow-hidden">
            {/* 门店组标题 */}
            <div
              className="flex items-center gap-2 border-b bg-muted/40 px-4 py-2 cursor-pointer hover:bg-muted/60"
              onClick={() => navigate(`/stores/${group.store_code}`)}
            >
              <Badge type="priority" text={group.priority} />
              <span className="text-sm font-bold">{group.store_name}</span>
              <span className="text-xs text-muted-foreground">{group.tasks.length} 项任务</span>
            </div>
            {/* 组内任务表 */}
            <DataTable
              columns={[
                { key: 'problem_indicator', label: '问题指标' },
                { key: 'action_required', label: '行动要求', render: (r) => <span className="text-xs">{r.action_required}</span> },
                { key: 'owner', label: '负责人' },
                { key: 'deadline', label: '截止日', render: (r) => r.deadline?.substring(0, 10) },
                { key: 'status', label: '状态', render: (r) => <Badge type="status" text={r.status} /> },
              ]}
              data={group.tasks}
              onRowClick={(r) => navigate(`/tasks/${r.task_id}`)}
              className="rounded-none border-0"
            />
          </div>
        ))}
      </div>
    </div>
  )
}
