/**
 * 医疗期计算器
 * 根据员工工龄和地区政策计算法定医疗期天数
 * 支持自定义地区政策（数据驱动）
 */

import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Calculator, HeartPulse, Info } from 'lucide-react'
import Card from '../../components/ui/Card'
import Button from '../../components/ui/Button'
import { settingsApi } from '../../lib/api-services'
import PageGuide from '../../components/ui/PageGuide'

interface PolicyRule {
  maxYears: number
  months: number
  cycleMonths: number
}

interface MedicalPeriodPolicy {
  id: string
  region: string
  legalBasis: string
  rules: PolicyRule[]
  isDefault: boolean
}

interface MedicalPeriodResult {
  totalMonths: number
  cumulativeDays: number
  actualDays: number
  endDate: string
  legalBasis: string
  notes: string[]
}

function calculateMedicalPeriod(
  workYears: number,
  policy: MedicalPeriodPolicy,
  sickDays: number,
  startDate: string,
): MedicalPeriodResult | null {
  if (!startDate || workYears < 0 || !policy.rules.length) return null

  const rule = policy.rules.find(r => workYears < r.maxYears) || policy.rules[policy.rules.length - 1]
  const totalMonths = rule.months
  const cumulativeDays = rule.cycleMonths * 30
  const legalBasis = policy.legalBasis
  const notes: string[] = []

  notes.push(`在 ${rule.cycleMonths} 个月的累计周期内，病休累计不超过 ${totalMonths} 个月即享有医疗期保护`)

  const actualDays = Math.max(0, totalMonths * 30 - sickDays)

  const start = new Date(startDate)
  const endDate = new Date(start)
  endDate.setMonth(endDate.getMonth() + totalMonths)

  notes.push('医疗期内企业不得解除劳动合同（法定情形除外）')
  notes.push('医疗期满后不能从事原工作也不能从事另行安排的工作，企业可提前30天通知或支付代通知金解除')

  return {
    totalMonths,
    cumulativeDays,
    actualDays,
    endDate: endDate.toISOString().slice(0, 10),
    legalBasis,
    notes,
  }
}

/**
 * 医疗期计算器页面
 */
