/**
 * 统一风险中心 — 汇总展示合同风险、薪酬风险、社保风险、合规风险
 * 按风险等级分类，支持快速跳转处理
 */
import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Link, useSearchParams } from 'react-router-dom'
import {
  ShieldAlert, AlertTriangle, Clock, Users, FileText,
  TrendingDown, Calendar, ChevronRight, Filter, CheckSquare,
} from 'lucide-react'
import Card from '../../components/ui/Card'
import { InlineAlert } from '../../components/ui/InlineAlert'
import PageGuide from '../../components/ui/PageGuide'
import QueryError from '../../components/ui/QueryError'
import Pagination from '../../components/ui/Pagination'
import { usePageSize } from '../../hooks/usePageSize'
import { dashboardApi } from '../../lib/api-services'

/** 风险等级配置 */
const RISK_LEVELS: Record<string, { label: string; color: string; bg: string }> = {
  HIGH: { label: '高风险', color: 'text-rose-600', bg: 'bg-rose-50 border-rose-200' },
  MEDIUM: { label: '中风险', color: 'text-amber-600', bg: 'bg-amber-50 border-amber-200' },
  LOW: { label: '低风险', color: 'text-blue-600', bg: 'bg-blue-50 border-blue-200' },
}

/** 风险类型配置 */
const RISK_TYPES: Record<string, { label: string; icon: typeof ShieldAlert; link: string; extraParams?: string }> = {
  CONTRACT: { label: '合同风险', icon: FileText, link: '/roster', extraParams: 'contractStatus=expired' },
  SALARY: { label: '薪酬风险', icon: TrendingDown, link: '/money' },
  TERMINATION: { label: '解聘风险', icon: Users, link: '/termination' },
  MONTHLY: { label: '月度任务', icon: Calendar, link: '/money' },
  ONBOARDING: { label: '入职手续', icon: Clock, link: '/roster' },
  RETIREMENT: { label: '退休提醒', icon: ShieldAlert, link: '/roster' },
}

