import { QRCodeSVG } from "qrcode.react"
import { useUnsavedChanges } from "../../hooks/useUnsavedChanges"
import { useState, useRef } from "react"
import { toast } from "sonner"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import api from "../../lib/api"
import Card from "../../components/ui/Card"
import Button from "../../components/ui/Button"
import { Input, Label, Select } from "../../components/ui/Input"
import Modal from "../../components/ui/Modal"
import { Users, FileText, AlertTriangle, Calendar, GraduationCap, TrendingUp, Scale, X, Plus, Paperclip, Trash2, Printer, Calculator, Shield, Info, Check, Eye, Download, UserX, UserPlus, Briefcase, FileSignature, DollarSign, Building2, RotateCcw, History } from "lucide-react"
import { fmt } from "./shared"

export default function BasicInfo({ profile, employeeId, attachments }: { profile: any; employeeId: string; attachments: any[] }) {
  const queryClient = useQueryClient()
  const [editing, setEditing] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [fileType, setFileType] = useState<'ID_CARD' | 'BANK_CARD' | 'EDUCATION' | 'OTHER'>('ID_CARD')

  const addAttachmentMutation = useMutation({
    mutationFn: (data: any) => api.post('/attachments', data),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['roster-profile', employeeId] }),
  })

  const deleteAttachmentMutation = useMutation({
    mutationFn: (id: string) => api.delete(`/attachments/${id}`),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['roster-profile', employeeId] }),
  })

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    const allowedTypes = ['application/pdf', 'image/jpeg', 'image/jpg', 'image/png', 'image/heic']
    const allowedExts = ['.pdf', '.jpg', '.jpeg', '.png', '.heic']
    const ext = file.name.toLowerCase().substring(file.name.lastIndexOf('.'))
    if (!allowedTypes.includes(file.type) && !allowedExts.includes(ext)) {
      toast.error('不支持的文件格式，请上传 PDF、JPG、PNG 或 HEIC 格式')
      return
    }
    if (file.size > 10 * 1024 * 1024) {
      toast.error('文件过大，请上传小于 10MB 的文件')
      return
    }
    const reader = new FileReader()
    reader.onload = (event) => {
      const fileUrl = event.target?.result as string
      addAttachmentMutation.mutate({ employeeId, fileName: file.name, fileType, fileUrl, fileSize: file.size })
    }
    reader.readAsDataURL(file)
  }

  const fileTypeLabels: Record<string, string> = { ID_CARD: '身份证', BANK_CARD: '银行卡', EDUCATION: '学历证书', OTHER: '其他' }
  const fileTypeColors: Record<string, string> = { ID_CARD: 'bg-blue-50 text-blue-600', BANK_CARD: 'bg-green-50 text-safe', EDUCATION: 'bg-amber-50 text-amber-600', OTHER: 'bg-gray-100 text-gray-500' }
  const formatSize = (bytes: number) => {
    if (!bytes) return '-'
    if (bytes < 1024) return `${bytes}B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)}KB`
    return `${(bytes / 1024 / 1024).toFixed(1)}MB`
  }

  const [form, setForm] = useState({
    department: profile.department || '',
    gender: profile.gender || '男',
    femaleWorkerType: profile.femaleWorkerType || '',
    phone: profile.phone || '',
    hireDate: profile.hireDate?.toString().slice(0, 10) || '',
    monthlySalary: profile.monthlySalary || '',
    emergencyContact: profile.emergencyContact || '',
    emergencyPhone: profile.emergencyPhone || '',
    address: profile.address || '',
    bankName: profile.bankName || '',
    bankAccount: profile.bankAccount || '',
    isPregnant: profile.isPregnant || false,
    isInMedicalPeriod: profile.isInMedicalPeriod || false,
    isWorkInjured: profile.isWorkInjured || false,
    socialInsBase: profile.socialInsBase ?? '',
    housingFundBase: profile.housingFundBase ?? '',
    specialDeduction: profile.specialDeduction ?? 0,
    city: profile.city || '',
    cityChangeReason: '',
  })

  const updateMutation = useMutation({
    mutationFn: (data: any) => api.put(`/employees/${profile.id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['roster-profile'] })
      queryClient.invalidateQueries({ queryKey: ['roster'] })
      setEditing(false)
    },
  })

  const handleSave = () => {
    if (form.city !== (profile.city || '') && !form.cityChangeReason.trim()) {
      toast.error('参保城市变更必须填写变更原因')
      return
    }
    const data: any = {
      department: form.department,
      gender: form.gender,
      femaleWorkerType: form.femaleWorkerType || undefined,
      phone: form.phone || undefined,
      hireDate: new Date(form.hireDate).toISOString(),
      monthlySalary: String(form.monthlySalary),
      emergencyContact: form.emergencyContact || undefined,
      emergencyPhone: form.emergencyPhone || undefined,
      address: form.address || undefined,
      bankName: form.bankName || undefined,
      bankAccount: form.bankAccount || undefined,
      isPregnant: form.isPregnant,
      isInMedicalPeriod: form.isInMedicalPeriod,
      isWorkInjured: form.isWorkInjured,
      socialInsBase: form.socialInsBase === '' ? null : Number(form.socialInsBase),
      housingFundBase: form.housingFundBase === '' ? null : Number(form.housingFundBase),
      specialDeduction: Number(form.specialDeduction) || 0,
      city: form.city || undefined,
      cityChangeReason: form.city !== profile.city ? form.cityChangeReason || undefined : undefined,
    }
    updateMutation.mutate(data)
  }

  const personalFields = [
    { label: '姓名', value: profile.name },
    { label: '部门', value: profile.department },
    { label: '性别', value: profile.gender || '未填写' },
    ...(profile.gender === '女'
      ? [{ label: '女性岗位', value: profile.femaleWorkerType === 'CADRE' ? '干部/管理岗' : profile.femaleWorkerType === 'WORKER' ? '工人/操作岗' : '未填写' }]
      : []),
    { label: '身份证号', value: profile.idCardNumber || '未填写' },
    { label: '手机号', value: profile.phone || '未填写' },
    { label: '入职日期', value: profile.hireDate?.toString().slice(0, 10) },
    { label: '状态', value: profile.status === 'ACTIVE' ? '在职' : '离职' },
    ...(profile.retirementDaysLeft != null
      ? (() => {
          if (profile.retirementDaysLeft <= 0) return [{ label: '距退休', value: '已到退休年龄' }]
          if (profile.birthDate) {
            const bd = new Date(profile.birthDate)
            const gender = profile.gender || '男'
            const fwt = profile.femaleWorkerType || null
            const baseAge = gender === '男' ? 60 : (fwt === 'WORKER' ? 50 : 55)
            const delayInterval = gender === '男' ? 4 : (fwt === 'WORKER' ? 2 : 4)
            const maxDelay = gender === '男' ? 36 : (fwt === 'WORKER' ? 60 : 36)
            const baseRetireDate = new Date(bd)
            baseRetireDate.setFullYear(baseRetireDate.getFullYear() + baseAge)
            const reformStart = new Date(2025, 0, 1)
            const monthsSince = Math.max(0, (baseRetireDate.getFullYear() - reformStart.getFullYear()) * 12 + (baseRetireDate.getMonth() - reformStart.getMonth()))
            const delayMonths = Math.min(maxDelay, Math.floor(monthsSince / delayInterval))
            const retireDate = new Date(baseRetireDate)
            retireDate.setMonth(retireDate.getMonth() + delayMonths)
            return [{ label: '退休日期', value: `${retireDate.getFullYear()}年${retireDate.getMonth() + 1}月${retireDate.getDate()}日` }]
          }
          return [{ label: '距退休', value: `${profile.retirementDaysLeft}天` }]
      })()
      : []),
    ...(profile.status !== 'ACTIVE' && profile.terminations && profile.terminations.length > 0
      ? [{ label: '离职日期', value: profile.terminations
          .map((t: any) => t.terminationDate?.toString().slice(0, 10))
          .filter(Boolean)
          .sort()
          .reverse()[0] || '未记录' }]
      : []),
  ]
  const salaryFields = [
    { label: '月工资', value: `¥${fmt(profile.monthlySalary)}` },
    { label: '紧急联系人', value: profile.emergencyContact || '未填写' },
    { label: '紧急联系电话', value: profile.emergencyPhone || '未填写' },
    { label: '住址', value: profile.address || '未填写' },
    { label: '开户行', value: profile.bankName || '未填写' },
    { label: '银行账号', value: profile.bankAccount || '未填写' },
  ]
  const special = [
    { label: '孕期', value: profile.isPregnant },
    { label: '医疗期', value: profile.isInMedicalPeriod },
    { label: '工伤', value: profile.isWorkInjured },
  ]
  return (
    <Card>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-xs font-medium">基本信息</h2>
        {!editing ? (
          <Button size="sm" variant="secondary" onClick={() => setEditing(true)}>编辑</Button>
        ) : (
          <div className="flex gap-2">
            <Button size="sm" onClick={handleSave} disabled={updateMutation.isPending}>
              {updateMutation.isPending ? '保存中...' : '保存'}
            </Button>
            <Button size="sm" variant="secondary" onClick={() => setEditing(false)}>取消</Button>
          </div>
        )}
      </div>
      {!editing ? (
        <div className="space-y-4">
          <div>
            <h3 className="text-xs font-medium text-gray-600 mb-2">个人信息</h3>
            <div className="grid md:grid-cols-3 gap-x-6 gap-y-3">
              {personalFields.map((f) => (
                <div key={f.label} className="flex justify-between border-b pb-1.5 text-xs">
                  <span className="text-gray-500 shrink-0">{f.label}</span>
                  <span className="font-medium text-right truncate ml-2">{f.value}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="pt-3 border-t">
            <h3 className="text-xs font-medium text-gray-600 mb-2">薪酬与银行</h3>
            <div className="grid md:grid-cols-3 gap-x-6 gap-y-3">
              {salaryFields.map((f) => (
                <div key={f.label} className="flex justify-between border-b pb-1.5 text-xs">
                  <span className="text-gray-500 shrink-0">{f.label}</span>
                  <span className="font-medium text-right truncate ml-2">{f.value}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      ) : (
        <div className="grid md:grid-cols-2 gap-3">
          <div><Label>姓名（不可编辑）</Label><Input value={profile.name} disabled /></div>
          <div><Label>身份证号（不可编辑）</Label><Input value={profile.idCardNumber || ''} disabled /></div>
          <div><Label>部门</Label><Input value={form.department} onChange={(e) => setForm({ ...form, department: e.target.value })} /></div>
          <div><Label>性别</Label><Select value={form.gender} onChange={(e) => setForm({ ...form, gender: e.target.value as '男' | '女' })}><option value="男">男</option><option value="女">女</option></Select></div>
          {form.gender === '女' && (
            <div><Label>女性岗位类型</Label><Select value={form.femaleWorkerType} onChange={(e) => setForm({ ...form, femaleWorkerType: e.target.value as '' | 'CADRE' | 'WORKER' })}><option value="">未选择</option><option value="CADRE">干部/管理岗</option><option value="WORKER">工人/操作岗</option></Select></div>
          )}
          <div><Label>手机号</Label><Input value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="选填" maxLength={11} /></div>
          <div><Label>入职日期</Label><Input type="date" value={form.hireDate} onChange={(e) => setForm({ ...form, hireDate: e.target.value })} /></div>
          <div><Label>月工资</Label><Input type="number" value={form.monthlySalary} onChange={(e) => setForm({ ...form, monthlySalary: Number(e.target.value) })} /></div>
          <div><Label>紧急联系人</Label><Input value={form.emergencyContact} onChange={(e) => setForm({ ...form, emergencyContact: e.target.value })} placeholder="选填" /></div>
          <div><Label>紧急联系电话</Label><Input value={form.emergencyPhone} onChange={(e) => setForm({ ...form, emergencyPhone: e.target.value })} placeholder="选填" /></div>
          <div className="md:col-span-2"><Label>住址</Label><Input value={form.address} onChange={(e) => setForm({ ...form, address: e.target.value })} placeholder="选填" /></div>
          <div><Label>开户行</Label><Input value={form.bankName} onChange={(e) => setForm({ ...form, bankName: e.target.value })} placeholder="选填" /></div>
          <div><Label>银行账号</Label><Input value={form.bankAccount} onChange={(e) => setForm({ ...form, bankAccount: e.target.value })} placeholder="选填" /></div>
        </div>
      )}

      {/* 薪税信息 */}
      <div className="mt-4 pt-4 border-t">
        <h3 className="text-xs font-medium text-gray-600 mb-3">薪税信息</h3>
        {!editing ? (
          <div className="grid md:grid-cols-4 gap-4">
            <div className="flex justify-between border-b pb-2 text-xs">
              <span className="text-gray-500">参保城市</span>
              <span className="font-medium">{profile.city || '未设置'}</span>
            </div>
            <div className="flex justify-between border-b pb-2 text-xs">
              <span className="text-gray-500">社保缴费基数</span>
              <span className="font-medium">{profile.socialInsBase ? `¥${fmt(profile.socialInsBase)}` : '未设置'}</span>
            </div>
            <div className="flex justify-between border-b pb-2 text-xs">
              <span className="text-gray-500">公积金缴费基数</span>
              <span className="font-medium">{profile.housingFundBase ? `¥${fmt(profile.housingFundBase)}` : '未设置'}</span>
            </div>
            <div className="flex justify-between border-b pb-2 text-xs">
              <span className="text-gray-500">专项附加扣除</span>
              <span className="font-medium">{profile.specialDeduction ? `¥${fmt(profile.specialDeduction)}/月` : '¥0.00/月'}</span>
            </div>
          </div>
        ) : (
          <div className="grid md:grid-cols-4 gap-4">
            <div>
              <Label>参保城市</Label>
              <Input placeholder="如 北京" value={form.city || ''} onChange={(e) => setForm({ ...form, city: e.target.value })} />
            </div>
            <div>
              <Label>社保缴费基数</Label>
              <Input type="number" placeholder="按人核定" value={form.socialInsBase} onChange={(e) => setForm({ ...form, socialInsBase: e.target.value })} />
            </div>
            <div>
              <Label>公积金缴费基数</Label>
              <Input type="number" placeholder="按人核定" value={form.housingFundBase} onChange={(e) => setForm({ ...form, housingFundBase: e.target.value })} />
            </div>
            <div>
              <Label>专项附加扣除（元/月）</Label>
              <Input type="number" placeholder="子女教育、赡养老人等" value={form.specialDeduction} onChange={(e) => setForm({ ...form, specialDeduction: Number(e.target.value) || 0 })} />
            </div>
            {form.city !== (profile.city || '') && (
              <div className="md:col-span-4">
                <Label>参保城市变更原因（必填）</Label>
                <Input placeholder="如：员工从北京调往上海工作" value={form.cityChangeReason} onChange={(e) => setForm({ ...form, cityChangeReason: e.target.value })} />
              </div>
            )}
          </div>
        )}
        <p className="text-xs text-gray-400 mt-2">社保/公积金基数按上年度月均工资核定，每年7月调整。专项附加扣除由员工在portal端填报，无则为0。</p>
      </div>

      {/* 特殊状态 */}
      <div className="mt-4 pt-4 border-t">
        <h3 className="text-xs font-medium text-gray-600 mb-3">特殊状态</h3>
        {!editing ? (
          <div className="flex gap-4">
            {special.map((s) => (
              <span key={s.label} className={`px-3 py-1 rounded text-xs ${s.value ? 'bg-red-50 text-danger' : 'bg-gray-50 text-gray-400'}`}>
                {s.label}：{s.value ? '是' : '否'}
              </span>
            ))}
          </div>
        ) : (
          <div className="flex gap-4">
            <label className="flex items-center gap-1.5 text-xs">
              <input type="checkbox" checked={form.isPregnant} onChange={(e) => setForm({ ...form, isPregnant: e.target.checked })} />
              孕期/哺乳期
            </label>
            <label className="flex items-center gap-1.5 text-xs">
              <input type="checkbox" checked={form.isInMedicalPeriod} onChange={(e) => setForm({ ...form, isInMedicalPeriod: e.target.checked })} />
              医疗期
            </label>
            <label className="flex items-center gap-1.5 text-xs">
              <input type="checkbox" checked={form.isWorkInjured} onChange={(e) => setForm({ ...form, isWorkInjured: e.target.checked })} />
              工伤
            </label>
          </div>
        )}
        {(profile.isPregnant || profile.isInMedicalPeriod || profile.isWorkInjured) && !editing && (
          <p className="text-xs text-amber-600 mt-2">⚠️ 该员工处于特殊保护期，解聘操作将触发法律风险预警</p>
        )}
      </div>

      {/* 员工端二维码 */}
      {!editing && profile.phone && (
        <div className="mt-4 pt-4 border-t">
          <div className="flex items-center justify-between mb-3">
            <h3 className="text-xs font-medium text-gray-600">员工端入口</h3>
            <Button size="sm" variant="secondary" onClick={() => {
              const url = `${window.location.origin}/portal/login`
              navigator.clipboard?.writeText(url)
            }}>
              复制链接
            </Button>
          </div>
          <div className="flex items-center gap-4">
            <div className="bg-white p-3 rounded-lg border">
              <QRCodeSVG
                value={`${window.location.origin}/portal/login`}
                size={120}
                level="M"
              />
            </div>
            <div className="text-xs text-gray-500 space-y-1">
              <p>员工扫码进入员工端，使用手机号登录</p>
              <p>可查看工资条、合同信息、确认签署</p>
              <p className="text-gray-400">链接：{window.location.origin}/portal/login</p>
            </div>
          </div>
        </div>
      )}

      {/* 附件管理 */}
      <div className="mt-4 pt-4 border-t">
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-xs font-medium text-gray-600">附件管理（{attachments?.length || 0}个）</h3>
          {!editing && (
            <div className="flex gap-2 items-center">
              <Select value={fileType} onChange={(e) => setFileType(e.target.value as any)} className="text-xs !w-28">
                <option value="ID_CARD">身份证</option><option value="BANK_CARD">银行卡</option><option value="EDUCATION">学历证书</option><option value="OTHER">其他</option>
              </Select>
              <input ref={fileInputRef} type="file" className="hidden" onChange={handleFileUpload} />
              <Button size="sm" variant="secondary" onClick={() => fileInputRef.current?.click()} disabled={addAttachmentMutation.isPending} className="shrink-0 whitespace-nowrap">
                {addAttachmentMutation.isPending ? '上传中...' : '上传附件'}
              </Button>
            </div>
          )}
        </div>
        {!editing && attachments?.length ? (
          <div className="space-y-1.5">
            {attachments.map((att) => (
              <div key={att.id} className="flex items-center justify-between bg-gray-50 rounded p-2 text-xs hover:bg-gray-100">
                <div className="flex items-center gap-2 min-w-0">
                  <Paperclip className="w-3.5 h-3.5 text-gray-400 shrink-0" />
                  <div className="min-w-0">
                    <div className="truncate font-medium text-gray-700">{att.fileName}</div>
                    <div className="flex items-center gap-2 mt-0.5">
                      <span className={`px-1.5 py-0.5 rounded text-xs ${fileTypeColors[att.fileType] || 'bg-gray-100 text-gray-500'}`}>{fileTypeLabels[att.fileType] || att.fileType}</span>
                      <span className="text-gray-400">{formatSize(att.fileSize)}</span>
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-1.5 shrink-0 ml-2">
                  <button onClick={() => window.open(att.fileUrl, '_blank')} className="text-gray-400 hover:text-blue-600" title="查看">
                    <Eye className="w-3.5 h-3.5" />
                  </button>
                  <a href={att.fileUrl} download={att.fileName} className="text-gray-400 hover:text-blue-600" title="下载">
                    <Download className="w-3.5 h-3.5" />
                  </a>
                  <button onClick={() => deleteAttachmentMutation.mutate(att.id)} className="text-gray-300 hover:text-danger" title="删除">
                    <Trash2 className="w-3.5 h-3.5" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        ) : !editing ? <div className="text-gray-400 text-xs text-center py-3">暂无附件</div> : null}
      </div>
    </Card>
  )
}
