import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Loader2, CalendarCheck, Clock, LogIn, LogOut, CalendarDays, Clock3 } from 'lucide-react'
import { portalApi } from '../../lib/api-services'

/** 考勤状态中文映射 */
const statusMap: Record<string, { label: string; color: string; dot: string }> = {
  NORMAL:   { label: '正常',   color: 'bg-green-50 text-safe',         dot: 'bg-safe' },
  LATE:     { label: '迟到',   color: 'bg-amber-50 text-amber-700',    dot: 'bg-amber-500' },
  EARLY:    { label: '早退',   color: 'bg-orange-50 text-orange-700',  dot: 'bg-orange-500' },
  ABSENT:   { label: '缺勤',   color: 'bg-red-50 text-red-700',        dot: 'bg-red-500' },
  LEAVE:    { label: '请假',   color: 'bg-blue-50 text-blue-700',      dot: 'bg-blue-500' },
  BUSINESS: { label: '出差',   color: 'bg-purple-50 text-purple-700',  dot: 'bg-purple-500' },
  WEEKEND:  { label: '休息',   color: 'bg-gray-50 text-gray-400',      dot: 'bg-gray-300' },
}

/** 根据日期类型和打卡状态，返回更准确的状态标签 */
function getDisplayStatus(record: any) {
  const baseStatus = record.status || 'UNKNOWN'
  const dateType = record.dateType // weekday / weekend / holiday
  const hasCheckIn = !!record.checkInTime

  // 有打卡记录的周末/节假日，状态改为"周末出勤"/"节假日出勤"
  if (hasCheckIn && baseStatus === 'NORMAL') {
    if (dateType === 'holiday') {
      return { label: '节假日出勤', color: 'bg-red-50 text-red-600', dot: 'bg-red-500' }
    }
    if (dateType === 'weekend') {
      return { label: '周末出勤', color: 'bg-amber-50 text-amber-600', dot: 'bg-amber-500' }
    }
  }

  // 无打卡的周末/节假日，显示"休息"
  if (!hasCheckIn && (dateType === 'weekend' || dateType === 'holiday')) {
    return { label: '休息', color: 'bg-gray-50 text-gray-400', dot: 'bg-gray-300' }
  }

  return statusMap[baseStatus] || { label: record.statusText || baseStatus || '未知', color: 'bg-gray-50 text-gray-600', dot: 'bg-gray-300' }
}

const weekdayMap = ['日', '一', '二', '三', '四', '五', '六']

/** 格式化时间：直接从 ISO 字符串提取 HH:mm，避免时区转换 */
function fmtTime(t: string): string {
  if (!t) return ''
  // 格式：2026-08-17T08:50:00.000Z → 08:50
  const m = t.match(/T(\d{2}):(\d{2})/)
  if (m) return `${m[1]}:${m[2]}`
  return t
}

/** 格式化日期：X月X日 周X（直接从字符串提取，避免时区转换） */
function fmtDate(d: string): { date: string; weekday: string; isWeekend: boolean } {
  try {
    const m = d.match(/(\d{4})-(\d{2})-(\d{2})/)
    if (m) {
      const month = parseInt(m[2])
      const day = parseInt(m[3])
      const dt = new Date(parseInt(m[1]), month - 1, day)
      return {
        date: `${month}月${day}日`,
        weekday: `周${weekdayMap[dt.getDay()]}`,
        isWeekend: dt.getDay() === 0 || dt.getDay() === 6,
      }
    }
  } catch {}
  return { date: d, weekday: '', isWeekend: false }
}

