/**
 * 用工体检诊断页面
 * 6 维度深度诊断 + 历史报告
 */

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { Stethoscope, Save, History, CheckCircle2, AlertCircle, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react'
import { RadialBarChart, RadialBar, PolarAngleAxis, ResponsiveContainer } from 'recharts'
import { dashboardApi } from '../../lib/api-services'
import Card from '../../components/ui/Card'
import Button from '../../components/ui/Button'
import PageGuide from '../../components/ui/PageGuide'

/**
 * 用工体检诊断页面
 */
export default function HealthCheck() {
  const queryClient = useQueryClient()
  const [showHistory, setShowHistory] = useState(false)
  const [expandedDim, setExpandedDim] = useState<string | null>(null)

  const { data: healthCheck, isLoading } = useQuery<any>({
    queryKey: ['health-check'],
    queryFn: async () => {
      return await dashboardApi.healthCheck()
    },
  })

  const { data: history } = useQuery<any>({
    queryKey: ['health-check-history'],
    queryFn: async () => {
      return await dashboardApi.healthCheckHistory()
    },
    enabled: showHistory,
  })

  const saveMutation = useMutation({
    mutationFn: async () => {
      return await dashboardApi.healthCheckSave()
    },
    onSuccess: () => {
      toast.success('诊断报告已保存')
      queryClient.invalidateQueries({ queryKey: ['health-check-history'] })
    },
    onError: () => toast.error('保存失败'),
  })

  if (isLoading) {
    return <div className="text-center py-8 text-gray-500">加载中...</div>
  }

  if (!healthCheck) return null

  const levelConfig: Record<string, { color: string; bg: string; text: string; icon: typeof CheckCircle2; label: string }> = {
    safe: { color: '#16A34A', bg: 'bg-green-50', text: 'text-safe', icon: CheckCircle2, label: '健康' },
    warning: { color: '#D97706', bg: 'bg-amber-50', text: 'text-warning', icon: AlertCircle, label: '中等风险' },
    danger: { color: '#C00000', bg: 'bg-red-50', text: 'text-danger', icon: AlertTriangle, label: '高风险' },
  }
  const level = levelConfig[healthCheck.level] || levelConfig.warning
  const LevelIcon = level.icon

  return (
    <div className="space-y-3">
      <PageGuide>用工健康检查，评估当前用工合规状况，包括合同签订率、社保覆盖率、试用期合规等关键指标。支持生成检查报告和整改建议。</PageGuide>
      <div className="flex items-center justify-between">
        <div>
          <div className="flex items-center gap-2">
            <Stethoscope className="h-5 w-5 text-primary" />
            <h1 className="text-base font-semibold">用工体检诊断</h1>
          </div>
          <p className="mt-1 text-sm text-gray-500">{healthCheck.year} 年度 · 6 维度深度诊断</p>
        </div>
        <div className="flex gap-2">
          <Button variant="secondary" size="sm" onClick={() => setShowHistory(!showHistory)}>
            <History className="w-4 h-4 mr-1" />
            {showHistory ? '收起历史' : '历史报告'}
          </Button>
          <Button size="sm" onClick={() => saveMutation.mutate()} disabled={saveMutation.isPending}>
            <Save className="w-4 h-4 mr-1" />
            保存报告
          </Button>
        </div>
      </div>

      {/* 评分标准说明 */}
      <Card>
        <div className="space-y-2">
          <div className="flex items-center gap-1.5 text-sm font-medium">
            <Stethoscope className="w-4 h-4 text-primary" />
            评分标准说明
          </div>
          <div className="grid grid-cols-3 gap-2 text-xs">
            <div className="flex items-center gap-1.5">
              <CheckCircle2 className="w-3.5 h-3.5 text-safe" />
              <div>
                <div className="font-medium text-safe">85 分以上 · 健康</div>
                <div className="text-gray-500">用工管理规范，风险低</div>
              </div>
            </div>
            <div className="flex items-center gap-1.5">
              <AlertCircle className="w-3.5 h-3.5 text-warning" />
              <div>
                <div className="font-medium text-warning">60-84 分 · 中等风险</div>
                <div className="text-gray-500">存在部分合规隐患</div>
              </div>
            </div>
            <div className="flex items-center gap-1.5">
              <AlertTriangle className="w-3.5 h-3.5 text-danger" />
              <div>
                <div className="font-medium text-danger">60 分以下 · 高风险</div>
                <div className="text-gray-500">需立即整改</div>
              </div>
            </div>
          </div>
          <div className="border-t pt-2 text-xs text-gray-500 space-y-1">
            <div className="font-medium text-gray-600">6 维度评分构成：</div>
            <div>- <b>合同管理</b>：合同签订率、到期预警、试用期合规</div>
            <div>- <b>薪酬社保</b>：社保覆盖率、公积金缴纳、薪资合规</div>
            <div>- <b>考勤加班</b>：加班时长合规、考勤记录完整性</div>
            <div>- <b>规章制度</b>：制度公示、民主程序、员工知情</div>
            <div>- <b>解聘合规</b>：解除程序合法、补偿计算准确</div>
            <div>- <b>证据链</b>：证据完整性、仲裁可追溯性</div>
          </div>
        </div>
      </Card>

      {/* 总评分 */}
      <Card className={level.bg}>
        <div className="flex items-center gap-4">
          <div className="relative w-28 h-28 shrink-0">
            <ResponsiveContainer width="100%" height="100%">
              <RadialBarChart
                innerRadius="70%"
                outerRadius="100%"
                data={[{ value: healthCheck.totalScore, fill: level.color }]}
                startAngle={90}
                endAngle={-270}
              >
                <PolarAngleAxis type="number" domain={[0, 100]} tick={false} />
                <RadialBar background dataKey="value" cornerRadius={8} />
              </RadialBarChart>
            </ResponsiveContainer>
            <div className="absolute inset-0 flex flex-col items-center justify-center">
              <span className={`text-2xl font-bold ${level.text}`}>{healthCheck.totalScore}</span>
              <span className="text-xs text-gray-500">{level.label}</span>
            </div>
          </div>
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-1">
              <LevelIcon className={`w-4 h-4 ${level.text}`} />
              <span className="text-sm font-medium">诊断总结</span>
            </div>
            <p className="text-sm text-gray-700">{healthCheck.summary}</p>
          </div>
        </div>
      </Card>

      {/* 历史报告 */}
      {showHistory && (
        <Card>
          <h2 className="text-sm font-medium mb-2 flex items-center gap-1.5">
            <History className="w-4 h-4 text-gray-500" />
            历史诊断报告
          </h2>
          {history && history.length > 0 ? (
            <div className="space-y-1.5">
              {history.map((r: any) => {
                const lc = levelConfig[r.level] || levelConfig.warning
                return (
                  <div key={r.id} className="flex items-center justify-between p-2 rounded-md bg-gray-50 text-xs">
                    <div className="flex items-center gap-2">
                      <span className="font-medium">{r.year} 年</span>
                      <span className={`font-bold ${lc.text}`}>{r.totalScore} 分</span>
                      <span className="text-gray-500">{r.summary}</span>
                    </div>
                    <span className="text-gray-400">
                      {new Date(r.createdAt).toLocaleDateString('zh-CN')}
                    </span>
                  </div>
                )
              })}
            </div>
          ) : (
            <div className="text-xs text-gray-500 text-center py-3">暂无历史报告</div>
          )}
        </Card>
      )}

      {/* 6 维度诊断 */}
      <div className="space-y-2">
        {healthCheck.dimensions.map((dim: any) => {
          const dimLevel = dim.score >= 85 ? 'safe' : dim.score >= 60 ? 'warning' : 'danger'
          const dc = levelConfig[dimLevel] || levelConfig.warning
          const DimIcon = dc.icon
          const isExpanded = expandedDim === dim.key
          return (
            <Card key={dim.key}>
              <button
                onClick={() => setExpandedDim(isExpanded ? null : dim.key)}
                className="flex items-center justify-between w-full text-left"
              >
                <div className="flex items-center gap-2.5">
                  <div className={`flex items-center justify-center w-8 h-8 rounded-lg ${dc.bg}`}>
                    <DimIcon className={`w-4 h-4 ${dc.text}`} />
                  </div>
                  <div>
                    <div className="text-sm font-medium">{dim.name}</div>
                    <div className="text-xs text-gray-500">{dim.findings[0]}</div>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <span className={`text-lg font-bold ${dc.text}`}>{dim.score}</span>
                  {isExpanded ? <ChevronUp className="w-4 h-4 text-gray-400" /> : <ChevronDown className="w-4 h-4 text-gray-400" />}
                </div>
              </button>

              {isExpanded && (
                <div className="mt-3 pt-3 border-t space-y-3">
                  {/* 发现的问题 */}
                  <div>
                    <div className="text-xs font-medium text-gray-700 mb-1">诊断发现</div>
                    <div className="space-y-1">
                      {dim.findings.map((f: string, i: number) => (
                        <div key={i} className="flex items-start gap-1.5 text-xs text-gray-600">
                          <span className={`w-1.5 h-1.5 rounded-full mt-1 flex-shrink-0 ${dim.score >= 85 ? 'bg-safe' : dim.score >= 60 ? 'bg-warning' : 'bg-danger'}`} />
                          {f}
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* 建议 */}
                  {dim.recommendations.length > 0 && (
                    <div>
                      <div className="text-xs font-medium text-primary mb-1">整改建议</div>
                      <div className="space-y-1">
                        {dim.recommendations.map((r: string, i: number) => (
                          <div key={i} className="flex items-start gap-1.5 text-xs text-gray-600">
                            <span className="w-1.5 h-1.5 rounded-full bg-primary mt-1 flex-shrink-0" />
                            {r}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </Card>
          )
        })}
      </div>
    </div>
  )
}
