import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { FileText, AlertCircle, Check, RefreshCw, Calendar, Briefcase, Clock, ShieldCheck, FileSignature } from 'lucide-react'
import { portalApi } from '../../lib/api-services'
import Card from '../../components/ui/Card'
import Button from '../../components/ui/Button'
import EmptyState from '../../components/ui/EmptyState'

/** 金额格式化：保留两位小数 + 千分位 */
const fmt = (n: number) => (n || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })

const contractTypeMap: Record<string, string> = {
  FIXED: '固定期限劳动合同',
  UNFIXED: '无固定期限劳动合同',
  LABOR: '劳务协议',
  INTERNSHIP: '实习协议',
  PARTTIME: '兼职协议',
  OUTSOURCING: '业务外包',
  UNSIGNED: '未签订',
}

export default function MyContract() {
  const [resending, setResending] = useState(false)
  const [resendMsg, setResendMsg] = useState('')

  const { data, isLoading } = useQuery<any>({
    queryKey: ['my-contract'],
    queryFn: async () => {
      return await portalApi.contract()
    },
  })

  const contract = data

  const daysToExpire = contract?.endDate
    ? Math.floor((new Date(contract.endDate).getTime() - Date.now()) / (1000 * 60 * 60 * 24))
    : null

  const isConfirmed = contract?.attachmentName?.startsWith('confirmed:')

  const handleResend = async () => {
    setResending(true)
    setResendMsg('')
    try {
      const data = await portalApi.resendContractConfirm(contract?.id) as any
      setResendMsg(data?.message || '重发成功')
    } catch (err: any) {
      setResendMsg(err.response?.data?.error?.message || '重发失败')
    } finally {
      setResending(false)
    }
  }

  return (
    <div className="space-y-4">
      {/* 页面标题 */}
      <h1 className="text-lg font-bold text-gray-900">我的劳动合同</h1>

      {isLoading ? (
        <Card className="p-6">
          <div className="animate-pulse space-y-3">
            <div className="h-6 bg-gray-100 rounded w-1/2" />
            <div className="h-4 bg-gray-100 rounded w-full" />
            <div className="h-4 bg-gray-100 rounded w-2/3" />
            <div className="h-10 bg-gray-100 rounded-lg w-full" />
          </div>
        </Card>
      ) : !contract ? (
        <Card className="p-6">
          <EmptyState title="暂无合同" description="HR 尚未录入您的合同信息" />
        </Card>
      ) : (
        <>
          {/* 到期提醒横幅 */}
          {daysToExpire !== null && daysToExpire <= 30 && daysToExpire >= 0 && (
            <div className="flex items-start gap-2 px-4 py-3 rounded-xl bg-amber-50 text-amber-700 text-sm border border-amber-200">
              <AlertCircle className="w-5 h-5 flex-shrink-0 mt-0.5" />
              <span>您的合同还有 <strong>{daysToExpire}</strong> 天到期，请关注续签事宜</span>
            </div>
          )}

          {/* 合同概览卡片 — 渐变头部 */}
          <div className="rounded-2xl overflow-hidden shadow-sm border border-gray-100">
            {/* 头部 */}
            <div className="bg-gradient-to-br from-indigo-600 to-indigo-700 px-5 py-4 text-white">
              <div className="flex items-center gap-3">
                <div className="w-11 h-11 rounded-xl bg-white/20 flex items-center justify-center flex-shrink-0 backdrop-blur-sm">
                  <FileText className="w-6 h-6" />
                </div>
                <div className="min-w-0 flex-1">
                  <div className="text-base font-bold truncate">
                    {contractTypeMap[contract.contractType] || '劳动合同'}
                  </div>
                  <div className="text-xs text-indigo-100 mt-0.5 flex items-center gap-1.5">
                    {contract.signMethod === 'PAPER' ? (
                      <><FileSignature className="w-3.5 h-3.5" />纸质合同</>
                    ) : (
                      <><ShieldCheck className="w-3.5 h-3.5" />电子合同</>
                    )}
                  </div>
                </div>
                {/* 签署状态徽章 */}
                <div className={`px-2.5 py-1 rounded-full text-xs font-medium flex-shrink-0 ${
                  isConfirmed ? 'bg-green-400/20 text-green-100' : 'bg-amber-400/20 text-amber-100'
                }`}>
                  {isConfirmed ? '已签署' : '待签署'}
                </div>
              </div>
            </div>

            {/* 信息区 */}
            <div className="bg-white px-5 py-4">
              <div className="grid grid-cols-2 gap-x-4 gap-y-4">
                <InfoCell icon={Calendar} label="合同开始" value={contract.startDate ? new Date(contract.startDate).toISOString().slice(0, 10) : '—'} />
                {contract.endDate && (
                  <InfoCell icon={Calendar} label="合同结束" value={new Date(contract.endDate).toISOString().slice(0, 10)} />
                )}
                {contract.contractYears > 0 && (
                  <InfoCell icon={Briefcase} label="合同期限" value={`${contract.contractYears}年`} />
                )}
                {contract.signDate && (
                  <InfoCell icon={Calendar} label="签订日期" value={new Date(contract.signDate).toISOString().slice(0, 10)} />
                )}
                {contract.baseSalary > 0 && (
                  <InfoCell icon={Briefcase} label="基本工资" value={`¥${fmt(Number(contract.baseSalary))}`} />
                )}
                {contract.performanceSalary > 0 && (
                  <InfoCell icon={Briefcase} label="绩效工资" value={`¥${fmt(Number(contract.performanceSalary))}`} />
                )}
                {contract.probationMonths > 0 && (
                  <InfoCell icon={Clock} label="试用期" value={`${contract.probationMonths}个月`} />
                )}
                {contract.probationSalary > 0 && (
                  <InfoCell icon={Briefcase} label="试用期工资" value={`¥${fmt(Number(contract.probationSalary))}`} />
                )}
              </div>
            </div>
          </div>

          {/* 签署确认记录 */}
          <div className="rounded-2xl overflow-hidden shadow-sm border border-gray-100">
            <div className="bg-white px-5 py-4">
              <h3 className="text-sm font-semibold text-gray-900 mb-3 flex items-center gap-2">
                <ShieldCheck className="w-4 h-4 text-primary" />
                签署确认
              </h3>
              {isConfirmed ? (
                <div className="flex items-center gap-3 px-4 py-3 rounded-xl bg-green-50 border border-green-100">
                  <div className="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center flex-shrink-0">
                    <Check className="w-5 h-5 text-green-600" />
                  </div>
                  <div>
                    <div className="text-sm font-medium text-green-700">已确认签署</div>
                    <div className="text-xs text-gray-400">
                      {new Date(contract.attachmentName.slice(10).split('|')[0]).toLocaleString()}
                    </div>
                  </div>
                </div>
              ) : (
                <div className="space-y-3">
                  <div className="flex items-center gap-2 px-4 py-3 rounded-xl bg-amber-50 border border-amber-100">
                    <AlertCircle className="w-4 h-4 text-amber-500 flex-shrink-0" />
                    <span className="text-sm text-amber-700">合同尚未确认签署</span>
                  </div>
                  <Button size="sm" variant="secondary" onClick={handleResend} disabled={resending}>
                    <RefreshCw className={`w-3.5 h-3.5 mr-1 ${resending ? 'animate-spin' : ''}`} />
                    {resending ? '重发中...' : '重发确认链接'}
                  </Button>
                  {resendMsg && <div className="text-xs text-gray-500">{resendMsg}</div>}
                </div>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  )
}

/** 信息单元格 — 图标 + 标签 + 值 的垂直排列 */
function InfoCell({ icon: Icon, label, value }: { icon: any; label: string; value: string }) {
  return (
    <div className="flex flex-col gap-1">
      <div className="flex items-center gap-1.5">
        <Icon className="w-3.5 h-3.5 text-gray-400" />
        <span className="text-xs text-gray-400">{label}</span>
      </div>
      <span className="text-sm font-medium text-gray-800 pl-5">{value}</span>
    </div>
  )
}
