import { useState } from "react"
import { useQuery } from "@tanstack/react-query"
import { rosterApi } from '../../lib/api-services'
import Card from "../../components/ui/Card"
import Button from "../../components/ui/Button"
import { FileText, AlertTriangle, Scale, X, Printer, Calculator, Shield } from "lucide-react"
import { fmt } from "./shared"
import { generateEvidenceText } from "./EvidenceChain"

export default function TerminationInfo({ employeeId, profile, records }: { employeeId: string; profile: any; records: any[] }) {
  const [printRecord, setPrintRecord] = useState<any | null>(null)
  const [showEvidence, setShowEvidence] = useState(false)

  const reasonMap: Record<string, string> = {
    NEGOTIATED: '协商解除', FAULT: '员工过错', NONFAULT: '非过错解除',
    LAYOFF: '经济性裁员', EXPIRED: '合同到期', ILLEGAL: '违法解除',
    RESIGNATION: '员工主动离职',
  }
  const legalBasisMap: Record<string, string> = {
    NEGOTIATED: '《劳动合同法》第36条', FAULT: '《劳动合同法》第39条',
    NONFAULT: '《劳动合同法》第40条', LAYOFF: '《劳动合同法》第41条',
    EXPIRED: '《劳动合同法》第44条、第46条', ILLEGAL: '《劳动合同法》第87条',
  }

  const { data: evidenceChain, isLoading: evidenceLoading } = useQuery<any>({
    queryKey: ['evidence-chain', employeeId],
    queryFn: async () => {
      return await rosterApi.evidenceChain(employeeId)
    },
    enabled: !!printRecord || showEvidence,
  })

  const validRecords = (records || []).filter((t: any) => t.status !== 'CANCELLED')
  const cancelledRecords = (records || []).filter((t: any) => t.status === 'CANCELLED')
  if (!validRecords.length && !cancelledRecords.length) return <Card><div className="text-center py-8 text-gray-400">暂无离职/解聘记录</div></Card>

  if (printRecord) {
    return (
      <div className="space-y-3">
        <div className="flex items-center justify-between">
          <button onClick={() => setPrintRecord(null)} className="text-gray-400 hover:text-gray-600 flex items-center gap-1 text-xs">
            <X className="w-4 h-4" />返回列表
          </button>
          <Button variant="secondary" size="sm" onClick={() => window.print()}>
            <Printer className="w-4 h-4 mr-1" />打印材料
          </Button>
        </div>

        {/* 1. 解聘通知书 */}
        <div className="border rounded-lg p-6 space-y-3 print:shadow-none">
          <div className="text-center">
            <h2 className="text-base font-bold">解除劳动合同通知书</h2>
          </div>
          <div className="text-xs text-gray-700 space-y-3">
            <p><strong>{profile.name}</strong> 先生/女士：</p>
            <p>
              您于 <strong>{profile.hireDate?.toString().slice(0, 10)}</strong> 入职我公司{profile.department}部门。
              因 <strong>{reasonMap[printRecord.reason] || printRecord.reason}</strong> 原因，公司决定于 <strong>{printRecord.terminationDate?.toString().slice(0, 10)}</strong> 起解除与您的劳动合同。
            </p>
            <p>解除依据：{legalBasisMap[printRecord.reason] || ''}</p>
            <p>经济补偿金：<strong>¥{fmt(printRecord.compensation)}</strong></p>
            {printRecord.remark && <p>备注：{printRecord.remark}</p>}
            <p>请于解除日期前办理工作交接手续，结清相关费用。</p>
            <div className="text-right mt-6 space-y-1">
              <p>公司（盖章）</p>
              <p className="text-gray-400">{printRecord.terminationDate?.toString().slice(0, 10)}</p>
            </div>
          </div>
        </div>

        {/* 2. 费用结算明细 */}
        <div className="border rounded-lg p-4 space-y-2">
          <h3 className="text-xs font-medium flex items-center gap-2"><Calculator className="w-4 h-4" />费用结算明细</h3>
          <div className="text-xs space-y-1">
            <div className="flex justify-between"><span>员工</span><span>{profile.name}（{profile.department}）</span></div>
            <div className="flex justify-between"><span>入职日期</span><span>{profile.hireDate?.toString().slice(0, 10)}</span></div>
            <div className="flex justify-between"><span>月工资</span><span>¥{fmt(profile.monthlySalary)}/月</span></div>
            <div className="flex justify-between"><span>解聘日期</span><span>{printRecord.terminationDate?.toString().slice(0, 10)}</span></div>
            <div className="flex justify-between"><span>解聘原因</span><span>{reasonMap[printRecord.reason] || printRecord.reason}</span></div>
            <div className="flex justify-between border-t pt-2 font-bold text-danger"><span>经济补偿金</span><span>¥{fmt(printRecord.compensation)}</span></div>
          </div>
        </div>

        {/* 3. 合规检查清单 */}
        {printRecord.checklist && Object.keys(printRecord.checklist).length > 0 && (
          <div className="border rounded-lg p-4 space-y-2">
            <h3 className="text-xs font-medium flex items-center gap-2"><Shield className="w-4 h-4" />合规检查清单</h3>
            <div className="text-xs space-y-1">
              {Object.entries(printRecord.checklist).map(([key, passed]: [string, any]) => (
                <div key={key} className="flex items-center gap-2">
                  <span className={passed ? 'text-safe' : 'text-danger'}>{passed ? '✓' : '✗'}</span>
                  <span className={passed ? '' : 'text-gray-500'}>{key}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* 4. 风险评估 */}
        {printRecord.riskLevel && printRecord.riskLevel !== 'SAFE' && (
          <div className="border rounded-lg p-4 space-y-2">
            <h3 className="text-xs font-medium flex items-center gap-2"><AlertTriangle className="w-4 h-4" />风险评估</h3>
            <div className="text-xs">
              <div className={`px-3 py-2 rounded-md ${printRecord.riskLevel === 'DANGER' ? 'bg-red-50 text-red-700' : 'bg-yellow-50 text-yellow-800'}`}>
                风险等级：{printRecord.riskLevel === 'DANGER' ? '高风险' : '注意'}
              </div>
            </div>
          </div>
        )}

        {/* 5. 仲裁证据链 */}
        <div className="border rounded-lg p-4 space-y-3">
          <h3 className="text-xs font-medium flex items-center gap-2"><FileText className="w-4 h-4" />仲裁证据链</h3>
          {evidenceChain ? (
            <>
              <div className="text-xs text-gray-500">
                共 {evidenceChain.summary?.total || 0} 条证据，
                已签确认 {evidenceChain.summary?.signed || 0} 条，
                未签 {evidenceChain.summary?.unsigned || 0} 条
              </div>
              {(() => {
                const grouped = (evidenceChain.evidence || []).reduce((acc: Record<string, any[]>, e: any) => {
                  (acc[e.category] = acc[e.category] || []).push(e)
                  return acc
                }, {})
                return Object.entries(grouped).map(([category, items]) => (
                  <div key={category} className="space-y-1">
                    <div className="text-xs font-medium text-gray-700">{category}</div>
                    {(items as any[]).map((e: any, i: number) => (
                      <div key={i} className="text-xs text-gray-600 pl-4 border-l-2 border-gray-200 ml-1">
                        <div className="flex items-center gap-2">
                          <span>{e.title}</span>
                          {e.acknowledged === true && <span className="text-safe">✓已签</span>}
                          {e.acknowledged === false && <span className="text-danger">✗未签</span>}
                        </div>
                        <div className="text-gray-400">{e.description}</div>
                      </div>
                    ))}
                  </div>
                ))
              })()}
            </>
          ) : (
            <div className="text-xs text-gray-400">加载证据链中...</div>
          )}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-3">
      {validRecords.map((t) => (
        <Card key={t.id} className="p-4">
          <div className="space-y-3">
            <div className="flex items-center gap-2 flex-wrap">
              <span className="text-xs font-medium text-gray-700">{t.terminationDate?.toString().slice(0, 10)}</span>
              <span className={`px-2 py-0.5 rounded text-xs ${t.type === 'RESIGNATION' ? 'bg-blue-50 text-blue-700' : 'bg-gray-100 text-gray-600'}`}>{t.type === 'RESIGNATION' ? '主动离职' : '公司解聘'}</span>
              <span className="px-2 py-0.5 rounded bg-gray-100 text-gray-600 text-xs">{reasonMap[t.reason] || t.reason}</span>
              {t.type !== 'RESIGNATION' && (
                <span className={`px-2 py-0.5 rounded text-xs ${t.riskLevel === 'SAFE' ? 'bg-green-50 text-safe' : t.riskLevel === 'WARNING' ? 'bg-amber-50 text-amber-600' : 'bg-red-50 text-danger'}`}>
                  {t.riskLevel === 'SAFE' ? '风险低' : t.riskLevel === 'WARNING' ? '注意' : '高风险'}
                </span>
              )}
              {t.status && (
                <span className={`px-2 py-0.5 rounded text-xs ${t.status === 'COMPLETED' ? 'bg-green-50 text-safe' : t.status === 'PENDING_APPROVAL' ? 'bg-amber-50 text-amber-700' : t.status === 'APPROVED' ? 'bg-blue-50 text-blue-700' : 'bg-gray-100 text-gray-600'}`}>
                  {t.status === 'DRAFT' ? '草稿' : t.status === 'PENDING_APPROVAL' ? '待审批' : t.status === 'APPROVED' ? '已审批' : t.status === 'COMPLETED' ? '已完成' : t.status === 'REJECTED' ? '已驳回' : t.status === 'EXECUTING' ? '执行中' : t.status}
                </span>
              )}
            </div>
            <div className="grid md:grid-cols-3 gap-x-6 gap-y-3 text-xs">
              {t.type === 'RESIGNATION' ? (
                <>
                  <div className="flex justify-between border-b pb-1.5">
                    <span className="text-gray-400 shrink-0">离职原因</span>
                    <span className="font-medium text-gray-700 text-right truncate ml-2">{t.resignationReason || '-'}</span>
                  </div>
                </>
              ) : (
                <>
                  <div className="flex justify-between border-b pb-1.5">
                    <span className="text-gray-400 shrink-0">经济补偿金</span>
                    <span className="font-medium text-gray-700 text-right truncate ml-2">¥{fmt(t.compensation)}</span>
                  </div>
                  <div className="flex justify-between border-b pb-1.5">
                    <span className="text-gray-400 shrink-0">法律依据</span>
                    <span className="font-medium text-gray-700 text-right truncate ml-2">{legalBasisMap[t.reason] || '-'}</span>
                  </div>
                </>
              )}
            </div>
            {t.remark && <div className="text-xs text-gray-500 bg-gray-50 px-2 py-1.5 rounded">{t.remark}</div>}
            <div className="flex justify-end">
              {t.type !== 'RESIGNATION' && (
                <Button variant="secondary" size="sm" onClick={() => setPrintRecord(t)}>
                  <Printer className="w-4 h-4 mr-1" />打印解聘材料
                </Button>
              )}
            </div>
          </div>
        </Card>
      ))}
      {cancelledRecords.length > 0 && (
        <>
          {validRecords.length > 0 && <div className="text-xs text-gray-400 pt-2">已撤销记录</div>}
          {cancelledRecords.map((t) => (
            <Card key={t.id} className="p-4 opacity-60">
              <div className="space-y-3">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-xs font-medium text-gray-500">{t.terminationDate?.toString().slice(0, 10)}</span>
                  <span className="px-2 py-0.5 rounded text-xs bg-gray-100 text-gray-500">{t.type === 'RESIGNATION' ? '主动离职' : '公司解聘'}</span>
                  <span className="px-2 py-0.5 rounded bg-gray-100 text-gray-500 text-xs">{reasonMap[t.reason] || t.reason}</span>
                  <span className="px-2 py-0.5 rounded text-xs bg-red-50 text-red-500 line-through">已撤销</span>
                </div>
                <div className="grid md:grid-cols-3 gap-x-6 gap-y-3 text-xs">
                  {t.type === 'RESIGNATION' ? (
                    <div className="flex justify-between border-b pb-1.5">
                      <span className="text-gray-400 shrink-0">离职原因</span>
                      <span className="font-medium text-gray-500 text-right truncate ml-2">{t.resignationReason || '-'}</span>
                    </div>
                  ) : (
                    <>
                      <div className="flex justify-between border-b pb-1.5">
                        <span className="text-gray-400 shrink-0">经济补偿金</span>
                        <span className="font-medium text-gray-500 text-right truncate ml-2">¥{fmt(t.compensation)}</span>
                      </div>
                      <div className="flex justify-between border-b pb-1.5">
                        <span className="text-gray-400 shrink-0">法律依据</span>
                        <span className="font-medium text-gray-500 text-right truncate ml-2">{legalBasisMap[t.reason] || '-'}</span>
                      </div>
                    </>
                  )}
                </div>
                {t.remark && <div className="text-xs text-gray-400 bg-gray-50 px-2 py-1.5 rounded">{t.remark}</div>}
              </div>
            </Card>
          ))}
        </>
      )}

      {/* 仲裁证据链 */}
      <div className="pt-3 border-t">
        <button
          onClick={() => setShowEvidence(!showEvidence)}
          className="flex items-center gap-2 text-xs font-medium text-gray-600 hover:text-gray-800"
        >
          <Scale className="w-4 h-4" />
          仲裁证据链
          {evidenceChain && (
            <span className="text-gray-400">
              （{evidenceChain.summary?.total || 0}条证据，已签{evidenceChain.summary?.signed || 0}，未签{evidenceChain.summary?.unsigned || 0}）
            </span>
          )}
          <span className="text-gray-400">{showEvidence ? '▾' : '▸'}</span>
        </button>
        {showEvidence && (
          <div className="mt-3 space-y-2">
            {evidenceLoading ? (
              <div className="text-xs text-gray-400 text-center py-4">生成证据链中...</div>
            ) : evidenceChain ? (
              <>
                {evidenceChain.risks && evidenceChain.risks.length > 0 && (
                  <Card className="p-3">
                    <div className="text-xs font-medium mb-2 flex items-center gap-1 text-danger">
                      <AlertTriangle className="w-3.5 h-3.5" />风险提醒（{evidenceChain.risks.length}项）
                    </div>
                    <div className="space-y-1.5">
                      {evidenceChain.risks.map((r: any, i: number) => (
                        <div key={i} className="text-xs border rounded p-2 bg-red-50 border-red-200 text-red-700">
                          <span className="font-medium">{r.title}</span>
                          <span className="text-xs opacity-70 ml-2">{r.category}</span>
                          <div className="opacity-90 mt-0.5">{r.description}</div>
                        </div>
                      ))}
                    </div>
                  </Card>
                )}
                {evidenceChain.evidence?.map((e: any, i: number) => (
                  <Card key={i} className="p-3">
                    <div className="flex items-start gap-2">
                      <span className="px-1.5 py-0.5 rounded border text-xs shrink-0 bg-gray-50 text-gray-600 border-gray-200">{e.category}</span>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="font-medium text-xs">{e.title}</span>
                          <span className="text-xs text-gray-400">{e.date}</span>
                          {e.acknowledged === true && <span className="text-xs text-safe">✓已签</span>}
                          {e.acknowledged === false && <span className="text-xs text-warning">⚠未签</span>}
                          {e.riskLevel === 'HIGH' && <span className="text-xs text-danger">⚠高风险</span>}
                        </div>
                        <div className="text-xs text-gray-600 mt-0.5">{e.description}</div>
                      </div>
                    </div>
                  </Card>
                ))}
                <button
                  onClick={() => {
                    const text = generateEvidenceText(evidenceChain)
                    const blob = new Blob([text], { type: 'text/plain;charset=utf-8' })
                    const url = URL.createObjectURL(blob)
                    const a = document.createElement('a')
                    a.href = url
                    a.download = `仲裁证据链_${evidenceChain.employee?.name}_${new Date().toISOString().slice(0, 10)}.txt`
                    a.click()
                    URL.revokeObjectURL(url)
                  }}
                  className="text-xs text-primary hover:underline"
                >
                  导出证据链
                </button>
              </>
            ) : (
              <div className="text-xs text-gray-400 text-center py-4">无数据</div>
            )}
          </div>
        )}
      </div>
    </div>
  )
}
