import { useState, useRef } from 'react'
import { toast } from 'sonner'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Upload, Download, X, ChevronRight } from 'lucide-react'
import { socialInsuranceApi } from '../../lib/api-services'
import { useAuthStore } from '../../store/authStore'
import Card from '../../components/ui/Card'
import Button from '../../components/ui/Button'
import { Input, Label } from '../../components/ui/Input'
import PageGuide from '../../components/ui/PageGuide'

const fmt = (n: number) => (n || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })

/** 专项附加扣除按月录入组件 */
export default function SpecialDeductionTab({ month, setMonth }: { month: string; setMonth: (m: string) => void }) {
  const queryClient = useQueryClient()
  const [editing, setEditing] = useState<string | null>(null)
  const [editForm, setEditForm] = useState<any>(null)
  const [showImport, setShowImport] = useState(false)
  const [importFile, setImportFile] = useState<File | null>(null)
  const [importResult, setImportResult] = useState<any>(null)
  const [importing, setImporting] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [unrecordedSearch, setUnrecordedSearch] = useState('')
  const [showUnrecorded, setShowUnrecorded] = useState(false)
  const [unrecordedPage, setUnrecordedPage] = useState(1)

  const { data: records = [], isLoading } = useQuery<any[]>({
    queryKey: ['special-deduction', month],
    queryFn: async () => {
      return await socialInsuranceApi.specialDeductionBatch(month)
    },
  })

  const { data: employees = [] } = useQuery<any[]>({
    queryKey: ['active-social-employees', month],
    queryFn: async () => {
      const res = await socialInsuranceApi.activeDeclaration(month) as any
      return (res?.items || []).map((item: any) => ({
        id: item.employeeId,
        name: item.name,
        department: item.department,
      }))
    },
  })

  const prevMonth = (() => {
    const [y, m] = month.split('-').map(Number)
    const d = new Date(y, m - 2, 1)
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`
  })()
  const { data: prevRecords = [] } = useQuery<any[]>({
    queryKey: ['special-deduction', prevMonth],
    queryFn: async () => {
      return await socialInsuranceApi.specialDeductionBatch(prevMonth)
    },
  })

  const saveMutation = useMutation({
    mutationFn: (data: any) => socialInsuranceApi.saveSpecialDeduction({ ...data, month }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['special-deduction'] })
      setEditing(null)
      setEditForm(null)
    },
  })

  const recordMap = new Map(records.map((r: any) => [r.employeeId, r]))
  const unrecordedAll = employees.filter((e: any) => !recordMap.has(e.id))
  const filteredUnrecorded = unrecordedSearch
    ? unrecordedAll.filter((e: any) => e.name.includes(unrecordedSearch) || (e.department || '').includes(unrecordedSearch))
    : unrecordedAll
  const unrecordedPageSize = 20
  const unrecordedTotalPages = Math.ceil(filteredUnrecorded.length / unrecordedPageSize)
  const pagedUnrecorded = filteredUnrecorded.slice((unrecordedPage - 1) * unrecordedPageSize, unrecordedPage * unrecordedPageSize)

  const startEdit = (empId: string, existing?: any) => {
    setEditing(empId)
    setEditForm(existing ? {
      children: existing.children,
      elderly: existing.elderly,
      housing: existing.housing,
      education: existing.education,
      infant: existing.infant,
      remark: existing.remark,
    } : { children: 0, elderly: 0, housing: 0, education: 0, infant: 0, remark: '' })
  }

  const batchCopyMutation = useMutation({
    mutationFn: async () => {
      let copied = 0
      for (const prev of prevRecords) {
        await socialInsuranceApi.saveSpecialDeduction({
          employeeId: prev.employeeId,
          month,
          children: prev.children || 0,
          elderly: prev.elderly || 0,
          housing: prev.housing || 0,
          education: prev.education || 0,
          infant: prev.infant || 0,
          remark: prev.remark || '',
        })
        copied++
      }
      return copied
    },
    onSuccess: (copied: number) => {
      queryClient.invalidateQueries({ queryKey: ['special-deduction'] })
      if (copied > 0) {
        toast.success(`已复制 ${copied} 条 ${prevMonth} 的扣除数据到 ${month}`)
      } else {
        toast.info(`${prevMonth} 无可复制的扣除数据`)
      }
    },
    onError: () => toast.error('复制上月数据失败'),
  })

  const calcTotal = (f: any) => (f.children || 0) + (f.elderly || 0) + (f.housing || 0) + (f.education || 0) + (f.infant || 0)

  return (
    <Card>
      <div className="mb-3">
        <PageGuide>
          专项附加扣除用于个税计算，包括子女教育、赡养老人、住房贷款/租金、继续教育、婴幼儿照护五项。可逐月逐人录入，或使用「复制上月」快速填充。仅社保在保人员需要填报。
        </PageGuide>
      </div>
      <div className="flex items-center justify-between mb-3">
        <h2 className="text-sm font-medium">专项附加扣除 — {month}</h2>
        <div className="flex items-center gap-2">
          <Button
            size="sm"
            variant="secondary"
            onClick={() => batchCopyMutation.mutate()}
            disabled={batchCopyMutation.isPending || prevRecords.length === 0}
          >
            {batchCopyMutation.isPending ? '复制中...' : `复制上月(${prevMonth})`}
          </Button>
          <Button
            size="sm"
            variant="secondary"
            onClick={() => setShowImport(true)}
          >
            <Upload className="w-3.5 h-3.5 mr-1" />批量导入
          </Button>
          <Input type="month" value={month} onChange={(e) => setMonth(e.target.value)} className="!w-32" />
        </div>
      </div>

      {isLoading ? (
        <div className="text-center py-8 text-gray-500">加载中...</div>
      ) : (
        <div className="space-y-3">
          {records.length > 0 && (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b text-left text-xs text-gray-500">
                    <th className="py-2 font-medium">姓名</th>
                    <th className="py-2 font-medium">部门</th>
                    <th className="py-2 font-medium text-right">子女教育</th>
                    <th className="py-2 font-medium text-right">赡养老人</th>
                    <th className="py-2 font-medium text-right">住房</th>
                    <th className="py-2 font-medium text-right">继续教育</th>
                    <th className="py-2 font-medium text-right">婴幼儿照护</th>
                    <th className="py-2 font-medium text-right">合计</th>
                    <th className="py-2 font-medium">备注</th>
                    <th className="py-2"></th>
                  </tr>
                </thead>
                <tbody>
                  {records.map((r: any) => (
                    <tr key={r.id} className="border-b last:border-0 hover:bg-gray-50">
                      {editing === r.employeeId ? (
                        <>
                          <td className="py-1.5">
                            <div className="flex flex-col gap-0.5">
                              <span>{r.employee?.name}</span>
                              {r.employee?.idCardNumber && <span className="text-gray-400 text-[11px] font-mono">{r.employee.idCardNumber}</span>}
                            </div>
                          </td>
                          <td className="py-1.5 text-gray-500">{r.employee?.department}</td>
                          <td className="py-1"><Input type="number" className="!w-20 !h-8 text-right" value={editForm.children} onChange={(e) => setEditForm({ ...editForm, children: Number(e.target.value) })} /></td>
                          <td className="py-1"><Input type="number" className="!w-20 !h-8 text-right" value={editForm.elderly} onChange={(e) => setEditForm({ ...editForm, elderly: Number(e.target.value) })} /></td>
                          <td className="py-1"><Input type="number" className="!w-20 !h-8 text-right" value={editForm.housing} onChange={(e) => setEditForm({ ...editForm, housing: Number(e.target.value) })} /></td>
                          <td className="py-1"><Input type="number" className="!w-20 !h-8 text-right" value={editForm.education} onChange={(e) => setEditForm({ ...editForm, education: Number(e.target.value) })} /></td>
                          <td className="py-1"><Input type="number" className="!w-20 !h-8 text-right" value={editForm.infant} onChange={(e) => setEditForm({ ...editForm, infant: Number(e.target.value) })} /></td>
                          <td className="py-1.5 text-right font-medium text-primary">¥{fmt(calcTotal(editForm))}</td>
                          <td className="py-1"><Input className="!w-24 !h-8" value={editForm.remark || ''} onChange={(e) => setEditForm({ ...editForm, remark: e.target.value })} /></td>
                          <td className="py-1">
                            <div className="flex gap-1">
                              <Button size="sm" className="!h-7 !px-2" onClick={() => saveMutation.mutate({ employeeId: r.employeeId, ...editForm })} disabled={saveMutation.isPending}>保存</Button>
                              <Button size="sm" variant="secondary" className="!h-7 !px-2" onClick={() => { setEditing(null); setEditForm(null) }}>取消</Button>
                            </div>
                          </td>
                        </>
                      ) : (
                        <>
                          <td className="py-1.5">
                            <div className="flex flex-col gap-0.5">
                              <span>{r.employee?.name}</span>
                              {r.employee?.idCardNumber && <span className="text-gray-400 text-[11px] font-mono">{r.employee.idCardNumber}</span>}
                            </div>
                          </td>
                          <td className="py-1.5 text-gray-500">{r.employee?.department}</td>
                          <td className="py-1.5 text-right">{r.children > 0 ? `¥${fmt(r.children)}` : '-'}</td>
                          <td className="py-1.5 text-right">{r.elderly > 0 ? `¥${fmt(r.elderly)}` : '-'}</td>
                          <td className="py-1.5 text-right">{r.housing > 0 ? `¥${fmt(r.housing)}` : '-'}</td>
                          <td className="py-1.5 text-right">{r.education > 0 ? `¥${fmt(r.education)}` : '-'}</td>
                          <td className="py-1.5 text-right">{r.infant > 0 ? `¥${fmt(r.infant)}` : '-'}</td>
                          <td className="py-1.5 text-right font-medium text-primary">¥{fmt(r.amount)}</td>
                          <td className="py-1.5 text-gray-400 text-xs">{r.remark || '-'}</td>
                          <td className="py-1.5"><button className="text-xs text-primary hover:underline" onClick={() => startEdit(r.employeeId, r)}>编辑</button></td>
                        </>
                      )}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}

          {unrecordedAll.length > 0 && (
            <div className="border-t pt-3">
              <button
                className="flex items-center gap-1 text-xs font-medium text-gray-500 mb-2"
                onClick={() => setShowUnrecorded(!showUnrecorded)}
              >
                <ChevronRight className={`w-3 h-3 transition-transform ${showUnrecorded ? 'rotate-90' : ''}`} />
                未录入员工（{unrecordedAll.length}人）
              </button>
              {showUnrecorded && (
                <>
                  <Input
                    placeholder="搜索姓名或部门..."
                    value={unrecordedSearch}
                    onChange={(e) => { setUnrecordedSearch(e.target.value); setUnrecordedPage(1) }}
                    className="mb-2 !h-8 !text-xs"
                  />
                  <div className="flex flex-wrap gap-2">
                    {pagedUnrecorded.map((e: any) => (
                      <button
                        key={e.id}
                        className="px-2 py-1 rounded-md border border-gray-200 text-xs text-gray-600 hover:border-primary hover:text-primary"
                        onClick={() => startEdit(e.id)}
                      >
                        {e.name}（{e.department}）
                      </button>
                    ))}
                  </div>
                  {unrecordedTotalPages > 1 && (
                    <div className="flex items-center justify-center gap-2 mt-2">
                      <button
                        onClick={() => setUnrecordedPage(p => Math.max(1, p - 1))}
                        disabled={unrecordedPage === 1}
                        className="text-xs text-gray-400 disabled:opacity-30"
                      >上一页</button>
                      <span className="text-xs text-gray-400">{unrecordedPage}/{unrecordedTotalPages}</span>
                      <button
                        onClick={() => setUnrecordedPage(p => Math.min(unrecordedTotalPages, p + 1))}
                        disabled={unrecordedPage === unrecordedTotalPages}
                        className="text-xs text-gray-400 disabled:opacity-30"
                      >下一页</button>
                    </div>
                  )}
                </>
              )}
            </div>
          )}

          {editing && !recordMap.has(editing) && (
            <div className="border rounded-md p-3 bg-gray-50 space-y-2">
              <h3 className="text-xs font-medium">新增专项附加扣除 — {employees.find((e: any) => e.id === editing)?.name}</h3>
              <div className="grid grid-cols-5 gap-2">
                <div><Label>子女教育</Label><Input type="number" value={editForm.children} onChange={(e) => setEditForm({ ...editForm, children: Number(e.target.value) })} /></div>
                <div><Label>赡养老人</Label><Input type="number" value={editForm.elderly} onChange={(e) => setEditForm({ ...editForm, elderly: Number(e.target.value) })} /></div>
                <div><Label>住房</Label><Input type="number" value={editForm.housing} onChange={(e) => setEditForm({ ...editForm, housing: Number(e.target.value) })} /></div>
                <div><Label>继续教育</Label><Input type="number" value={editForm.education} onChange={(e) => setEditForm({ ...editForm, education: Number(e.target.value) })} /></div>
                <div><Label>婴幼儿照护</Label><Input type="number" value={editForm.infant} onChange={(e) => setEditForm({ ...editForm, infant: Number(e.target.value) })} /></div>
              </div>
              <div className="flex items-center gap-3">
                <div className="flex-1"><Label>备注</Label><Input value={editForm.remark} onChange={(e) => setEditForm({ ...editForm, remark: e.target.value })} /></div>
                <div className="text-sm text-gray-500 pt-5">合计：<span className="font-medium text-primary">¥{fmt(calcTotal(editForm))}</span></div>
              </div>
              <div className="flex gap-2">
                <Button size="sm" onClick={() => saveMutation.mutate({ employeeId: editing, ...editForm })} disabled={saveMutation.isPending}>保存</Button>
                <Button size="sm" variant="secondary" onClick={() => { setEditing(null); setEditForm(null) }}>取消</Button>
              </div>
            </div>
          )}

          {records.length === 0 && unrecordedAll.length === 0 && (
            <div className="text-center py-8 text-gray-400 text-sm">暂无员工数据</div>
          )}
        </div>
      )}

      {showImport && (
        <div className="fixed inset-0 bg-black/30 flex items-center justify-center z-50 p-4" onClick={() => setShowImport(false)}>
          <Card className="max-w-lg w-full" >
            <div onClick={(e) => e.stopPropagation()} className="p-4">
              <div className="flex items-center justify-between mb-3">
                <h2 className="text-sm font-medium">批量导入专项附加扣除 — {month}</h2>
                <button onClick={() => { setShowImport(false); setImportFile(null); setImportResult(null) }} className="text-gray-400 hover:text-gray-600"><X className="w-4 h-4" /></button>
              </div>

              <div className="space-y-3">
                <div className="flex gap-2">
                  <Button size="sm" variant="secondary" onClick={async () => {
                    try {
                      const token = useAuthStore.getState().accessToken
                      const baseURL = import.meta.env.DEV ? 'http://localhost:3000/api/v1' : '/api/v1'
                      const res = await fetch(`${baseURL}/import/special-deduction/template`, {
                        headers: token ? { Authorization: `Bearer ${token}` } : {},
                      })
                      const blob = await res.blob()
                      const url = URL.createObjectURL(blob)
                      const a = document.createElement('a')
                      a.href = url
                      a.download = '专项附加扣除导入模板.xlsx'
                      a.click()
                      URL.revokeObjectURL(url)
                    } catch { toast.error('下载模板失败') }
                  }}>
                    <Download className="w-3.5 h-3.5 mr-1" />下载模板
                  </Button>
                </div>

                <div className="border-2 border-dashed border-gray-200 rounded-lg p-6 text-center">
                  <input ref={fileInputRef} type="file" accept=".xlsx,.xls" className="hidden" id="special-deduction-import-file" onChange={(e) => { setImportFile(e.target.files?.[0] || null); setImportResult(null) }} />
                  <label htmlFor="special-deduction-import-file" className="cursor-pointer text-xs text-primary hover:underline">
                    {importFile ? importFile.name : '点击选择 Excel 文件'}
                  </label>
                </div>

                {importResult && (
                  <div className="px-3 py-2 rounded-md bg-green-50 text-green-700 text-xs space-y-1">
                    <div className="font-medium">导入完成</div>
                    <div>成功 {importResult.updated} 条，跳过 {importResult.skipped} 条，共 {importResult.total} 条</div>
                    {importResult.errors?.length > 0 && (
                      <div className="mt-1 pt-1 border-t border-green-200">
                        {importResult.errors.slice(0, 5).map((e: string, i: number) => <div key={i} className="text-amber-600">{e}</div>)}
                        {importResult.errors.length > 5 && <div className="text-amber-600">...还有 {importResult.errors.length - 5} 条</div>}
                      </div>
                    )}
                  </div>
                )}

                <div className="flex justify-end gap-2">
                  <Button variant="secondary" size="sm" onClick={() => { setShowImport(false); setImportFile(null); setImportResult(null) }}>取消</Button>
                  <Button size="sm" onClick={async () => {
                    if (!importFile) return toast.error('请选择文件')
                    setImporting(true)
                    setImportResult(null)
                    try {
                      const token = useAuthStore.getState().accessToken
                      const formData = new FormData()
                      formData.append('file', importFile)
                      formData.append('month', month)
                      const res = await fetch('/api/v1/import/special-deduction', {
                        method: 'POST',
                        headers: token ? { Authorization: `Bearer ${token}` } : {},
                        body: formData,
                      })
                      const data = await res.json()
                      if (!data.success) { toast.error(data.error?.message || '导入失败') }
                      else {
                        setImportResult(data.data)
                        queryClient.invalidateQueries({ queryKey: ['special-deduction'] })
                        toast.success(`导入完成：成功 ${data.data.updated} 条`)
                      }
                    } catch (e: any) { toast.error(e?.message || '导入失败') }
                    finally { setImporting(false) }
                  }} disabled={!importFile || importing}>{importing ? '导入中...' : '开始导入'}</Button>
                </div>
              </div>
            </div>
          </Card>
        </div>
      )}
    </Card>
  )
}
