import { AttendanceRecord } from '../entities/attendance-record.entity';
import { esc, sectionFrame, sectionHeader } from './archive-report.helpers';

export function buildAttendance(records: AttendanceRecord[], now: string): string {
  if (records.length === 0) return '';

  const present = records.filter((r) => r.status === 'present').length;
  const absent = records.filter((r) => r.status === 'absent').length;
  const late = records.filter((r) => r.status === 'late').length;
  const leave = records.filter((r) => r.status === 'leave').length;
  const total = records.length;
  const rate = total > 0 ? ((present / total) * 100).toFixed(1) : '0';

  const metricHtml = `
      <div class="title-row">
        <div>
          <div class="source">${esc(now)} · 系统生成</div>
          <div class="section-title">出勤记录</div>
        </div>
      </div>
      <div class="grid-4" style="margin-bottom:14px;">
        <div class="metric">
          <div class="label">总考勤次数</div>
          <strong>${total}</strong>
          <p>累计记录</p>
        </div>
        <div class="metric">
          <div class="label">出勤率</div>
          <strong>${esc(rate)}%</strong>
          <p>出勤: ${present} 次</p>
        </div>
        <div class="metric">
          <div class="label">缺勤 / 迟到</div>
          <strong>${absent} / ${late}</strong>
          <p>缺勤 ${absent} · 迟到 ${late}</p>
        </div>
        <div class="metric">
          <div class="label">请假</div>
          <strong>${leave}</strong>
          <p>累计请假次数</p>
        </div>
      </div>`;

  const chart = renderAttendanceBar(records);
  const matrix = renderAttendanceMatrix(records);

  return sectionFrame(`
      ${sectionHeader('出勤记录')}
      ${metricHtml}
      ${chart}
      ${matrix}
    `);
}

export function renderAttendanceBar(records: AttendanceRecord[]): string {
  if (records.length === 0) return '';

  const statuses = ['present', 'absent', 'late', 'leave'] as const;
  const counts = statuses.map((s) => records.filter((r) => r.status === s).length);
  const labels = ['出勤', '缺勤', '迟到', '请假'];
  const colors = ['#18a77d', '#dc2626', '#f59e0b', '#f15b75'];
  const maxCount = Math.max(...counts, 1);

  const w = 600;
  const h = 150;
  const pad = { top: 20, right: 20, bottom: 30, left: 40 };
  const plotW = w - pad.left - pad.right;
  const plotH = h - pad.top - pad.bottom;
  const barGap = 30;
  const barW = (plotW - barGap * (statuses.length - 1)) / statuses.length;

  const scaleH = (v: number): number => (v / maxCount) * plotH;

  let bars = '';
  for (let i = 0; i < statuses.length; i++) {
    const x = pad.left + i * (barW + barGap);
    const bh = scaleH(counts[i]);
    const y = pad.top + plotH - bh;
    bars += `<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${barW.toFixed(1)}" height="${bh.toFixed(1)}" fill="${colors[i]}" rx="4"/>`;
    bars += `<text x="${(x + barW / 2).toFixed(1)}" y="${(y - 6).toFixed(1)}" text-anchor="middle" fill="#101828" font-size="12" font-weight="700">${counts[i]}</text>`;
    bars += `<text x="${(x + barW / 2).toFixed(1)}" y="${(h - 8).toFixed(1)}" text-anchor="middle" fill="#667085" font-size="11">${labels[i]}</text>`;
  }

  // Y-axis grid
  const ySteps = 4;
  let yGrid = '';
  for (let i = 0; i <= ySteps; i++) {
    const val = Math.round((maxCount * i) / ySteps);
    const y = pad.top + plotH - (plotH * i) / ySteps;
    yGrid += `<text x="${pad.left - 6}" y="${y + 4}" text-anchor="end" fill="#667085" font-size="10">${val}</text>`;
    if (i < ySteps) {
      yGrid += `<line x1="${pad.left}" y1="${y}" x2="${w - pad.right}" y2="${y}" stroke="#eaf3fd" stroke-width="1"/>`;
    }
  }

  return `<div class="card" style="margin-bottom:14px;">
      <h3>出勤统计</h3>
      <svg class="bar-chart" viewBox="0 0 ${w} ${h}" xmlns="http://www.w3.org/2000/svg">
        <rect x="0" y="0" width="${w}" height="${h}" fill="#fff"/>
        ${yGrid}
        ${bars}
      </svg>
    </div>`;
}

export function renderAttendanceMatrix(records: AttendanceRecord[]): string {
  if (records.length === 0) return '';

  // Group by date
  const dateMap = new Map<string, AttendanceRecord[]>();
  for (const r of records) {
    const existing = dateMap.get(r.attendanceDate) ?? [];
    existing.push(r);
    dateMap.set(r.attendanceDate, existing);
  }

  const dates = [...dateMap.keys()].sort();
  const sessions = ['上午', '下午', '晚自习'];

  let rows = '';
  for (const date of dates.slice(-30)) {
    const dayRecords = dateMap.get(date) ?? [];
    const cellMap = new Map<string, string>();
    for (const r of dayRecords) {
      cellMap.set(r.session, r.status);
    }

    let cells = '';
    for (const session of sessions) {
      const status = cellMap.get(session) ?? '';
      cells += `<td>${status ? statusBadge(status) : '-'}</td>`;
    }

    rows += `<tr><td class="nowrap">${esc(date)}</td>${cells}</tr>`;
  }

  return `<div class="card" style="margin-bottom:14px;">
      <h3>考勤明细（最近30条）</h3>
      <table class="data-table">
        <thead><tr>
          <th>日期</th>
          ${sessions.map((s) => `<th>${esc(s)}</th>`).join('')}
        </tr></thead>
        <tbody>${rows}</tbody>
      </table>
      <div class="note">图例: <span class="status present">到</span> 出勤 &nbsp; <span class="status absent">缺</span> 缺勤 &nbsp; <span class="status late">迟</span> 迟到 &nbsp; <span class="status leave">假</span> 请假</div>
    </div>`;
}

export function statusBadge(status: string): string {
  const map: Record<string, { cls: string; text: string }> = {
    present: { cls: 'present', text: '到' },
    absent: { cls: 'absent', text: '缺' },
    late: { cls: 'late', text: '迟' },
    leave: { cls: 'leave', text: '假' },
  };
  const entry = map[status];
  if (!entry) return `<span class="muted">${esc(status)}</span>`;
  return `<span class="status ${entry.cls}">${entry.text}</span>`;
}
