import { useQuery } from '@tanstack/react-query'
import api from '@/lib/api'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { FilterableTable } from '@/components/FilterableTable'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { formatCurrency, formatNumber } from '@/lib/utils'

const LEVEL_BG: Record<string, string> = {
  red: 'bg-red-100 text-red-700 border-red-300',
  orange: 'bg-orange-100 text-orange-700 border-orange-300',
  yellow: 'bg-yellow-100 text-yellow-700 border-yellow-300',
}

export function AttendanceAlertTab({ month }: { month: string }) {
  const { data: summaryData, isLoading: summaryLoading } = useQuery({
    queryKey: ['ss/attendance-summary', month],
    queryFn: () => api.get('/smart-scheduling/attendance-summary', { params: { month } }),
  })

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

  const summaryRows = (summaryData as any)?.data || []
  const alertRows = (alertData as any)?.data || []

  const storeNames = [...new Set(summaryRows.map((r: any) => r.store_name))].sort() as string[]

  const redCount = alertRows.filter((r: any) => r.alert_level === 'red').length
  const orangeCount = alertRows.filter((r: any) => r.alert_level === 'orange').length
  const yellowCount = alertRows.filter((r: any) => r.alert_level === 'yellow').length

  if (summaryLoading || alertLoading) return <LoadingSpinner text="加载考勤预警数据..." />

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-3 gap-3">
        <div className="rounded-lg border border-red-300 bg-red-50 p-3">
          <p className="text-xs text-red-600">红色预警（旷工/出勤异常）</p>
          <p className="text-2xl font-bold text-red-700">{redCount}</p>
        </div>
        <div className="rounded-lg border border-orange-300 bg-orange-50 p-3">
          <p className="text-xs text-orange-600">橙色预警（偏差大）</p>
          <p className="text-2xl font-bold text-orange-700">{orangeCount}</p>
        </div>
        <div className="rounded-lg border border-yellow-300 bg-yellow-50 p-3">
          <p className="text-xs text-yellow-600">黄色预警（考勤扣款/出勤率低）</p>
          <p className="text-2xl font-bold text-yellow-700">{yellowCount}</p>
        </div>
      </div>

      <CollapsibleSection title="门店考勤汇总" subtitle="各门店出勤天数、旷工、迟到扣款、低出勤率">
        <FilterableTable
          data={summaryRows}
          sortOptions={[
            { key: 'emp_count', label: '人数' },
            { key: 'avg_attend_days', label: '均出勤天' },
            { key: 'avg_hours', label: '均工时' },
            { key: 'total_absent_days', label: '旷工天数' },
            { key: 'total_late_deduction', label: '迟到扣款' },
            { key: 'low_attendance_rate_pct', label: '低出勤率' },
          ]}
          defaultSort="emp_count"
          defaultOrder="desc"
          filterKey="store_name"
          filterLabel="全部门店"
          columns={[
            { key: 'store_name', label: '门店' },
            { key: 'emp_count', label: '人数', align: 'right', render: (r) => formatNumber(r.emp_count) },
            { key: 'avg_attend_days', label: '均出勤天', align: 'right', render: (r) => r.avg_attend_days },
            { key: 'avg_hours', label: '均工时', align: 'right', render: (r) => formatNumber(r.avg_hours) },
            { key: 'total_absent_days', label: '旷工天数', align: 'right', render: (r) => <span className={parseFloat(r.total_absent_days) > 0 ? 'text-red-600 font-medium' : ''}>{r.total_absent_days || 0}</span> },
            { key: 'absent_emp_count', label: '旷工人数', align: 'right', render: (r) => <span className={parseFloat(r.absent_emp_count) > 0 ? 'text-red-600' : ''}>{r.absent_emp_count || 0}</span> },
            { key: 'total_late_deduction', label: '迟到扣款', align: 'right', render: (r) => formatCurrency(r.total_late_deduction) },
            { key: 'punch_issue_count', label: '打卡异常人数', align: 'right', render: (r) => <span className={parseFloat(r.punch_issue_count) > 5 ? 'text-orange-600' : ''}>{r.punch_issue_count || 0}</span> },
            { key: 'low_attendance_rate_pct', label: '低出勤率%', align: 'right', render: (r) => <span className={parseFloat(r.low_attendance_rate_pct) > 20 ? 'text-red-600 font-medium' : ''}>{r.low_attendance_rate_pct ? r.low_attendance_rate_pct + '%' : '0%'}</span> },
          ]}
        />
      </CollapsibleSection>

      <CollapsibleSection title="考勤异常明细" subtitle="员工级考勤预警列表（按严重程度排序）">
        <FilterableTable
          data={alertRows}
          sortOptions={[
            { key: 'attend_diff', label: '偏差天' },
            { key: 'absent_days', label: '旷工天' },
            { key: 'late_deduction', label: '迟到扣款' },
            { key: 'actual_hours', label: '实际工时' },
          ]}
          defaultSort="attend_diff"
          defaultOrder="desc"
          filterKey="store_name"
          filterLabel="全部门店"
          statusFilterKey="alert_level"
          statusFilterLabel="全部等级"
          statusOptions={[
            { value: 'red', label: '红色' },
            { value: 'orange', label: '橙色' },
            { value: 'yellow', label: '黄色' },
          ]}
          columns={[
            { key: 'store_name', label: '门店' },
            { key: 'employee_code', label: '工号' },
            { key: 'position', label: '岗位' },
            { key: 'salary_attend_days', label: '薪资出勤天', align: 'right', render: (r) => r.salary_attend_days },
            { key: 'expected_attend', label: '应出勤天', align: 'right', render: (r) => r.expected_attend },
            { key: 'attend_diff', label: '偏差天', align: 'right', render: (r) => <span className={parseFloat(r.attend_diff) > 5 ? 'text-red-600 font-medium' : ''}>{r.attend_diff}</span> },
            { key: 'absent_days', label: '旷工天', align: 'right', render: (r) => <span className={parseFloat(r.absent_days) > 0 ? 'text-red-600 font-bold' : ''}>{r.absent_days || 0}</span> },
            { key: 'late_deduction', label: '迟到扣款', align: 'right', render: (r) => formatCurrency(r.late_deduction) },
            { key: 'no_punch_deduction', label: '未打卡扣款', align: 'right', render: (r) => formatCurrency(r.no_punch_deduction) },
            { key: 'actual_hours', label: '实际工时', align: 'right', render: (r) => formatNumber(r.actual_hours) },
            { key: 'alert_type', label: '预警类型', render: (r) => <span className={`px-2 py-0.5 rounded text-xs border ${LEVEL_BG[r.alert_level] || ''}`}>{r.alert_type}</span> },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
