/**
 * 员工端 — 个人资料查看与编辑
 * 员工可查看自己的入职资料，并编辑部分字段（紧急联系人、地址、银行卡、学历等）
 * 数据直接同步到花名册（Employee 表）
 */
import { useState, useEffect, useRef } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { User, Phone, IdCard, MapPin, Banknote, GraduationCap, AlertCircle, Check, Save, Briefcase, Calendar, Paperclip, Trash2, Eye, Upload } 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 { toast } from 'sonner'

export default function MyProfile() {
  const queryClient = useQueryClient()
  const [editing, setEditing] = useState(false)
  const [form, setForm] = useState({
    emergencyContact: '',
    emergencyPhone: '',
    address: '',
    bankAccount: '',
    bankName: '',
    education: '',
    city: '',
  })
  const [deductionForm, setDeductionForm] = useState({
    children: 0,
    elderly: 0,
    housing: 0,
    education: 0,
    infant: 0,
    remark: '',
  })

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

  useEffect(() => {
    if (profile) {
      setForm({
        emergencyContact: profile.emergencyContact || '',
        emergencyPhone: profile.emergencyPhone || '',
        address: profile.address || '',
        bankAccount: profile.bankAccount || '',
        bankName: profile.bankName || '',
        education: profile.education || '',
        city: profile.city || '',
      })
      const d = profile.specialDeductionDetail
      setDeductionForm({
        children: d?.children || 0,
        elderly: d?.elderly || 0,
        housing: d?.housing || 0,
        education: d?.education || 0,
        infant: d?.infant || 0,
        remark: d?.remark || '',
      })
    }
  }, [profile])

  const updateMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => portalApi.updateProfile(data),
    onSuccess: () => {
      toast.success('资料更新成功')
      setEditing(false)
      queryClient.invalidateQueries({ queryKey: ['portal-profile'] })
    },
    onError: (err: any) => {
      toast.error(err?.response?.data?.error?.message || '更新失败')
    },
  })

  const handleSave = () => {
    updateMutation.mutate({ ...form, specialDeductionDetail: deductionForm })
  }

  if (isLoading) {
    return (
      <div className="space-y-4">
        <div className="h-32 bg-gray-100 rounded-xl animate-pulse" />
        <div className="h-48 bg-gray-100 rounded-xl animate-pulse" />
      </div>
    )
  }

  if (!profile) {
    return <Card><div className="text-center py-8 text-gray-400 text-sm">暂无个人资料信息</div></Card>
  }

  const readOnlyFields = [
    { label: '姓名', value: profile.name, icon: User },
    { label: '工号', value: profile.employeeNo || '未填写', icon: Briefcase },
    { label: '性别', value: profile.gender === '男' ? '男' : profile.gender === '女' ? '女' : '未填写', icon: User },
    { label: '出生日期', value: profile.birthDate || '未填写', icon: Calendar },
    { label: '手机号', value: profile.phone || '未填写', icon: Phone },
    { label: '证件号码', value: profile.idCardNo || '未填写', icon: IdCard },
    { label: '部门', value: profile.department || '未填写', icon: Briefcase },
    { label: '岗位', value: profile.position || '未填写', icon: Briefcase },
    ...(profile.gender === '女' ? [{ label: '女性岗位类型', value: profile.femaleWorkerType === 'CADRE' ? '干部/管理岗' : profile.femaleWorkerType === 'WORKER' ? '工人/操作岗' : '未填写', icon: User }] : []),
    { label: '入职日期', value: profile.hireDate || '未填写', icon: Calendar },
  ]

  const educationOptions = ['博士', '硕士', '本科', '大专', '高中', '其他']

  return (
    <div className="space-y-4">
      {/* 只读信息卡片 */}
      <Card>
        <div className="flex items-center gap-2 mb-4">
          <User className="w-4 h-4 text-primary" />
          <h2 className="text-sm font-medium">基本信息</h2>
          <span className="text-xs text-gray-400">（由 HR 维护，如需修改请联系 HR）</span>
        </div>
        <div className="grid grid-cols-2 gap-3">
          {readOnlyFields.map((f) => {
            const Icon = f.icon
            return (
              <div key={f.label} className="flex items-center gap-2 p-2.5 rounded-lg bg-gray-50">
                <Icon className="w-4 h-4 text-gray-400 flex-shrink-0" />
                <div className="min-w-0">
                  <div className="text-xs text-gray-400">{f.label}</div>
                  <div className="text-sm text-gray-700 truncate">{f.value}</div>
                </div>
              </div>
            )
          })}
        </div>
      </Card>

      {/* 可编辑信息卡片 */}
      <Card>
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <AlertCircle className="w-4 h-4 text-primary" />
            <h2 className="text-sm font-medium">入职资料补充</h2>
          </div>
          {!editing ? (
            <Button size="sm" variant="secondary" onClick={() => setEditing(true)}>
              编辑
            </Button>
          ) : (
            <div className="flex gap-2">
              <Button size="sm" variant="secondary" onClick={() => { setEditing(false); }}>
                取消
              </Button>
              <Button size="sm" onClick={handleSave} disabled={updateMutation.isPending}>
                <Save className="w-3.5 h-3.5 mr-1" />
                {updateMutation.isPending ? '保存中...' : '保存'}
              </Button>
            </div>
          )}
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <div>
            <Label>紧急联系人</Label>
            <Input
              value={form.emergencyContact}
              onChange={(e) => setForm({ ...form, emergencyContact: e.target.value })}
              placeholder="请输入紧急联系人姓名"
              disabled={!editing}
            />
          </div>
          <div>
            <Label>紧急联系电话</Label>
            <Input
              type="tel"
              value={form.emergencyPhone}
              onChange={(e) => setForm({ ...form, emergencyPhone: e.target.value })}
              placeholder="请输入紧急联系人电话"
              maxLength={11}
              disabled={!editing}
            />
          </div>
          <div className="md:col-span-2">
            <Label>住址</Label>
            <Input
              value={form.address}
              onChange={(e) => setForm({ ...form, address: e.target.value })}
              placeholder="请输入现住址"
              disabled={!editing}
            />
          </div>
          <div>
            <Label>银行卡号</Label>
            <Input
              value={form.bankAccount}
              onChange={(e) => setForm({ ...form, bankAccount: e.target.value })}
              placeholder="请输入银行卡号"
              disabled={!editing}
            />
          </div>
          <div>
            <Label>开户行</Label>
            <Input
              value={form.bankName}
              onChange={(e) => setForm({ ...form, bankName: e.target.value })}
              placeholder="如：工商银行xx支行"
              disabled={!editing}
            />
          </div>
          <div>
            <Label>学历</Label>
            {editing ? (
              <select
                value={form.education}
                onChange={(e) => setForm({ ...form, education: e.target.value })}
                className="w-full h-10 px-3 rounded-md border border-gray-300 text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              >
                <option value="">请选择</option>
                {educationOptions.map((e) => <option key={e} value={e}>{e}</option>)}
              </select>
            ) : (
              <Input value={form.education || '未填写'} disabled />
            )}
          </div>
          <div>
            <Label>参保城市</Label>
            <Input
              value={form.city}
              onChange={(e) => setForm({ ...form, city: e.target.value })}
              placeholder="如：北京"
              disabled={!editing}
            />
          </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-700">专项附加扣除（元/月）</h3>
            <span className="text-xs text-gray-400">
              合计：¥{((deductionForm.children || 0) + (deductionForm.elderly || 0) + (deductionForm.housing || 0) + (deductionForm.education || 0) + (deductionForm.infant || 0)).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}
              {profile.specialDeductionDetail?.month && `（${profile.specialDeductionDetail.month}月记录）`}
            </span>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
            <div>
              <Label>子女教育</Label>
              <Input
                type="number"
                value={deductionForm.children}
                onChange={(e) => setDeductionForm({ ...deductionForm, children: Number(e.target.value) || 0 })}
                placeholder="0"
                disabled={!editing}
              />
            </div>
            <div>
              <Label>赡养老人</Label>
              <Input
                type="number"
                value={deductionForm.elderly}
                onChange={(e) => setDeductionForm({ ...deductionForm, elderly: Number(e.target.value) || 0 })}
                placeholder="0"
                disabled={!editing}
              />
            </div>
            <div>
              <Label>住房贷款/租金</Label>
              <Input
                type="number"
                value={deductionForm.housing}
                onChange={(e) => setDeductionForm({ ...deductionForm, housing: Number(e.target.value) || 0 })}
                placeholder="0"
                disabled={!editing}
              />
            </div>
            <div>
              <Label>继续教育</Label>
              <Input
                type="number"
                value={deductionForm.education}
                onChange={(e) => setDeductionForm({ ...deductionForm, education: Number(e.target.value) || 0 })}
                placeholder="0"
                disabled={!editing}
              />
            </div>
            <div>
              <Label>婴幼儿照护</Label>
              <Input
                type="number"
                value={deductionForm.infant}
                onChange={(e) => setDeductionForm({ ...deductionForm, infant: Number(e.target.value) || 0 })}
                placeholder="0"
                disabled={!editing}
              />
            </div>
            <div className="md:col-span-3">
              <Label>备注</Label>
              <Input
                value={deductionForm.remark}
                onChange={(e) => setDeductionForm({ ...deductionForm, remark: e.target.value })}
                placeholder="可选备注信息"
                disabled={!editing}
              />
            </div>
          </div>
        </div>

        {editing && (
          <div className="mt-4 p-3 rounded-lg bg-blue-50 text-blue-600 text-xs flex items-center gap-2">
            <Check className="w-3.5 h-3.5 flex-shrink-0" />
            保存后资料将同步到花名册，HR 可在管理端查看
          </div>
        )}
      </Card>

      {/* 附件资料卡片 */}
      <AttachmentCard />
    </div>
  )
}