export default function MyAttendance() {
  const [month, setMonth] = useState(new Date().toISOString().slice(0, 7))

  const { data, isLoading } = useQuery({
    queryKey: ['portal-attendance', month],
    queryFn: async () => {
      return await portalApi.attendance(month)
    },
  })

  const records = data?.records || []
  const published = data?.published || false

  // 生成月份列表（最近6个月）
  const months: string[] = []
  const now = new Date()
  for (let i = 0; i < 6; i++) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1)
    months.push(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`)
  }

  // 统计（按显示状态归类）
  const stats = records.reduce((acc: Record<string, { count: number; label: string; color: string; dot: string }>, r: any) => {
    const cfg = getDisplayStatus(r)
    if (!acc[cfg.label]) {
      acc[cfg.label] = { count: 0, label: cfg.label, color: cfg.color, dot: cfg.dot }
    }
    acc[cfg.label].count++
    return acc
  }, {})

  return (
    <div className="space-y-4">
      {/* 页面标题 */}
      <div className="flex items-center gap-2">
        <CalendarCheck className="w-5 h-5 text-primary" />
        <h1 className="text-base font-bold">我的考勤</h1>
      </div>

      {/* 月份选择 — 胶囊式 */}
      <div className="flex gap-2 overflow-x-auto pb-1 scrollbar-hide">
        {months.map(m => (
          <button
            key={m}
            onClick={() => setMonth(m)}
            className={`px-3.5 py-1.5 rounded-full text-xs whitespace-nowrap transition-all ${
              month === m
                ? 'bg-primary text-white font-medium shadow-sm'
                : 'bg-white border border-gray-200 text-gray-500 hover:bg-gray-50'
            }`}
          >
            {m}
          </button>
        ))}
      </div>

      {isLoading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-6 h-6 animate-spin text-gray-400" />
        </div>
      ) : !published ? (
        <div className="bg-white rounded-2xl p-8 text-center border border-gray-100">
          <CalendarDays className="w-10 h-10 text-gray-300 mx-auto mb-2" />
          <p className="text-sm text-gray-400">{month} 月考勤表尚未发布</p>
        </div>
      ) : records.length === 0 ? (
        <div className="bg-white rounded-2xl p-8 text-center border border-gray-100">
          <CalendarDays className="w-10 h-10 text-gray-300 mx-auto mb-2" />
          <p className="text-sm text-gray-400">暂无考勤记录</p>
        </div>
      ) : (
        <>
          {/* 统计概览 */}
          <div className="flex gap-2 flex-wrap">
            {Object.entries(stats).map(([label, info]: [string, any]) => {
              return (
                <div key={label} className={`flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs ${info.color}`}>
                  <span className={`w-1.5 h-1.5 rounded-full ${info.dot}`} />
                  {info.label} {info.count}
                </div>
              )
            })}
            {(() => {
              const totalOt = records.reduce((sum: number, r: any) => sum + (r.overtimeHours || 0), 0)
              if (totalOt <= 0) return null
              return (
                <div className="flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs bg-orange-50 text-orange-600">
                  <Clock3 className="w-3.5 h-3.5" />
                  加班 {totalOt}h
                </div>
              )
            })()}
          </div>

          {/* 考勤列表 — 卡片式时间线 */}
          <div className="bg-white rounded-2xl overflow-hidden border border-gray-100">
            <div className="px-4 py-3 border-b border-gray-100">
              <h2 className="text-sm font-semibold text-gray-900">{data?.title || `${month}月考勤表`}</h2>
            </div>
            <div className="divide-y divide-gray-50">
              {records.map((record: any) => {
                const { date, weekday, isWeekend } = fmtDate(record.date)
                const cfg = getDisplayStatus(record)
                const hasOvertime = record.hasOvertime || (record.overtimeHours || 0) > 0
                const otHours = record.overtimeHours || 0
                const otRate = record.overtimeRate || 0
                const dateTypeLabel = record.dateType === 'holiday' ? '法定节假日' : record.dateType === 'weekend' ? '休息日' : '工作日'
                const dateTypeColor = record.dateType === 'holiday' ? 'text-red-500' : record.dateType === 'weekend' ? 'text-amber-600' : 'text-gray-400'
                return (
                  <div key={record.id} className="flex items-center gap-3 px-4 py-3 hover:bg-gray-25 transition-colors">
                    {/* 日期 */}
                    <div className={`flex-shrink-0 w-16 text-center ${isWeekend ? 'text-gray-400' : 'text-gray-700'}`}>
                      <div className="text-sm font-medium">{date}</div>
                      <div className="text-xs text-gray-400">{weekday}</div>
                    </div>
                    {/* 分割线 */}
                    <div className="w-px h-8 bg-gray-100 flex-shrink-0" />
                    {/* 打卡时间 + 加班 */}
                    <div className="flex-1 min-w-0 space-y-1">
                      <div className="flex items-center gap-1.5 text-xs">
                        <LogIn className="w-3.5 h-3.5 text-gray-400 flex-shrink-0" />
                        <span className="text-gray-500">上班</span>
                        <span className={`font-mono ${record.checkInTime ? 'text-gray-700' : 'text-gray-300'}`}>
                          {record.checkInTime ? fmtTime(record.checkInTime) : '未打卡'}
                        </span>
                      </div>
                      <div className="flex items-center gap-1.5 text-xs">
                        <LogOut className="w-3.5 h-3.5 text-gray-400 flex-shrink-0" />
                        <span className="text-gray-500">下班</span>
                        <span className={`font-mono ${record.checkOutTime ? 'text-gray-700' : 'text-gray-300'}`}>
                          {record.checkOutTime ? fmtTime(record.checkOutTime) : '未打卡'}
                        </span>
                      </div>
                      {hasOvertime && (
                        <div className="flex items-center gap-1.5 text-xs pt-0.5">
                          <Clock3 className="w-3.5 h-3.5 text-orange-500 flex-shrink-0" />
                          <span className="text-gray-500">加班</span>
                          <span className="font-mono text-orange-600 font-medium">{otHours}h</span>
                          <span className="text-gray-300">·</span>
                          <span className={dateTypeColor}>{dateTypeLabel}</span>
                          <span className="text-gray-300">·</span>
                          <span className="text-orange-500">{otRate}倍</span>
                        </div>
                      )}
                    </div>
                    {/* 状态标签 */}
                    <div className="flex flex-col items-end gap-1 flex-shrink-0">
                      <span className={`text-xs px-2 py-1 rounded-full font-medium ${cfg.color}`}>
                        {cfg.label}
                      </span>
                      {hasOvertime && (
                        <span className="text-xs px-2 py-0.5 rounded-full bg-orange-50 text-orange-600 font-medium">
                          +{otHours}h
                        </span>
                      )}
                    </div>
                  </div>
                )
              })}
            </div>
          </div>
        </>
      )}
    </div>
  )
}
