/**
 * 员工端 — 电子签署页面
 * 查看自己的待签/已签文件，通过手机验证码确认签署
 *
 * 签署流程：
 * 1. 查看待签文件内容
 * 2. 点击「获取验证码」→ 系统发送验证码到登记手机号
 * 3. 输入验证码 → 点击「确认签署」
 * 4. 签署完成，自动记录证据链
 */
import { useState, useRef, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { PenTool, FileText, CheckCircle2, Clock, XCircle, ChevronLeft, Shield, Phone } from 'lucide-react'
import { portalApi } from '../../lib/api-services'
import Card from '../../components/ui/Card'
import Button from '../../components/ui/Button'
import { Input, Label } from '../../components/ui/Input'
import { InlineAlert } from '../../components/ui/InlineAlert'
import EmptyState from '../../components/ui/EmptyState'

const STATUS_MAP: Record<string, { label: string; color: string; icon: React.ReactNode }> = {
  PENDING: { label: '待签署', color: 'bg-amber-50 text-amber-700', icon: <Clock className="w-3 h-3" /> },
  SIGNING: { label: '签署中', color: 'bg-blue-50 text-blue-700', icon: <Clock className="w-3 h-3" /> },
  COMPLETED: { label: '已签署', color: 'bg-green-50 text-safe', icon: <CheckCircle2 className="w-3 h-3" /> },
  CANCELLED: { label: '已取消', color: 'bg-gray-100 text-gray-400', icon: <XCircle className="w-3 h-3" /> },
  EXPIRED: { label: '已过期', color: 'bg-red-50 text-red-600', icon: <XCircle className="w-3 h-3" /> },
}

const SCENE_LABELS: Record<string, { label: string; color: string }> = {
  CONTRACT: { label: '劳动合同', color: 'bg-blue-50 text-blue-600 border border-blue-200' },
  RESIGNATION: { label: '离职协议', color: 'bg-orange-50 text-orange-600 border border-orange-200' },
  POLICY: { label: '规章制度', color: 'bg-amber-50 text-amber-600 border border-amber-200' },
  PAYSLIP: { label: '工资条', color: 'bg-emerald-50 text-emerald-600 border border-emerald-200' },
  ONBOARDING: { label: '入职文件', color: 'bg-purple-50 text-purple-600 border border-purple-200' },
}

const SIGN_METHOD_LABELS: Record<string, { label: string; color: string }> = {
  ELECTRONIC: { label: '电子签', color: 'bg-blue-50 text-blue-600' },
  PAPER: { label: '线下手签', color: 'bg-orange-50 text-orange-600' },
}

export default function MyEsign() {
  const queryClient = useQueryClient()
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [verifyCode, setVerifyCode] = useState('')
  const [countdown, setCountdown] = useState(0)
  const codeInputRef = useRef<HTMLInputElement>(null)

  const { data: list = [], isLoading } = useQuery<any[]>({
    queryKey: ['portal-esign'],
    queryFn: () => portalApi.myEsignList(),
  })

  const { data: detail, isLoading: detailLoading } = useQuery<any>({
    queryKey: ['portal-esign-detail', selectedId],
    queryFn: () => portalApi.esignDetail(selectedId!),
    enabled: !!selectedId,
  })

  /** 发送验证码 */
  const sendCodeMutation = useMutation({
    mutationFn: (id: string) => portalApi.esignSendCode(id),
    onSuccess: (res: any) => {
      toast.success(`验证码已发送至 ${res.phone || '登记手机号'}`)
      setCountdown(60)
      // 开发阶段直接显示验证码
      if (res.code) {
        toast.info(`开发模式验证码：${res.code}`, { duration: 10000 })
      }
      setTimeout(() => codeInputRef.current?.focus(), 100)
    },
    onError: (err: any) => toast.error(err?.response?.data?.error?.message || '验证码发送失败'),
  })

  /** 签署确认 */
  const signMutation = useMutation({
    mutationFn: ({ id, code }: { id: string; code: string }) => portalApi.signEsign(id, code),
    onSuccess: () => {
      toast.success('签署成功')
      queryClient.invalidateQueries({ queryKey: ['portal-esign'] })
      queryClient.invalidateQueries({ queryKey: ['portal-esign-detail', selectedId] })
      setVerifyCode('')
    },
    onError: (err: any) => toast.error(err?.response?.data?.error?.message || '签署失败'),
  })

  /** 倒计时 */
  useEffect(() => {
    if (countdown <= 0) return
    const timer = setTimeout(() => setCountdown(countdown - 1), 1000)
    return () => clearTimeout(timer)
  }, [countdown])

  const pendingCount = list.filter((r: any) => r.status === 'PENDING').length

  // ===== 详情页 =====
  if (selectedId) {
    const st = detail ? STATUS_MAP[detail.status] || STATUS_MAP.PENDING : null
    const canSign = detail?.status === 'PENDING' && detail?.signMethod !== 'PAPER'
    const isPaperSign = detail?.signMethod === 'PAPER'

    return (
      <div className="space-y-4">
        <button
          onClick={() => { setSelectedId(null); setVerifyCode('') }}
          className="flex items-center gap-1 text-gray-500 hover:text-gray-700 text-sm py-2"
        >
          <ChevronLeft className="w-4 h-4" />返回列表
        </button>

        {detailLoading ? (
          <Card className="p-6">
            <div className="animate-pulse space-y-3">
              <div className="h-6 bg-gray-100 rounded w-2/3" />
              <div className="h-4 bg-gray-100 rounded w-1/3" />
              <div className="h-20 bg-gray-100 rounded w-full" />
            </div>
          </Card>
        ) : detail ? (
          <>
            <Card className="p-5">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center">
                  <FileText className="w-5 h-5 text-primary" />
                </div>
                <div className="flex-1 min-w-0">
                  <h1 className="text-base font-semibold truncate">{detail.documentTitle}</h1>
                  <div className="text-xs text-gray-500 mt-0.5">
                    发起时间：{new Date(detail.createdAt).toLocaleString('zh-CN')}
                  </div>
                </div>
                {st && (
                  <span className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs ${st.color}`}>
                    {st.icon}{st.label}
                  </span>
                )}
              </div>

              {detail.remark && (
                <div className="mb-4 px-3 py-2 rounded-md bg-gray-50 text-xs text-gray-600">
                  {detail.remark}
                </div>
              )}

              {detail.scene && SCENE_LABELS[detail.scene] && (
                <div className="mb-3">
                  <span className={`px-2 py-0.5 rounded text-xs ${SCENE_LABELS[detail.scene].color}`}>{SCENE_LABELS[detail.scene].label}</span>
                </div>
              )}
            </Card>

            {/* 文件内容 */}
            {detail.documentContent && (
              <Card className="p-5">
                <div className="text-sm font-medium mb-3 flex items-center gap-1.5">
                  <FileText className="w-4 h-4 text-gray-400" />文件内容
                </div>
                <div className="text-sm text-gray-700 whitespace-pre-wrap leading-relaxed border rounded-md p-3 max-h-96 overflow-y-auto bg-gray-50/50">
                  {detail.documentContent}
                </div>
              </Card>
            )}

            {/* 线下手签信息 */}
            {isPaperSign && (
              <Card className="p-5">
                <div className="text-sm font-medium mb-3 flex items-center gap-1.5">
                  <FileText className="w-4 h-4 text-orange-500" />线下手签信息
                </div>
                <div className="grid grid-cols-2 gap-3 text-xs">
                  <div>
                    <div className="text-gray-400">签署日期</div>
                    <div className="text-gray-700">{detail.signedAt ? new Date(detail.signedAt).toLocaleDateString('zh-CN') : '—'}</div>
                  </div>
                  <div>
                    <div className="text-gray-400">签署地点</div>
                    <div className="text-gray-700">{detail.signedLocation || '—'}</div>
                  </div>
                  <div>
                    <div className="text-gray-400">见证人</div>
                    <div className="text-gray-700">{detail.witnessName || '—'}</div>
                  </div>
                </div>
                {detail.scanFileUrls && (detail.scanFileUrls as any[]).length > 0 && (
                  <div className="mt-3 space-y-2">
                    <div className="text-xs text-gray-400">签署扫描件（{(detail.scanFileUrls as any[]).length}份）</div>
                    {(detail.scanFileUrls as any[]).map((f: any, i: number) => (
                      <div key={i} className="flex items-center gap-2 text-xs bg-gray-50 rounded px-3 py-2">
                        <FileText className="w-4 h-4 text-gray-400 shrink-0" />
                        <a href={f.url} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline flex-1 truncate">{f.name}</a>
                      </div>
                    ))}
                  </div>
                )}
              </Card>
            )}

            {/* 签署操作 */}
            <Card className="p-5">
              {canSign ? (
                <div className="space-y-4">
                  <InlineAlert type="info" className="flex items-start gap-2">
                    <Shield className="w-4 h-4 mt-0.5 shrink-0" />
                    <div className="text-xs">
                      <div className="font-medium">签署确认</div>
                      <div className="mt-1">请仔细阅读上述文件内容，确认无误后通过手机验证码完成签署。签署后将自动记录证据链（IP、时间戳、验证码），具有法律效力。</div>
                    </div>
                  </InlineAlert>

                  <div>
                    <Label>手机验证码</Label>
                    <div className="flex gap-2">
                      <Input
                        ref={codeInputRef}
                        value={verifyCode}
                        onChange={(e) => setVerifyCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                        placeholder="请输入6位验证码"
                        maxLength={6}
                        className="flex-1"
                        onKeyDown={(e) => {
                          if (e.key === 'Enter' && verifyCode.length === 6) {
                            signMutation.mutate({ id: detail.id, code: verifyCode })
                          }
                        }}
                      />
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => sendCodeMutation.mutate(detail.id)}
                        disabled={sendCodeMutation.isPending || countdown > 0}
                        className="whitespace-nowrap"
                      >
                        {countdown > 0 ? `${countdown}s` : '获取验证码'}
                      </Button>
                    </div>
                    <div className="text-xs text-gray-400 mt-1 flex items-center gap-1">
                      <Phone className="w-3 h-3" />
                      验证码将发送至您登记的手机号
                    </div>
                  </div>

                  <Button
                    className="w-full"
                    onClick={() => signMutation.mutate({ id: detail.id, code: verifyCode })}
                    disabled={signMutation.isPending || verifyCode.length !== 6}
                  >
                    <PenTool className="w-4 h-4 mr-1" />
                    {signMutation.isPending ? '签署中...' : '确认签署'}
                  </Button>
                </div>
              ) : detail.status === 'COMPLETED' ? (
                <div className="text-center space-y-2">
                  <CheckCircle2 className="w-10 h-10 text-safe mx-auto" />
                  <div className="text-sm font-medium text-gray-700">
                    {isPaperSign ? '线下手签已登记' : '签署已完成'}
                  </div>
                  <div className="text-xs text-gray-400">
                    {isPaperSign
                      ? `签署日期：${detail.signedAt ? new Date(detail.signedAt).toLocaleDateString('zh-CN') : '—'}`
                      : `完成时间：${detail.completedAt ? new Date(detail.completedAt).toLocaleString('zh-CN') : '—'}`}
                  </div>
                  {isPaperSign && detail.signedLocation && (
                    <div className="text-xs text-gray-400">签署地点：{detail.signedLocation}</div>
                  )}
                </div>
              ) : (
                <div className="text-center text-xs text-gray-400">
                  当前状态：{st?.label}
                </div>
              )}
            </Card>
          </>
        ) : (
          <Card className="p-6">
            <EmptyState title="记录不存在" description="该签署记录可能已被删除" />
          </Card>
        )}
      </div>
    )
  }

  // ===== 列表页 =====
  return (
    <div className="space-y-4">
      <div className="flex items-center gap-2">
        <PenTool className="w-5 w-5 text-primary" />
        <h1 className="text-base font-bold">电子签署</h1>
        {pendingCount > 0 && (
          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-amber-100 text-amber-700">
            <Clock className="w-3 h-3" />{pendingCount} 项待签
          </span>
        )}
      </div>

      {isLoading ? (
        <div className="text-center py-12 text-gray-400 text-sm">加载中...</div>
      ) : list.length === 0 ? (
        <Card className="p-6">
          <EmptyState title="暂无签署任务" description="没有需要您签署的文件" />
        </Card>
      ) : (
        <div className="space-y-2">
          {list.map((r: any) => {
            const st = STATUS_MAP[r.status] || STATUS_MAP.PENDING
            return (
              <Card key={r.id} className="cursor-pointer hover:shadow-md transition-shadow">
                <div onClick={() => setSelectedId(r.id)} className="flex items-center gap-3 p-4">
                  <div className={`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${
                    r.status === 'PENDING' ? 'bg-amber-100' : r.status === 'COMPLETED' ? 'bg-green-100' : 'bg-gray-100'
                  }`}>
                    <FileText className={`w-5 h-5 ${
                      r.status === 'PENDING' ? 'text-amber-600' : r.status === 'COMPLETED' ? 'text-green-600' : 'text-gray-400'
                    }`} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1.5">
                      <span className="text-sm font-medium truncate min-w-0">{r.documentTitle}</span>
                      {r.scene && SCENE_LABELS[r.scene] && (
                        <span className={`px-1.5 py-0.5 rounded text-xs flex-shrink-0 ${SCENE_LABELS[r.scene].color}`}>{SCENE_LABELS[r.scene].label}</span>
                      )}
                      {r.signMethod === 'PAPER' && (
                        <span className={`px-1.5 py-0.5 rounded text-xs flex-shrink-0 ${(SIGN_METHOD_LABELS[r.signMethod] || SIGN_METHOD_LABELS.ELECTRONIC).color}`}>
                          {(SIGN_METHOD_LABELS[r.signMethod] || SIGN_METHOD_LABELS.ELECTRONIC).label}
                        </span>
                      )}
                    </div>
                    <div className="text-xs text-gray-500 mt-1">
                      {new Date(r.createdAt).toLocaleDateString('zh-CN')}
                    </div>
                  </div>
                  <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs flex-shrink-0 ${st.color}`}>
                    {st.icon}{st.label}
                  </span>
                </div>
              </Card>
            )
          })}
        </div>
      )}
    </div>
  )
}