/** 附件资料卡片 — 员工可上传/查看/删除自己的附件 */
function AttachmentCard() {
  const queryClient = useQueryClient()
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [fileType, setFileType] = useState<'ID_CARD' | 'BANK_CARD' | 'EDUCATION' | 'CERTIFICATE' | 'CONTRACT' | 'PHOTO' | 'OTHER'>('ID_CARD')

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

  const addMutation = useMutation({
    mutationFn: (data: Record<string, unknown>) => portalApi.addAttachment(data),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['portal-attachments'] }),
    onError: (err: any) => toast.error(err?.response?.data?.error?.message || '上传失败'),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => portalApi.removeAttachment(id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['portal-attachments'] }),
  })

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    const allowedExts = ['.pdf', '.jpg', '.jpeg', '.png', '.heic', '.gif', '.bmp', '.webp', '.doc', '.docx', '.xls', '.xlsx']
    const ext = file.name.toLowerCase().substring(file.name.lastIndexOf('.'))
    if (!allowedExts.includes(ext)) {
      toast.error('不支持的文件格式')
      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
      addMutation.mutate({ fileName: file.name, fileType, fileUrl, fileSize: file.size })
    }
    reader.readAsDataURL(file)
  }

  const fileTypeLabels: Record<string, string> = {
    ID_CARD: '身份证', BANK_CARD: '银行卡', EDUCATION: '学历证书',
    CERTIFICATE: '职业资格证书', CONTRACT: '合同扫描件', PHOTO: '员工照片', 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', CERTIFICATE: 'bg-purple-50 text-purple-600',
    CONTRACT: 'bg-cyan-50 text-cyan-600', PHOTO: 'bg-pink-50 text-pink-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`
  }

  return (
    <Card>
      <div className="flex items-center gap-2 mb-4">
        <Paperclip className="w-4 h-4 text-primary" />
        <h2 className="text-sm font-medium">附件资料（{attachments.length}个）</h2>
      </div>

      <div className="flex gap-2 items-center mb-3">
        <select
          value={fileType}
          onChange={(e) => setFileType(e.target.value as any)}
          className="h-9 px-2 rounded-md border border-gray-300 text-xs"
        >
          <option value="ID_CARD">身份证</option>
          <option value="BANK_CARD">银行卡</option>
          <option value="EDUCATION">学历证书</option>
          <option value="CERTIFICATE">职业资格证书</option>
          <option value="CONTRACT">合同扫描件</option>
          <option value="PHOTO">员工照片</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={addMutation.isPending}>
          <Upload className="w-3.5 h-3.5 mr-1" />
          {addMutation.isPending ? '上传中...' : '上传附件'}
        </Button>
      </div>

      {isLoading ? (
        <div className="text-center py-4 text-gray-400 text-xs">加载中...</div>
      ) : attachments.length > 0 ? (
        <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>
                <button
                  onClick={() => {
                    if (confirm(`确认删除「${att.fileName}」？`)) deleteMutation.mutate(att.id)
                  }}
                  className="text-gray-300 hover:text-red-500"
                  title="删除"
                >
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-gray-400 text-xs text-center py-4">暂无附件，请点击上方上传</div>
      )}
    </Card>
  )
}
