import { useState } from 'react'
import { usePageSize } from '../hooks/usePageSize'
import { useQuery } from '@tanstack/react-query'
import { ShieldCheck, FileText, CheckCircle, XCircle } from 'lucide-react'
import { evidenceApi } from '../lib/api-services'
import Card from '../components/ui/Card'
import EmptyState from '../components/ui/EmptyState'
import Pagination from '../components/ui/Pagination'
import PageGuide from '../components/ui/PageGuide'
import QueryError from '../components/ui/QueryError'

/**
 * 证据链管理页面
 */
export default function Evidence() {
  const [refType, setRefType] = useState<string>('')
  const pageSize = usePageSize()
  const [page, setPage] = useState(1)

  const { data: listData, isLoading, isError, error, refetch } = useQuery<any>({
    queryKey: ['evidence', refType, page, pageSize],
    queryFn: async () => {
      const params: any = { page, pageSize }
      params.category = refType || 'ALL'
      return await evidenceApi.list(params)
    },
  })
  const list = listData?.records || []
  const total = listData?.total || 0

  const { data: verifyResult, refetch: verifyAll } = useQuery<any>({
    queryKey: ['evidence-verify-all'],
    queryFn: async () => {
      return await evidenceApi.verifyAll()
    },
    enabled: false,
  })

  return (
    <div className="space-y-3">
      <PageGuide>
        证据链管理记录系统中所有关键操作的不可篡改证据，用于劳动仲裁举证。支持按关联类型筛选、验证证据完整性。点击「验证全部完整性」可批量校验所有证据是否被篡改。
      </PageGuide>
      <div className="flex items-center justify-between">
        <div>
          <div className="flex items-center gap-2">
            <ShieldCheck className="h-5 w-5 text-primary" />
            <h1 className="text-base font-semibold">证据链管理</h1>
          </div>
          <p className="mt-1 text-sm text-gray-500">不可篡改的操作证据链，用于劳动仲裁举证</p>
        </div>
        <button
          onClick={() => verifyAll()}
          className="px-3 py-1.5 text-sm rounded-lg bg-primary text-white hover:bg-primary/90"
        >
          验证全部完整性
        </button>
      </div>

      {verifyResult && (
        <Card className={verifyResult?.invalid === 0 ? 'border-green-300 bg-green-50' : 'border-red-300 bg-red-50'}>
          <div className="flex items-center gap-2">
            {verifyResult?.invalid === 0 ? (
              <CheckCircle className="w-5 h-5 text-green-600" />
            ) : (
              <XCircle className="w-5 h-5 text-red-600" />
            )}
            <span className="text-sm font-medium">
              {verifyResult?.invalid === 0
                ? `全部 ${verifyResult?.total || 0} 条证据链验证通过，数据完整无篡改${verifyResult?.repaired ? `（自动修复 ${verifyResult.repaired} 条历史数据）` : ''}`
                : `${verifyResult?.valid || 0} 条通过，${verifyResult?.invalid || 0} 条异常，请检查`}
            </span>
          </div>
          {verifyResult?.invalidItems?.length > 0 && (
            <div className="mt-3 space-y-1.5">
              {verifyResult.invalidItems.map((item: any) => (
                <div key={item.id} className="flex items-center justify-between px-3 py-2 rounded bg-red-50 border border-red-200 text-sm">
                  <div className="flex items-center gap-2">
                    <XCircle className="w-4 h-4 text-red-500 shrink-0" />
                    <span className="text-red-700">{item.description}</span>
                  </div>
                  <span className="text-xs text-gray-400">{new Date(item.createdAt).toLocaleString('zh-CN')}</span>
                </div>
              ))}
            </div>
          )}
        </Card>
      )}

      <div className="flex gap-2">
        {['', 'ONBOARD', 'CONTRACT_SIGN', 'PAYSLIP_CONFIRM', 'DISCIPLINARY', 'ATTENDANCE', 'TERMINATION'].map((t) => (
          <button
            key={t}
            onClick={() => { setRefType(t); setPage(1) }}
            className={`px-3 py-1 text-xs rounded-lg ${refType === t ? 'bg-primary text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
          >
            {t === '' ? '全部' : t === 'DISCIPLINARY' ? '违纪' : t === 'TERMINATION' ? '解聘' : t === 'CONTRACT_SIGN' ? '合同' : t === 'PAYSLIP_CONFIRM' ? '薪酬' : t === 'ONBOARD' ? '入职' : '考勤'}
          </button>
        ))}
      </div>

      {isLoading ? (
        <div className="text-center py-8 text-gray-500">加载中...</div>
      ) : isError ? (
        <QueryError error={error} onRetry={refetch} />
      ) : !list || list.length === 0 ? (
        <EmptyState title="暂无证据链记录" description="系统操作将自动生成证据链" />
      ) : (
        <div className="space-y-2">
          {list.map((item: any) => (
            <Card key={item.id} className="hover:shadow-md transition-shadow">
              <div className="flex items-start justify-between">
                <div className="flex items-start gap-2.5 flex-1 min-w-0">
                  <FileText className="w-4 h-4 text-primary mt-0.5 flex-shrink-0" />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-medium truncate">{item.lastAction || item.firstAction || item.category}</span>
                      <span className="px-1.5 py-0.5 rounded text-xs bg-gray-100 text-gray-600">
                        {item.category === 'DISCIPLINARY' ? '违纪' : item.category === 'TERMINATION' ? '解聘' : item.category === 'CONTRACT_SIGN' ? '合同' : item.category === 'PAYSLIP_CONFIRM' ? '薪酬' : item.category === 'ONBOARD' ? '入职' : '考勤'}
                      </span>
                    </div>
                    {item.employeeName && (
                      <div className="text-xs text-gray-500 mt-0.5">
                        员工：{item.employeeName}{item.employeeDept ? ` · ${item.employeeDept}` : ''}{item.employeeIdCardNumber && <span className="ml-1 font-mono text-gray-400">{item.employeeIdCardNumber}</span>}
                      </div>
                    )}
                    <div className="text-xs text-gray-400 mt-0.5 flex items-center gap-2">
                      <span>{item.eventCount} 条事件 · {new Date(item.createdAt).toLocaleString('zh-CN')}</span>
                      {item.hashShort && (
                        <span className="font-mono text-gray-400">SHA: {item.hashShort}…</span>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}
      <Pagination
        page={page}
        pageSize={pageSize}
        total={total}
        onPageChange={setPage}
        onPageSizeChange={() => setPage(1)}
      />
    </div>
  )
}
