import { useState } from 'react'
import { toast } from 'sonner'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { PenTool, Plus, X, RefreshCw, ExternalLink, FileText, AlertCircle } from 'lucide-react'
import { esignApi, rosterApi } from '../lib/api-services'
import PageGuide from '../components/ui/PageGuide'
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 Modal from '../components/ui/Modal'

const STATUS_CONFIG: Record<string, { label: string; color: string }> = {
  PENDING: { label: '待签署', color: 'bg-yellow-50 text-yellow-700' },
  SIGNING: { label: '签署中', color: 'bg-blue-50 text-blue-700' },
  COMPLETED: { label: '已完成', color: 'bg-green-50 text-safe' },
  REJECTED: { label: '已拒绝', color: 'bg-red-50 text-danger' },
  EXPIRED: { label: '已过期', color: 'bg-gray-100 text-gray-500' },
  CANCELLED: { label: '已取消', color: 'bg-gray-100 text-gray-500' },
}

export default function ESign() {
  const queryClient = useQueryClient()
  const [filterStatus, setFilterStatus] = useState('')
  const [showCreate, setShowCreate] = useState(false)
  const [formData, setFormData] = useState({
    employeeId: '',
    documentTitle: '',
    remark: '',
  })

  const { data: records = [], isLoading } = useQuery<any[]>({
    queryKey: ['esign-records', filterStatus],
    queryFn: async () => {
      return await esignApi.list(filterStatus || undefined)
    },
  })

  const { data: rosterData } = useQuery<any>({
    queryKey: ['roster-for-esign'],
    queryFn: async () => {
      return await rosterApi.list({ search: '', page: 1, pageSize: 200 } as any) as any
    },
    enabled: showCreate,
  })

  const createMutation = useMutation({
    mutationFn: async (data: { employeeId: string; documentTitle: string; remark?: string }) =>
      esignApi.create(data) as any,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['esign-records'] })
      setShowCreate(false)
      setFormData({ employeeId: '', documentTitle: '', remark: '' })
      toast.success('签署记录已创建，待对接易签宝后将自动发送签署链接')
    },
    onError: () => toast.error('创建失败'),
  })

  const cancelMutation = useMutation({
    mutationFn: (id: string) => esignApi.cancel(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['esign-records'] })
      toast.success('已取消签署')
    },
  })

  const refreshStatusMutation = useMutation({
    mutationFn: (id: string) => esignApi.status(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['esign-records'] })
      toast.success('状态已刷新')
    },
  })

  const handleCreate = () => {
    if (!formData.employeeId) { toast.error('请选择员工'); return }
    if (!formData.documentTitle.trim()) { toast.error('请填写文件标题'); return }
    createMutation.mutate(formData)
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-2">
        <PenTool className="h-5 w-5 text-primary" />
        <div>
          <h1 className="text-base font-semibold">电子签署</h1>
          <p className="mt-1 text-sm text-gray-500">对接易签宝实现在线合同签署</p>
        </div>
      </div>

      <PageGuide>
        通过易签宝平台发起电子合同签署，员工在线完成签署后自动回传签署状态和PDF文件。
        <span className="text-amber-600"> 当前为框架预留阶段，对接易签宝API后将自动启用在线签署功能。</span>
      </PageGuide>

      <InlineAlert type="info" className="flex items-start gap-2">
        <AlertCircle className="w-4 h-4 mt-0.5 shrink-0" />
        <div>
          <span className="font-medium">对接状态：框架已就绪，待接入易签宝API</span>
          <div className="mt-1 text-xs">
            需要提供易签宝的 AppId、AppSecret 和 API 基础地址。对接后可实现：
            ① HR在系统发起签署 → ② 调用易签宝创建签署流程 → ③ 员工收到签署链接 → ④ 签署完成自动回调更新状态 → ⑤ 合同自动关联电子版PDF
          </div>
        </div>
      </InlineAlert>

      <div className="flex items-center justify-between">
        <div className="flex gap-2">
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value)}
            className="h-9 rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-700 shadow-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/10"
          >
            <option value="">全部状态</option>
            {Object.entries(STATUS_CONFIG).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
          </select>
        </div>
        <Button size="sm" onClick={() => setShowCreate(true)}>
          <Plus className="w-4 h-4 mr-1" />发起签署
        </Button>
      </div>

      {/* 签署记录列表 */}
      <Card>
        {isLoading ? (
          <div className="text-center py-8 text-gray-400">加载中...</div>
        ) : records.length === 0 ? (
          <div className="text-center py-8 text-gray-400 text-sm">暂无签署记录，点击「发起签署」创建</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b text-xs text-gray-500">
                  <th className="py-2 px-3 text-left">文件标题</th>
                  <th className="py-2 px-3 text-left">签署人</th>
                  <th className="py-2 px-3 text-left">部门</th>
                  <th className="py-2 px-3 text-left">状态</th>
                  <th className="py-2 px-3 text-left">发起时间</th>
                  <th className="py-2 px-3 text-left">完成时间</th>
                  <th className="py-2 px-3 text-right">操作</th>
                </tr>
              </thead>
              <tbody>
                {records.map((r: any) => {
                  const statusCfg = STATUS_CONFIG[r.status] || STATUS_CONFIG.PENDING
                  return (
                    <tr key={r.id} className="border-b last:border-0 hover:bg-gray-50">
                      <td className="py-2 px-3">
                        <div className="flex items-center gap-1.5">
                          <FileText className="w-3.5 h-3.5 text-gray-400 shrink-0" />
                          <span className="font-medium truncate max-w-[200px]">{r.documentTitle}</span>
                        </div>
                        {r.remark && <div className="text-xs text-gray-400 mt-0.5">{r.remark}</div>}
                      </td>
                      <td className="py-2 px-3">{r.employee?.name || '—'}</td>
                      <td className="py-2 px-3 text-gray-500">{r.employee?.department || '—'}</td>
                      <td className="py-2 px-3">
                        <span className={`px-2 py-0.5 rounded text-xs ${statusCfg.color}`}>{statusCfg.label}</span>
                      </td>
                      <td className="py-2 px-3 text-gray-500 text-xs">{new Date(r.createdAt).toLocaleString('zh-CN')}</td>
                      <td className="py-2 px-3 text-gray-500 text-xs">{r.completedAt ? new Date(r.completedAt).toLocaleString('zh-CN') : '—'}</td>
                      <td className="py-2 px-3 text-right">
                        <div className="flex items-center justify-end gap-1">
                          {r.status === 'COMPLETED' && r.signedPdfUrl && (
                            <a href={r.signedPdfUrl} target="_blank" rel="noopener noreferrer"
                              className="text-xs text-primary hover:underline flex items-center gap-0.5">
                              <ExternalLink className="w-3 h-3" />查看PDF
                            </a>
                          )}
                          {(r.status === 'PENDING' || r.status === 'SIGNING') && (
                            <>
                              <button className="text-xs text-gray-400 hover:text-primary" onClick={() => refreshStatusMutation.mutate(r.id)}
                                title="刷新状态">
                                <RefreshCw className={`w-3.5 h-3.5 ${refreshStatusMutation.isPending ? 'animate-spin' : ''}`} />
                              </button>
                              <button className="text-xs text-gray-400 hover:text-danger" onClick={() => {
                                if (confirm('确定取消此签署任务吗？')) cancelMutation.mutate(r.id)
                              }}>取消</button>
                            </>
                          )}
                        </div>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </Card>

      {/* 发起签署 Modal */}
      {showCreate && (
        <Modal open={true} onClose={() => setShowCreate(false)} title="发起电子签署" size="md">
          <div className="space-y-3">
            <InlineAlert type="info">
              选择员工并填写文件标题，系统将创建签署记录。对接易签宝后，将自动生成签署链接并发送给员工。
            </InlineAlert>
            <div>
              <Label>签署员工 *</Label>
              <select
                className="h-9 w-full rounded-md border border-gray-200 bg-white px-3 text-sm text-gray-700 shadow-sm outline-none transition focus:border-primary focus:ring-2 focus:ring-primary/10"
                value={formData.employeeId}
                onChange={(e) => setFormData({ ...formData, employeeId: e.target.value })}
              >
                <option value="">请选择员工</option>
                {rosterData?.items?.filter((e: any) => e.status === 'ACTIVE').map((emp: any) => (
                  <option key={emp.id} value={emp.id}>{emp.name} - {emp.department}</option>
                ))}
              </select>
            </div>
            <div>
              <Label>文件标题 *</Label>
              <Input value={formData.documentTitle} onChange={(e) => setFormData({ ...formData, documentTitle: e.target.value })}
                placeholder="如：2024年度劳动合同" />
            </div>
            <div>
              <Label>备注</Label>
              <Input value={formData.remark} onChange={(e) => setFormData({ ...formData, remark: e.target.value })}
                placeholder="可选" />
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <Button variant="secondary" size="sm" onClick={() => setShowCreate(false)}>取消</Button>
              <Button size="sm" onClick={handleCreate} disabled={createMutation.isPending}>
                {createMutation.isPending ? '创建中...' : '发起签署'}
              </Button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}
