import { useState, useMemo, Fragment } from 'react'
import { useQuery } from '@tanstack/react-query'
import api from '@/lib/api'
import { Pagination } from '@/components/Pagination'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { SearchSelect } from '@/components/SearchSelect'
import { formatCurrency, formatNumber } from '@/lib/utils'

const PAGE_SIZE = 20

const ACTION_STYLES: Record<string, string> = {
  '建议招聘': 'bg-red-100 text-red-700',
  '建议优化': 'bg-orange-100 text-orange-700',
  '关注': 'bg-yellow-100 text-yellow-700',
  '维持': 'bg-green-100 text-green-700',
}

const LEVEL_ROW_STYLES: Record<string, string> = {
  red: 'bg-red-50/50',
  orange: 'bg-orange-50/50',
  yellow: 'bg-yellow-50/30',
}

export function StaffingForecastTab({ month }: { month: string }) {
  const [page, setPage] = useState(1)
  const [storeFilter, setStoreFilter] = useState('')
  const [actionFilter, setActionFilter] = useState('')
  const [sort, setSort] = useState('urgency')
  const [order, setOrder] = useState<'asc' | 'desc'>('desc')
  const [expandedRow, setExpandedRow] = useState<string | null>(null)
  const [showRules, setShowRules] = useState(false)

  const { data, isLoading } = useQuery({
    queryKey: ['ss/staffing-forecast', month],
    queryFn: () => api.get('/smart-scheduling/staffing-forecast', { params: { month } }),
  })

  const result = (data as any)?.data || {}
  const forecasts: any[] = result.forecasts || []
  const summary = result.summary || {}

  const storeNames = useMemo(() => [...new Set(forecasts.map((f) => f.store_name))].sort(), [forecasts])

  const filtered = useMemo(() => {
    let r = forecasts
    if (storeFilter) r = r.filter(f => f.store_name === storeFilter)
    if (actionFilter) r = r.filter(f => f.action === actionFilter)
    return [...r].sort((a, b) => {
      let av: number, bv: number
      if (sort === 'store_name') {
        return order === 'desc' ? b.store_name.localeCompare(a.store_name) : a.store_name.localeCompare(b.store_name)
      }
      av = parseFloat(a[sort]) || 0
      bv = parseFloat(b[sort]) || 0
      return order === 'desc' ? bv - av : av - bv
    })
  }, [forecasts, storeFilter, actionFilter, sort, order])

  const total = filtered.length
  const paged = filtered.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE)

  if (isLoading) return <LoadingSpinner text="生成人员预测分析..." />

  const sorts = [
    { key: 'urgency', label: '紧急度' },
    { key: 'store_name', label: '门店' },
    { key: 'emp_count', label: '人数' },
    { key: 'turnover_pct', label: '离职率' },
    { key: 'revenue_per_emp', label: '人均创收' },
    { key: 'avg_attend', label: '出勤天' },
  ]

  const rowKey = (r: any) => `${r.store_name}_${r.role}`

  return (
    <div className="space-y-4">
      {/* 汇总卡片 */}
      <div className="grid grid-cols-4 gap-3">
        <div className="rounded-lg border p-3 text-center">
          <p className="text-xs text-muted-foreground">预测总数</p>
          <p className="text-2xl font-bold mt-1">{summary.total || 0}</p>
        </div>
        <div className="rounded-lg border border-red-200 bg-red-50 p-3 text-center">
          <p className="text-xs text-red-600">建议招聘</p>
          <p className="text-2xl font-bold text-red-700 mt-1">{summary.hire || 0}</p>
        </div>
        <div className="rounded-lg border border-orange-200 bg-orange-50 p-3 text-center">
          <p className="text-xs text-orange-600">建议优化</p>
          <p className="text-2xl font-bold text-orange-700 mt-1">{summary.optimize || 0}</p>
        </div>
        <div className="rounded-lg border border-yellow-200 bg-yellow-50 p-3 text-center">
          <p className="text-xs text-yellow-600">需关注</p>
          <p className="text-2xl font-bold text-yellow-700 mt-1">{summary.watch || 0}</p>
        </div>
      </div>

      {/* 规则引擎面板 */}
      <div className="rounded-lg border">
        <button onClick={() => setShowRules(!showRules)} className="w-full flex items-center justify-between px-4 py-2 text-sm font-medium hover:bg-muted/50">
          <span>规则引擎说明（优化规则7条 + 招聘规则7条 + 决策逻辑4步）</span>
          <span className="text-xs text-muted-foreground">{showRules ? '收起 ▲' : '展开 ▼'}</span>
        </button>
        {showRules && result.ruleEngine && (
          <div className="border-t px-4 py-3 space-y-4">
            {/* 动态标准 */}
            <div>
              <p className="text-xs font-medium text-muted-foreground mb-2">动态标准值（基于全部门店中位数）</p>
              <div className="grid grid-cols-3 gap-3 mb-2">
                <div className="rounded border p-2 text-center">
                  <p className="text-xs text-muted-foreground">人均创收中位数</p>
                  <p className="text-sm font-bold">{formatCurrency(result.ruleEngine.standards.revenue_per_emp)}</p>
                </div>
                <div className="rounded border p-2 text-center">
                  <p className="text-xs text-muted-foreground">工时产能中位数</p>
                  <p className="text-sm font-bold">{result.ruleEngine.standards.revenue_per_hour}元/h</p>
                </div>
                <div className="rounded border p-2 text-center">
                  <p className="text-xs text-muted-foreground">人力成本率中位数</p>
                  <p className="text-sm font-bold">{result.ruleEngine.standards.wage_ratio}%</p>
                </div>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-xs">
                  <thead>
                    <tr className="border-b text-muted-foreground">
                      <th className="text-left py-1 px-2">岗位</th>
                      <th className="text-right py-1 px-2">占比标准</th>
                      <th className="text-right py-1 px-2">均薪</th>
                      <th className="text-right py-1 px-2">出勤标准</th>
                      <th className="text-right py-1 px-2">工时标准</th>
                      <th className="text-right py-1 px-2">最低出勤</th>
                      <th className="text-right py-1 px-2">最大人数</th>
                    </tr>
                  </thead>
                  <tbody>
                    {Object.entries(result.ruleEngine.standards.roles || {}).map(([role, s]: [string, any]) => (
                      <tr key={role} className="border-b">
                        <td className="py-1 px-2 font-medium">{role}</td>
                        <td className="text-right py-1 px-2">{s.role_ratio}%</td>
                        <td className="text-right py-1 px-2">{formatCurrency(s.normal_pay)}</td>
                        <td className="text-right py-1 px-2">{s.normal_attend}天</td>
                        <td className="text-right py-1 px-2">{s.normal_hours}h</td>
                        <td className="text-right py-1 px-2">{s.min_attend}天</td>
                        <td className="text-right py-1 px-2">{s.max_count}人</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* 决策逻辑 */}
            <div>
              <p className="text-xs font-medium text-muted-foreground mb-2">决策逻辑（4步推理）</p>
              <div className="space-y-1">
                {(result.ruleEngine.decisionLogic || []).map((step: any) => (
                  <div key={step.step} className="flex items-start gap-2 text-xs">
                    <span className="font-bold text-primary min-w-[20px]">{step.step}.</span>
                    <div>
                      <span className="font-medium">{step.name}</span>
                      <span className="text-muted-foreground ml-2">{step.desc}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* 优化规则 */}
            <div>
              <p className="text-xs font-medium text-orange-600 mb-2">优化信号规则（R1~R7，触发后抑制所有招聘信号）</p>
              <div className="space-y-1">
                {(result.ruleEngine.optimizationRules || []).map((r: any) => (
                  <div key={r.id} className="flex items-start gap-2 text-xs rounded border border-orange-100 bg-orange-50/30 p-2">
                    <span className="font-bold text-orange-700 min-w-[28px]">{r.id}</span>
                    <div className="flex-1">
                      <span className="font-medium">{r.name}</span>
                      <span className="text-muted-foreground ml-2">{r.condition}</span>
                    </div>
                    <span className="text-orange-600 font-medium min-w-[40px] text-right">+{r.score}分</span>
                  </div>
                ))}
              </div>
            </div>

            {/* 招聘规则 */}
            <div>
              <p className="text-xs font-medium text-red-600 mb-2">招聘信号规则（R8~R14，仅无优化信号时触发）</p>
              <div className="space-y-1">
                {(result.ruleEngine.hireRules || []).map((r: any) => (
                  <div key={r.id} className="flex items-start gap-2 text-xs rounded border border-red-100 bg-red-50/30 p-2">
                    <span className="font-bold text-red-700 min-w-[28px]">{r.id}</span>
                    <div className="flex-1">
                      <span className="font-medium">{r.name}</span>
                      <span className="text-muted-foreground ml-2">{r.condition}</span>
                      {r.constraint && <span className="text-muted-foreground ml-1">（{r.constraint}）</span>}
                    </div>
                    <span className="text-red-600 font-medium min-w-[40px] text-right">+{r.score}分</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* 筛选排序 */}
      <div className="flex gap-2 flex-wrap items-center">
        <SearchSelect
          value={storeFilter}
          onChange={(v) => { setStoreFilter(v); setPage(1) }}
          options={storeNames}
          emptyLabel="全部门店"
          className="min-w-[140px]"
        />
        <SearchSelect
          value={actionFilter}
          onChange={(v) => { setActionFilter(v); setPage(1) }}
          options={['建议招聘', '建议优化', '关注', '维持']}
          emptyLabel="全部动作"
          className="min-w-[120px]"
        />
        <span className="mx-2 text-muted-foreground">|</span>
        {sorts.map(s => (
          <button key={s.key} onClick={() => { setSort(s.key); setPage(1) }} className={`px-3 py-1 rounded text-xs ${sort === s.key ? 'bg-primary text-primary-foreground' : 'bg-muted'}`}>按{s.label}</button>
        ))}
        <span className="mx-2 text-muted-foreground">|</span>
        <button onClick={() => { setOrder(order === 'asc' ? 'desc' : 'asc'); setPage(1) }} className="px-3 py-1 rounded text-xs bg-muted">
          {order === 'asc' ? '↑ 升序' : '↓ 降序'}
        </button>
      </div>

      {/* 预测表格 */}
      <div className="overflow-x-auto rounded-lg border">
        <table className="w-full text-sm">
          <thead className="bg-muted/50">
            <tr>
              <th className="px-3 py-2 font-medium text-muted-foreground whitespace-nowrap text-left">门店</th>
              <th className="px-3 py-2 font-medium text-muted-foreground whitespace-nowrap text-left">岗位</th>
              <th className="px-3 py-2 font-medium text-muted-foreground whitespace-nowrap text-left">建议动作</th>
              <th className="px-3 py-2 font-medium text-muted-foreground whitespace-nowrap text-right">紧急度</th>
              <th className="px-3 py-2 font-medium text-muted-foreground whitespace-nowrap text-right">人数</th>
              <th className="px-3 py-2 font-medium text-muted-foreground whitespace-nowrap text-right">人均创收</th>
              <th className="px-3 py-2 font-medium text-muted-foreground whitespace-nowrap text-right">工时产能</th>
              <th className="px-3 py-2 font-medium text-muted-foreground whitespace-nowrap text-right">人力成本率</th>
              <th className="px-3 py-2 font-medium text-muted-foreground whitespace-nowrap text-right">岗位占比</th>
              <th className="px-3 py-2 font-medium text-muted-foreground whitespace-nowrap text-right">离职率</th>
            </tr>
          </thead>
          <tbody>
            {paged.length === 0 ? (
              <tr><td colSpan={10} className="px-3 py-8 text-center text-muted-foreground">暂无数据</td></tr>
            ) : paged.map((r, i) => {
              const key = rowKey(r)
              const isExpanded = expandedRow === key
              return (
                <Fragment key={i}>
                  <tr
                    key={i}
                    onClick={() => setExpandedRow(isExpanded ? null : key)}
                    className={`border-t hover:bg-muted/30 cursor-pointer ${LEVEL_ROW_STYLES[r.action_level] || ''}`}
                  >
                    <td className="px-3 py-2 whitespace-nowrap">{r.store_name}</td>
                    <td className="px-3 py-2 whitespace-nowrap font-medium">{r.role}</td>
                    <td className="px-3 py-2 whitespace-nowrap">
                      <span className={`px-2 py-0.5 rounded text-xs font-medium ${ACTION_STYLES[r.action] || ''}`}>{r.action}</span>
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap text-right">
                      <span className={r.urgency >= 70 ? 'text-red-600 font-bold' : r.urgency >= 40 ? 'text-orange-600 font-medium' : 'text-yellow-600'}>{r.urgency}%</span>
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap text-right">{formatNumber(r.emp_count)}</td>
                    <td className="px-3 py-2 whitespace-nowrap text-right">
                      <span className={r.revenue_per_emp > 0 && r.revenue_per_emp < 15000 ? 'text-red-600' : ''}>{r.revenue_per_emp > 0 ? formatCurrency(r.revenue_per_emp) : '-'}</span>
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap text-right">
                      <span className={r.revenue_per_hour > 0 && r.revenue_per_hour < 200 ? 'text-red-600' : ''}>{r.revenue_per_hour > 0 ? `${r.revenue_per_hour}元/h` : '-'}</span>
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap text-right">
                      <span className={r.wage_ratio > 30 ? 'text-orange-600' : ''}>{r.wage_ratio > 0 ? `${r.wage_ratio}%` : '-'}</span>
                    </td>
                    <td className="px-3 py-2 whitespace-nowrap text-right">{r.role_emp_ratio > 0 ? `${r.role_emp_ratio}%` : '-'}</td>
                    <td className="px-3 py-2 whitespace-nowrap text-right"><span className={r.turnover_pct > 0 ? 'text-red-600' : ''}>{r.turnover_pct > 0 ? `${r.turnover_pct}%` : '-'}</span></td>
                  </tr>
                  {isExpanded && (
                    <tr key={`${i}-detail`} className="border-t bg-muted/20">
                      <td colSpan={10} className="px-4 py-3">
                        <div className="space-y-3">
                          {r.analysis && (
                            <div className="flex items-start gap-2">
                              <span className="text-xs font-medium text-blue-600 whitespace-nowrap mt-0.5">AI分析：</span>
                              <span className="text-sm">{r.analysis}</span>
                            </div>
                          )}
                          {r.hire_reasons && (
                            <div className="flex items-start gap-2">
                              <span className="text-xs font-medium text-red-600 whitespace-nowrap mt-0.5">招聘依据：</span>
                              <span className="text-sm">{r.hire_reasons || '无'}</span>
                            </div>
                          )}
                          {r.optimize_reasons && (
                            <div className="flex items-start gap-2">
                              <span className="text-xs font-medium text-orange-600 whitespace-nowrap mt-0.5">优化依据：</span>
                              <span className="text-sm">{r.optimize_reasons || '无'}</span>
                            </div>
                          )}
                          <div className="border-t pt-2">
                            <p className="text-xs font-medium text-muted-foreground mb-2">产能指标对比（实际 vs 标准）</p>
                            <div className="grid grid-cols-5 gap-3">
                              <div className="rounded border p-2">
                                <p className="text-xs text-muted-foreground">人均创收</p>
                                <p className="text-sm font-medium">{r.revenue_per_emp > 0 ? formatCurrency(r.revenue_per_emp) : '-'} <span className="text-xs text-muted-foreground">/ 中位{formatCurrency(r.standards?.revenue_per_emp ?? 15000)}</span></p>
                              </div>
                              <div className="rounded border p-2">
                                <p className="text-xs text-muted-foreground">工时产能</p>
                                <p className="text-sm font-medium">{r.revenue_per_hour > 0 ? `${r.revenue_per_hour}元/h` : '-'} <span className="text-xs text-muted-foreground">/ 中位{r.standards?.revenue_per_hour ?? 200}元/h</span></p>
                              </div>
                              <div className="rounded border p-2">
                                <p className="text-xs text-muted-foreground">人力成本率</p>
                                <p className="text-sm font-medium">{r.wage_ratio > 0 ? `${r.wage_ratio}%` : '-'} <span className="text-xs text-muted-foreground">/ 中位{r.standards?.wage_ratio ?? 30}%</span></p>
                              </div>
                              <div className="rounded border p-2">
                                <p className="text-xs text-muted-foreground">岗位占比</p>
                                <p className="text-sm font-medium">{r.role_emp_ratio > 0 ? `${r.role_emp_ratio}%` : '-'} <span className="text-xs text-muted-foreground">/ 标准{r.standards?.expected_role_ratio ?? '-'}%</span></p>
                              </div>
                              <div className="rounded border p-2">
                                <p className="text-xs text-muted-foreground">出勤/工时</p>
                                <p className="text-sm font-medium">{r.avg_attend > 0 ? `${r.avg_attend}天/${r.avg_hours}h` : '-'} <span className="text-xs text-muted-foreground">/ 标准{r.standards?.normal_attend ?? 20}天/{r.standards?.normal_hours ?? 160}h</span></p>
                              </div>
                            </div>
                          </div>
                          <div className="grid grid-cols-4 gap-3 border-t pt-2">
                            <div>
                              <p className="text-xs text-muted-foreground">在职人数</p>
                              <p className="text-sm font-medium">{r.active_count ?? r.emp_count}人</p>
                            </div>
                            <div>
                              <p className="text-xs text-muted-foreground">当月离职/入职</p>
                              <p className="text-sm font-medium"><span className="text-red-600">{r.left_count}</span> / <span className="text-blue-500">{r.new_count}</span></p>
                            </div>
                            <div>
                              <p className="text-xs text-muted-foreground">岗位月薪资</p>
                              <p className="text-sm font-medium">{formatCurrency(r.total_pay ?? r.avg_pay * r.emp_count)}</p>
                            </div>
                            <div>
                              <p className="text-xs text-muted-foreground">均薪/月</p>
                              <p className="text-sm font-medium">{formatCurrency(r.avg_pay)} <span className="text-xs text-muted-foreground">/ 均值{formatCurrency(r.standards?.normal_pay ?? 0)}</span></p>
                            </div>
                          </div>
                          {r.suggestion && (
                            <div className="pt-2 border-t">
                              <p className="text-xs font-medium text-muted-foreground mb-1">AI建议：</p>
                              <p className="text-sm">{r.suggestion}</p>
                            </div>
                          )}
                        </div>
                      </td>
                    </tr>
                  )}
                </Fragment>
              )
            })}
          </tbody>
        </table>
      </div>
      <Pagination page={page} pageSize={PAGE_SIZE} total={total} onPageChange={setPage} />
    </div>
  )
}
