// Reports page

const ReportsPage = ({ data }) => {
  const [period, setPeriod] = React.useState('2026');

  // Per-employee summary
  const summary = data.employees.map(e => {
    const empLeaves = data.leaves.filter(l => l.empId === e.id && l.status === 'approved');
    const vacation = empLeaves.filter(l => l.type === 'vacation').reduce((s, l) => s + l.days, 0);
    const personal = empLeaves.filter(l => l.type === 'personal').reduce((s, l) => s + l.days, 0);
    const sick = empLeaves.filter(l => l.type === 'sick').reduce((s, l) => s + l.days, 0);
    const otHours = data.otRequests.filter(o => o.empId === e.id && o.status === 'approved').reduce((s, o) => s + o.hours, 0);
    const swaps = data.swapRequests.filter(s => s.empId === e.id && s.status === 'approved').length;
    return { ...e, vacation, personal, sick, otHours, swaps, total: vacation + personal + sick };
  });

  const totalLeave = summary.reduce((s, e) => s + e.total, 0);
  const totalOt = summary.reduce((s, e) => s + e.otHours, 0);
  const totalSwaps = summary.reduce((s, e) => s + e.swaps, 0);

  // Monthly trend — sum of approved leave days by from_date's month for current year
  const MONTH_LABELS = ['ม.ค.','ก.พ.','มี.ค.','เม.ย.','พ.ค.','มิ.ย.','ก.ค.','ส.ค.','ก.ย.','ต.ค.','พ.ย.','ธ.ค.'];
  const monthTotals = new Array(12).fill(0);
  const yr = new Date().getFullYear();
  data.leaves.filter(l => l.status === 'approved').forEach(l => {
    const d = new Date(l.from);
    if (d.getFullYear() === yr) monthTotals[d.getMonth()] += l.days;
  });
  const months = MONTH_LABELS.map((m, i) => ({ m, v: monthTotals[i] }));
  const maxMonth = Math.max(1, ...months.map(m => m.v));

  return (
    <div data-screen-label="Reports">
      <div className="row between mb-3">
        <div>
          <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-.02em' }}>รายงานสรุป</div>
          <div className="text-sm muted">วันลา OT และการสลับวันหยุดของพนักงานทั้งหมด</div>
        </div>
        <div className="row" style={{ gap: 8 }}>
          <select value={period} onChange={e => setPeriod(e.target.value)} style={{
            padding: '7px 12px', borderRadius: 8, border: '1px solid var(--ink-200)', background: 'var(--paper)', fontSize: 13
          }}>
            <option value="2026">ปี 2569 (2026)</option>
            <option value="2026-q2">ไตรมาส 2/2569</option>
            <option value="2026-05">พฤษภาคม 2569</option>
          </select>
          <button className="btn btn-ghost"><Icon name="download" size={14}/> Export Excel</button>
          <button className="btn btn-primary"><Icon name="file" size={14}/> สร้าง PDF</button>
        </div>
      </div>

      <div className="stats-row">
        <div className="stat">
          <div className="stat-icon"><Icon name="plane"/></div>
          <div className="stat-label">วันลารวมทั้งบริษัท</div>
          <div className="stat-value">{totalLeave}<span style={{ fontSize: 14, color: 'var(--ink-400)', fontWeight: 500 }}> วัน</span></div>
          <div className="stat-meta">เฉลี่ย <strong>{(totalLeave / data.employees.length).toFixed(1)}</strong> วัน/คน</div>
        </div>
        <div className="stat">
          <div className="stat-icon" style={{ background: 'var(--ot-bg)', color: 'var(--ot)' }}><Icon name="sparkle"/></div>
          <div className="stat-label">OT รวม (8 ชม. = 1 วัน)</div>
          <div className="stat-value">{(totalOt / 8).toFixed(1)}<span style={{ fontSize: 14, color: 'var(--ink-400)', fontWeight: 500 }}> วัน</span></div>
          <div className="stat-meta">เฉลี่ย <strong>{(totalOt / 8 / Math.max(1, data.employees.length)).toFixed(1)}</strong> วัน/คน · รวม {totalOt} ชม.</div>
        </div>
        <div className="stat">
          <div className="stat-icon" style={{ background: 'var(--swap-bg)', color: 'var(--swap)' }}><Icon name="swap"/></div>
          <div className="stat-label">การสลับวันหยุด</div>
          <div className="stat-value">{totalSwaps}<span style={{ fontSize: 14, color: 'var(--ink-400)', fontWeight: 500 }}> ครั้ง</span></div>
          <div className="stat-meta">อนุมัติ 100%</div>
        </div>
        <div className="stat">
          <div className="stat-icon" style={{ background: 'var(--sick-bg)', color: 'var(--sick)' }}><Icon name="alert"/></div>
          <div className="stat-label">อัตราการลาป่วย</div>
          <div className="stat-value">2.8<span style={{ fontSize: 14, color: 'var(--ink-400)', fontWeight: 500 }}>%</span></div>
          <div className="stat-meta">ต่ำกว่าเดือนก่อน <strong>0.4%</strong></div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 20, marginBottom: 20 }}>
        <div className="card">
          <div className="card-header">
            <div>
              <div className="card-title">วันลาแต่ละเดือน ปี 2569</div>
              <div className="card-sub">รวมทั้งบริษัท (วัน)</div>
            </div>
          </div>
          <div className="card-body">
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10, height: 180 }}>
              {months.map((m, i) => (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                  <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-700)', fontFamily: 'var(--font-en)' }}>
                    {m.v || ''}
                  </div>
                  <div style={{
                    width: '100%',
                    height: `${(m.v / maxMonth) * 140 || 4}px`,
                    background: m.v > 0
                      ? 'linear-gradient(180deg, var(--brand-500), var(--brand-700))'
                      : 'var(--ink-100)',
                    borderRadius: '6px 6px 0 0',
                  }}/>
                  <div className="text-xs muted">{m.m}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-header">
            <div>
              <div className="card-title">สัดส่วนประเภทการลา</div>
            </div>
          </div>
          <div className="card-body">
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '10px 0' }}>
              <DonutChart vac={summary.reduce((s,e)=>s+e.vacation,0)} pers={summary.reduce((s,e)=>s+e.personal,0)} sick={summary.reduce((s,e)=>s+e.sick,0)}/>
            </div>
            <div className="col" style={{ gap: 8, marginTop: 8 }}>
              <LegendRow color="var(--vac)" label="พักร้อน" value={summary.reduce((s,e)=>s+e.vacation,0)}/>
              <LegendRow color="var(--pers)" label="ลากิจ" value={summary.reduce((s,e)=>s+e.personal,0)}/>
              <LegendRow color="var(--sick)" label="ลาป่วย" value={summary.reduce((s,e)=>s+e.sick,0)}/>
            </div>
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-header">
          <div>
            <div className="card-title">สรุปรายบุคคล</div>
            <div className="card-sub">{data.employees.length} คน · ใช้สำหรับประเมินผลและคำนวณค่าจ้าง</div>
          </div>
        </div>
        <table className="t">
          <thead>
            <tr>
              <th>พนักงาน</th>
              <th>แผนก</th>
              <th className="num">พักร้อน</th>
              <th className="num">ลากิจ</th>
              <th className="num">ลาป่วย</th>
              <th className="num">รวมวันลา</th>
              <th className="num">OT (วัน)</th>
              <th className="num">สลับวัน</th>
              <th>การใช้งาน</th>
            </tr>
          </thead>
          <tbody>
            {summary.map(e => {
              const usage = (e.total / 39) * 100;
              return (
                <tr key={e.id}>
                  <td>
                    <div className="row" style={{ gap: 8 }}>
                      <span className="avatar" style={{ background: e.color, width: 26, height: 26, fontSize: 10 }}>{e.avatar}</span>
                      <strong>{e.name}</strong>
                    </div>
                  </td>
                  <td><span className="chip">{e.dept}</span></td>
                  <td className="num">{e.vacation}</td>
                  <td className="num">{e.personal}</td>
                  <td className="num">{e.sick}</td>
                  <td className="num" style={{ fontWeight: 600 }}>{e.total}</td>
                  <td className="num" title={`${e.otHours} ชม.`}>{(e.otHours / 8).toFixed(1)}</td>
                  <td className="num">{e.swaps}</td>
                  <td style={{ minWidth: 120 }}>
                    <div className="bar"><span style={{ width: `${Math.min(100, usage)}%` }}/></div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

const LegendRow = ({ color, label, value }) => (
  <div className="row between">
    <div className="row" style={{ gap: 8 }}>
      <span style={{ width: 10, height: 10, borderRadius: 3, background: color }}/>
      <span className="text-sm">{label}</span>
    </div>
    <strong className="num text-sm">{value} วัน</strong>
  </div>
);

const DonutChart = ({ vac, pers, sick }) => {
  const total = Math.max(1, vac + pers + sick);
  const c = 2 * Math.PI * 40;
  const v1 = (vac / total) * c;
  const v2 = (pers / total) * c;
  const v3 = (sick / total) * c;
  return (
    <svg width="140" height="140" viewBox="0 0 100 100">
      <circle cx="50" cy="50" r="40" fill="none" stroke="var(--ink-100)" strokeWidth="14"/>
      <circle cx="50" cy="50" r="40" fill="none" stroke="var(--vac)" strokeWidth="14"
        strokeDasharray={`${v1} ${c}`} strokeDashoffset="0" transform="rotate(-90 50 50)"/>
      <circle cx="50" cy="50" r="40" fill="none" stroke="var(--pers)" strokeWidth="14"
        strokeDasharray={`${v2} ${c}`} strokeDashoffset={-v1} transform="rotate(-90 50 50)"/>
      <circle cx="50" cy="50" r="40" fill="none" stroke="var(--sick)" strokeWidth="14"
        strokeDasharray={`${v3} ${c}`} strokeDashoffset={-(v1+v2)} transform="rotate(-90 50 50)"/>
      <text x="50" y="50" textAnchor="middle" dy="2" style={{ fontWeight: 700, fontSize: 16, fontFamily: 'var(--font-en)' }} fill="var(--ink-900)">
        {vac + pers + sick}
      </text>
      <text x="50" y="62" textAnchor="middle" style={{ fontSize: 7 }} fill="var(--ink-500)">วัน</text>
    </svg>
  );
};

window.ReportsPage = ReportsPage;
