import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { FileText, AlertCircle, Check, RefreshCw, Calendar, Briefcase, Clock } 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 })

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">
              <AlertCircle className="w-5 h-5 flex-shrink-0 mt-0.5" />
              <span>您的合同还有 <strong>{daysToExpire}</strong> 天到期，请关注续签事宜</span>
            </div>
          )}

          {/* 合同概览卡片 */}
          <Card className="p-5">
            <div className="flex items-center gap-3 mb-4">
              <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center flex-shrink-0">
                <FileText className="w-5 h-5 text-primary" />
              </div>
              <div className="min-w-0">
                <div className="text-sm font-semibold text-gray-900 truncate">
                  {contract.contractType === 'FIXED' ? '固定期限劳动合同' : contract.contractType === 'UNFIXED' ? '无固定期限劳动合同' : '未签订'}
                </div>
                <div className="text-xs text-gray-500">{contract.signMethod === 'PAPER' ? '纸质合同' : '电子合同'}</div>
              </div>
            </div>

            <div className="space-y-3">
              <InfoRow icon={Calendar} label="合同开始" value={new Date(contract.startDate).toISOString().slice(0, 10)} />
              {contract.endDate && (
                <InfoRow icon={Calendar} label="合同结束" value={new Date(contract.endDate).toISOString().slice(0, 10)} />
              )}
              {contract.contractYears > 0 && (
                <InfoRow icon={Briefcase} label="合同期限" value={`${contract.contractYears}年`} />
              )}
              {contract.signDate && (
                <InfoRow icon={Calendar} label="签订日期" value={new Date(contract.signDate).toISOString().slice(0, 10)} />
              )}
              {contract.probationMonths > 0 && (
                <InfoRow icon={Clock} label="试用期" value={`${contract.probationMonths}个月`} />
              )}
              {contract.probationSalary > 0 && (
                <InfoRow icon={Briefcase} label="试用期工资" value={`¥${fmt(Number(contract.probationSalary))}`} />
              )}
            </div>
          </Card>

          {/* 签署确认记录 */}
          <Card className="p-4">
            <h3 className="text-sm font-semibold text-gray-900 mb-3">签署确认</h3>
            {isConfirmed ? (
              <div className="flex items-center gap-3">
                <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 text-sm text-amber-600">
                  <AlertCircle className="w-4 h-4" />
                  <span>合同尚未确认签署</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>
            )}
          </Card>
        </>
      )}
    </div>
  )
}

function InfoRow({ icon: Icon, label, value }: { icon: any; label: string; value: string }) {
  return (
    <div className="flex items-center justify-between gap-2">
      <div className="flex items-center gap-2 flex-shrink-0">
        <Icon className="w-4 h-4 text-gray-400" />
        <span className="text-sm text-gray-500">{label}</span>
      </div>
      <span className="text-sm font-medium text-gray-800 text-right truncate">{value}</span>
    </div>
  )
}