export default function RiskCenter() {
  const [filterLevel, setFilterLevel] = useState<string>('ALL')
  const [filterType, setFilterType] = useState<string>('ALL')
  const pageSize = usePageSize()
  const [page, setPage] = useState(1)
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [showBatch, setShowBatch] = useState(false)

  /** 获取风险列表 */
  const { data: risks = [], isLoading, isError, error, refetch } = useQuery<any[]>({
    queryKey: ['risk-center'],
    queryFn: async () => {
      return await dashboardApi.risks()
    },
  })

  /** 按级别统计 */
  const stats = useMemo(() => {
    const high = risks.filter((r: any) => r.level === 'HIGH').length
    const medium = risks.filter((r: any) => r.level === 'MEDIUM').length
    const low = risks.filter((r: any) => r.level === 'LOW').length
    return { high, medium, low, total: risks.length }
  }, [risks])

  /** 按类型统计 */
  const typeStats = useMemo(() => {
    const map: Record<string, number> = {}
    risks.forEach((r: any) => {
      map[r.type] = (map[r.type] || 0) + 1
    })
    return map
  }, [risks])

  /** 筛选后的风险列表 */
  const filteredRisks = useMemo(() => {
    return risks.filter((r: any) => {
      if (filterLevel !== 'ALL' && r.level !== filterLevel) return false
      if (filterType !== 'ALL' && r.type !== filterType) return false
      return true
    })
  }, [risks, filterLevel, filterType])

  /** 构建带筛选参数的跳转链接 */
  const buildLink = (r: any) => {
    const typeCfg = RISK_TYPES[r.type] || { link: '/', extraParams: '' }
    const params: string[] = []
    if (r.employee) params.push(`employee=${encodeURIComponent(r.employee.name)}`)
    if (typeCfg.extraParams) params.push(typeCfg.extraParams)
    return params.length > 0 ? `${typeCfg.link}?${params.join('&')}` : typeCfg.link
  }

  const toggleSelect = (id: string) => {
    setSelectedIds(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }

  const toggleSelectAll = () => {
    if (selectedIds.size === pagedRisks.length) {
      setSelectedIds(new Set())
    } else {
      setSelectedIds(new Set(pagedRisks.map((r: any, i: number) => `${r.type}-${i}`)))
    }
  }

  const total = filteredRisks.length
  const pagedRisks = filteredRisks.slice((page - 1) * pageSize, page * pageSize)

  return (
    <div className="space-y-4">
      <PageGuide>
        统一风险中心汇总展示合同到期、薪酬异常、社保漏缴、合规风险等各类人力资源风险。按风险等级（高/中/低）分类展示，支持筛选和快速跳转处理。建议定期查看以及时发现和处置风险。
      </PageGuide>
      {/* 页头 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <ShieldAlert className="h-5 w-5 text-primary" />
          <div>
            <h1 className="text-base font-semibold">统一风险中心</h1>
            <p className="mt-0.5 text-sm text-gray-500">汇总合同、薪酬、社保、合规风险</p>
          </div>
        </div>
      </div>

      {/* 风险概览卡片 */}
      <div className="grid grid-cols-4 gap-3">
        <Card className="p-3">
          <div className="text-xs text-gray-400">总风险</div>
          <div className="text-2xl font-bold text-gray-900 mt-1">{stats.total}</div>
        </Card>
        <Card className="p-3">
          <div className="text-xs text-gray-400">高风险</div>
          <div className="text-2xl font-bold text-rose-600 mt-1">{stats.high}</div>
        </Card>
        <Card className="p-3">
          <div className="text-xs text-gray-400">中风险</div>
          <div className="text-2xl font-bold text-amber-600 mt-1">{stats.medium}</div>
        </Card>
        <Card className="p-3">
          <div className="text-xs text-gray-400">低风险</div>
          <div className="text-2xl font-bold text-blue-600 mt-1">{stats.low}</div>
        </Card>
      </div>

      {/* 高风险告警 */}
      {stats.high > 0 && (
        <InlineAlert type="error">
          当前有 {stats.high} 项高风险事项需要立即处理，请尽快跟进。
        </InlineAlert>
      )}

      {/* 风险类型分布 */}
      <Card>
        <h2 className="text-sm font-medium mb-3">风险类型分布</h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
          {Object.entries(RISK_TYPES).map(([key, cfg]) => {
            const count = typeStats[key] || 0
            if (count === 0) return null
            const Icon = cfg.icon
            return (
              <Link
                key={key}
                to={cfg.extraParams ? `${cfg.link}?${cfg.extraParams}` : cfg.link}
                className="flex items-center gap-2 p-2.5 rounded-lg border border-gray-100 hover:border-primary/30 hover:bg-primary/5 transition-colors"
              >
                <Icon className="w-4 h-4 text-gray-400" />
                <div className="flex-1 min-w-0">
                  <div className="text-xs text-gray-600 truncate">{cfg.label}</div>
                  <div className="text-sm font-bold text-gray-900">{count}</div>
                </div>
                <ChevronRight className="w-3 h-3 text-gray-300" />
              </Link>
            )
          })}
          {Object.values(typeStats).every((v) => v === 0) && (
            <div className="col-span-full text-center py-4 text-sm text-gray-400">暂无风险项</div>
          )}
        </div>
      </Card>

      {/* 筛选器 */}
      <div className="flex items-center gap-3 flex-wrap">
        <div className="flex items-center gap-1 text-sm text-gray-400">
          <Filter className="w-4 h-4" />
          筛选
        </div>
        <div className="flex gap-1">
          <button
            className={`px-3 py-1 rounded-md text-xs transition-colors ${filterLevel === 'ALL' ? 'bg-primary text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
            onClick={() => setFilterLevel('ALL')}
          >全部</button>
          {Object.entries(RISK_LEVELS).map(([key, cfg]) => (
            <button
              key={key}
              className={`px-3 py-1 rounded-md text-xs transition-colors ${filterLevel === key ? 'bg-primary text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
              onClick={() => setFilterLevel(key)}
            >{cfg.label}</button>
          ))}
        </div>
        <div className="flex gap-1 ml-2">
          <button
            className={`px-3 py-1 rounded-md text-xs transition-colors ${filterType === 'ALL' ? 'bg-primary text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
            onClick={() => setFilterType('ALL')}
          >全部类型</button>
          {Object.entries(RISK_TYPES).map(([key, cfg]) => (
            <button
              key={key}
              className={`px-3 py-1 rounded-md text-xs transition-colors ${filterType === key ? 'bg-primary text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
              onClick={() => setFilterType(key)}
            >{cfg.label}</button>
          ))}
        </div>
        <button
          className={`px-3 py-1 rounded-md text-xs transition-colors ml-auto flex items-center gap-1 ${showBatch ? 'bg-primary text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
          onClick={() => { setShowBatch(!showBatch); setSelectedIds(new Set()) }}
        >
          <CheckSquare className="w-3.5 h-3.5" />
          {showBatch ? '退出批量' : '批量处理'}
        </button>
      </div>

      {/* 风险列表 */}
      <Card>
        {isLoading ? (
          <div className="text-center py-8 text-gray-400">加载中...</div>
        ) : isError ? (
          <QueryError error={error} onRetry={refetch} />
        ) : filteredRisks.length === 0 ? (
          <div className="text-center py-8 text-gray-400 text-sm">
            {risks.length === 0 ? '暂无风险项，一切正常' : '当前筛选条件下无匹配项'}
          </div>
        ) : (
          <>
          {showBatch && pagedRisks.length > 0 && (
            <div className="flex items-center gap-2 mb-2 px-3 py-2 bg-gray-50 rounded-md">
              <button onClick={toggleSelectAll} className="text-xs text-primary hover:underline">
                {selectedIds.size === pagedRisks.length ? '取消全选' : '全选'}
              </button>
              <span className="text-xs text-gray-500">已选 {selectedIds.size} 项</span>
              {selectedIds.size > 0 && (
                <>
                  <Link to={`/contracts?batch=${encodeURIComponent(Array.from(selectedIds).join(','))}`} className="text-xs text-primary hover:underline ml-2">
                    批量续签
                  </Link>
                  <Link to={`/termination?batch=${encodeURIComponent(Array.from(selectedIds).join(','))}`} className="text-xs text-primary hover:underline">
                    批量离职
                  </Link>
                </>
              )}
            </div>
          )}
          <div className="space-y-2">
            {pagedRisks.map((r: any, i: number) => {
              const levelCfg = RISK_LEVELS[r.level] || RISK_LEVELS.LOW
              const typeCfg = RISK_TYPES[r.type] || { label: r.type, icon: AlertTriangle, link: '/' }
              const Icon = typeCfg.icon
              const link = buildLink(r)
              const itemId = `${r.type}-${i}`
              return (
                <div
                  key={i}
                  className={`flex items-start gap-3 p-3 rounded-lg border ${levelCfg.bg} hover:shadow-sm transition-shadow`}
                >
                  {showBatch && (
                    <input
                      type="checkbox"
                      checked={selectedIds.has(itemId)}
                      onChange={() => toggleSelect(itemId)}
                      className="mt-1 shrink-0"
                    />
                  )}
                  <Link to={link} className="flex items-start gap-3 flex-1 min-w-0">
                    <Icon className={`w-4 h-4 mt-0.5 shrink-0 ${levelCfg.color}`} />
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span className={`text-xs font-medium ${levelCfg.color}`}>{levelCfg.label}</span>
                        <span className="text-xs text-gray-400">{typeCfg.label}</span>
                      </div>
                      <div className="text-sm text-gray-700 mt-0.5">{r.title}</div>
                      {r.description && (
                        <div className="text-xs text-gray-500 mt-0.5">{r.description}</div>
                      )}
                      {r.employee && (
                        <div className="text-xs text-gray-400 mt-0.5">
                          {r.employee.name} · {r.employee.department || ''}
                          {r.employee.idCardNumber && <span className="ml-1 font-mono">{r.employee.idCardNumber}</span>}
                        </div>
                      )}
                    </div>
                    <ChevronRight className="w-4 h-4 text-gray-300 shrink-0 mt-1" />
                  </Link>
                  {r.type === 'CONTRACT_EXPIRY' && (
                    <Link to={`/contracts?employee=${encodeURIComponent(r.employee?.name || '')}`} className="text-xs text-primary hover:underline shrink-0 mt-1">
                      续签
                    </Link>
                  )}
                  {r.type === 'PROBATION_END' && (
                    <Link to={`/work-process?type=REGULAR&employee=${encodeURIComponent(r.employee?.name || '')}`} className="text-xs text-primary hover:underline shrink-0 mt-1">
                      转正
                    </Link>
                  )}
                  {r.type === 'TERMINATION_RISK' && (
                    <Link to={`/termination?employee=${encodeURIComponent(r.employee?.name || '')}`} className="text-xs text-primary hover:underline shrink-0 mt-1">
                      处理
                    </Link>
                  )}
                </div>
              )
            })}
          </div>
          <Pagination page={page} pageSize={pageSize} total={total} onPageChange={setPage} onPageSizeChange={() => setPage(1)} />
          </>
        )}
      </Card>
    </div>
  )
}