export default function MedicalPeriodCalculator() {
  const [selectedPolicyId, setSelectedPolicyId] = useState('')
  const [workYears, setWorkYears] = useState('')
  const [sickDays, setSickDays] = useState('0')
  const [startDate, setStartDate] = useState('')
  const [result, setResult] = useState<MedicalPeriodResult | null>(null)

  const { data: policies = [] } = useQuery<MedicalPeriodPolicy[]>({
    queryKey: ['medical-period-policies'],
    queryFn: () => settingsApi.medicalPeriodPolicies(),
  })

  const selectedPolicy = useMemo(() => {
    if (!policies.length) return null
    if (selectedPolicyId) return policies.find(p => p.id === selectedPolicyId) || null
    return policies.find(p => p.isDefault) || policies[0]
  }, [policies, selectedPolicyId])

  const handleCalculate = () => {
    const years = parseFloat(workYears) || 0
    const days = parseInt(sickDays) || 0
    if (!selectedPolicy) return
    const r = calculateMedicalPeriod(years, selectedPolicy, days, startDate)
    setResult(r)
  }

  const handleReset = () => {
    setSelectedPolicyId('')
    setWorkYears('')
    setSickDays('0')
    setStartDate('')
    setResult(null)
  }

  return (
    <div className="space-y-3">
      <PageGuide>医疗期计算器，根据员工工龄和病情计算法定医疗期。输入入职日期、诊断日期等，自动计算医疗期起止时间和对应工资标准。关联：解聘合规检查时参考医疗期信息。</PageGuide>
      <div className="flex items-center gap-2">
        <HeartPulse className="h-5 w-5 text-primary" />
        <h1 className="text-base font-semibold">医疗期计算器</h1>
      </div>

      <Card>
        <div className="space-y-3">
          {/* 地区选择 */}
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">所在地区</label>
            <select
              value={selectedPolicy?.id || ''}
              onChange={(e) => setSelectedPolicyId(e.target.value)}
              className="w-full px-3 py-2 text-sm border rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
            >
              {policies.map(p => (
                <option key={p.id} value={p.id}>{p.region}{p.isDefault ? '（默认）' : ''}</option>
              ))}
            </select>
          </div>

          {/* 工龄输入 */}
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">本单位工作年限（年）</label>
            <input
              type="number"
              value={workYears}
              onChange={(e) => setWorkYears(e.target.value)}
              placeholder="如：5.5"
              step="0.5"
              min="0"
              className="w-full px-3 py-2 text-sm border rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
            />
          </div>

          {/* 病休开始日期 */}
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">开始病休日期</label>
            <input
              type="date"
              value={startDate}
              onChange={(e) => setStartDate(e.target.value)}
              className="w-full px-3 py-2 text-sm border rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
            />
          </div>

          {/* 累计病休天数 */}
          <div>
            <label className="block text-xs font-medium text-gray-700 mb-1">已累计病休天数</label>
            <input
              type="number"
              value={sickDays}
              onChange={(e) => setSickDays(e.target.value)}
              placeholder="0"
              min="0"
              className="w-full px-3 py-2 text-sm border rounded-md focus:outline-none focus:ring-1 focus:ring-primary"
            />
          </div>

          <div className="flex gap-2">
            <Button onClick={handleCalculate} className="flex-1">
              <Calculator className="w-4 h-4 mr-1" />
              立即计算
            </Button>
            <Button variant="secondary" onClick={handleReset}>
              重置
            </Button>
          </div>
        </div>
      </Card>

      {/* 计算结果 */}
      {result && (
        <Card className="border-primary/20 bg-primary/5">
          <div className="space-y-3">
            <h2 className="text-sm font-medium flex items-center gap-1.5">
              <Info className="w-4 h-4 text-primary" />
              计算结果
            </h2>

            <div className="grid grid-cols-2 gap-3">
              <div className="p-3 rounded-lg bg-white">
                <div className="text-xs text-gray-500">法定医疗期</div>
                <div className="text-lg font-bold text-primary">{result.totalMonths} 个月</div>
              </div>
              <div className="p-3 rounded-lg bg-white">
                <div className="text-xs text-gray-500">累计计算周期</div>
                <div className="text-lg font-bold text-primary">{result.cumulativeDays / 30} 个月</div>
              </div>
              <div className="p-3 rounded-lg bg-white">
                <div className="text-xs text-gray-500">剩余可用天数</div>
                <div className={`text-lg font-bold ${result.actualDays > 0 ? 'text-safe' : 'text-danger'}`}>
                  {result.actualDays} 天
                </div>
              </div>
              <div className="p-3 rounded-lg bg-white">
                <div className="text-xs text-gray-500">医疗期截止日</div>
                <div className="text-sm font-bold text-gray-800">{result.endDate}</div>
              </div>
            </div>

            {/* 法律依据 */}
            <div className="p-2 rounded-md bg-amber-50 text-xs text-amber-800">
              <span className="font-medium">法律依据：</span>{result.legalBasis}
            </div>

            {/* 注意事项 */}
            <div className="space-y-1">
              <div className="text-xs font-medium text-gray-700">注意事项</div>
              {result.notes.map((note, i) => (
                <div key={i} className="flex items-start gap-1.5 text-xs text-gray-600">
                  <span className="w-1.5 h-1.5 rounded-full bg-primary mt-1 flex-shrink-0" />
                  {note}
                </div>
              ))}
            </div>
          </div>
        </Card>
      )}

      {/* 当前政策分档表 */}
      {selectedPolicy && (
        <Card>
          <h2 className="text-sm font-medium mb-2">医疗期分档表（{selectedPolicy.region}）</h2>
          <div className="overflow-x-auto">
            <table className="w-full text-xs">
              <thead>
                <tr className="border-b text-left text-gray-500">
                  <th className="py-2 pr-3">工作年限</th>
                  <th className="py-2 pr-3">医疗期</th>
                  <th className="py-2 pr-3">累计周期</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {selectedPolicy.rules.map((rule, idx) => {
                  const prevMax = idx > 0 ? selectedPolicy.rules[idx - 1].maxYears : 0
                  const isLast = idx === selectedPolicy.rules.length - 1
                  return (
                    <tr key={idx}>
                      <td className="py-2 pr-3">{isLast ? `${prevMax} 年以上` : `${prevMax}-${rule.maxYears} 年`}</td>
                      <td className="py-2 pr-3">{rule.months} 个月</td>
                      <td className="py-2 pr-3">{rule.cycleMonths} 个月</td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        </Card>
      )}
    </div>
  )
}
