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

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

  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

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

      {/* 筛选器 */}
      <div className="flex flex-wrap gap-2">
        <SearchSelect
          value={priority}
          onChange={setPriority}
          options={[
            { value: 'P0-修复数据口径', label: 'P0-修复数据口径' },
            { value: 'P0-综合专项整改', label: 'P0-综合专项整改' },
            { value: 'P1-重点整改', label: 'P1-重点整改' },
            { value: 'P2-单项改善', label: 'P2-单项改善' },
            { value: '标杆候选', label: '标杆候选' },
            { value: '持续跟踪', label: '持续跟踪' },
          ]}
          emptyLabel="全部优先级"
          className="min-w-[140px]"
        />
        <SearchSelect
          value={status}
          onChange={setStatus}
          options={['待启动', '进行中', '已验收', '已回滚']}
          emptyLabel="全部状态"
          className="min-w-[120px]"
        />
      </div>

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

      {/* 任务列表 — 按门店分组 */}
      <div className="space-y-3">
        {groups.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>
            {/* 组内任务表 */}
            <FilterableTable
              data={group.tasks}
              sortOptions={[
                { key: 'priority', label: '优先级' },
                { key: 'deadline', label: '截止日' },
                { key: 'problem_indicator', label: '问题指标' },
              ]}
              defaultSort="priority"
              defaultOrder="asc"
              filterKey="status"
              filterLabel="全部状态"
              onRowClick={(r) => navigate(`/tasks/${r.task_id}`)}
              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} /> },
              ]}
            />
          </div>
        ))}
      </div>
    </div>
  )
}
