/* global React, window */
const { useState: useRepState, useEffect: useRepEffect } = React;

// Circular face avatar (clickable → profile).
function RepAvatar({ id, size = 36 }) {
  const [err, setErr] = useRepState(false);
  const src = (err || !id) ? '/img/avatar-person.svg' : `/faces/${id}.jpg`;
  return <img src={src} alt="" onError={() => setErr(true)}
    onClick={() => id && window.openProfile && window.openProfile(id)} title={id ? 'ดูโปรไฟล์' : ''}
    style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flex: 'none',
      cursor: id ? 'pointer' : 'default', border: '1px solid var(--line)' }} />;
}

// รายงาน — monthly per-employee summary (present/absent/leave days, late count,
// total late + OT minutes). Export to CSV for payroll.
function ReportPage({ role }) {
  const [month, setMonth] = useRepState((window.TODAY || new Date().toISOString().slice(0, 10)).slice(0, 7));
  const [deptFilter, setDeptFilter] = useRepState('all');
  const [rows, setRows] = useRepState([]);
  const [loading, setLoading] = useRepState(true);

  const load = async () => {
    setLoading(true);
    const q = new URLSearchParams({ month });
    if (deptFilter !== 'all') q.set('department_id', deptFilter);
    const r = await fetch('/api/attendance/monthly?' + q.toString(), { credentials: 'include' });
    if (r.ok) { const d = await r.json(); setRows(d.rows || []); }
    setLoading(false);
  };
  useRepEffect(() => { load(); }, [month, deptFilter]);

  const exportCsv = () => {
    const header = ['รหัส', 'ชื่อ-สกุล', 'แผนก', 'มา(วัน)', 'ยังไม่ออก', 'ขาด', 'ลา', 'สาย(ครั้ง)', 'สายรวม(นาที)', 'OT รวม(นาที)'];
    const lines = rows.map((r) => [
      r.employee_id, `${r.first_name || ''} ${r.last_name || ''}`.trim(), r.department_name || '',
      r.present_days, r.in_only_days, r.absent_days, r.leave_days,
      r.late_count, r.total_late_min, r.total_ot_min,
    ]);
    const csv = '﻿' + [header, ...lines].map((row) => row.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = `report_${month}.csv`;
    a.click();
  };

  const monthLabel = new Date(month + '-01T00:00:00').toLocaleDateString('th-TH', { month: 'long', year: 'numeric' });

  return (
    <div data-screen-label="Report">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
        <div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, margin: 0 }}>รายงานรายเดือน / Report</h1>
          <div style={{ fontSize: 12.5, color: 'var(--ink-4)', marginTop: 4 }}>สรุปการมาทำงาน · สาย · OT · {monthLabel} — Export CSV เข้าระบบเงินเดือนได้</div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
          <input className="gv-input" type="month" value={month} onChange={(e) => setMonth(e.target.value)} style={{ width: 160 }}/>
          <select className="gv-select" value={deptFilter} onChange={(e) => setDeptFilter(e.target.value)} style={{ width: 180 }}>
            <option value="all">ทุกแผนก</option>
            {(window.DEPARTMENTS || []).map((d) => <option key={d.id} value={String(d.id)}>{d.name}</option>)}
          </select>
          <button className="gv-btn dark sm" onClick={exportCsv} disabled={!rows.length}>⬇ Export CSV</button>
        </div>
      </div>

      <div className="gv-card">
        <div style={{ overflowX: 'auto', maxHeight: 'calc(100vh - 240px)', overflowY: 'auto' }}>
          <table className="gv-tbl">
            <thead>
              <tr>
                <th>พนักงาน</th><th>แผนก</th>
                <th style={{ textAlign: 'center' }}>มา</th>
                <th style={{ textAlign: 'center' }}>ยังไม่ออก</th>
                <th style={{ textAlign: 'center' }}>ขาด</th>
                <th style={{ textAlign: 'center' }}>ลา</th>
                <th style={{ textAlign: 'center' }}>สาย</th>
                <th style={{ textAlign: 'center' }}>OT(น.)</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={8}><div className="gv-empty">กำลังโหลด…</div></td></tr>
              ) : rows.length === 0 ? (
                <tr><td colSpan={8}><div className="gv-empty">— ไม่มีข้อมูล —</div></td></tr>
              ) : rows.map((r) => (
                <tr key={r.employee_id}>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <RepAvatar id={r.employee_id} />
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontWeight: 600, fontSize: 13.5, whiteSpace: 'nowrap' }}>{r.first_name} {r.last_name}</div>
                        <div style={{ fontSize: 11.5, color: 'var(--ink-4)' }}>{r.employee_id}</div>
                      </div>
                    </div>
                  </td>
                  <td>{r.department_name ? <span className="gv-chip c-gray">{r.department_name}</span> : <span style={{ color: 'var(--ink-5)' }}>—</span>}</td>
                  <td className="tnum" style={{ textAlign: 'center', color: 'var(--mint-ink)', fontWeight: 600 }}>{r.present_days}</td>
                  <td className="tnum" style={{ textAlign: 'center', color: 'var(--yellow-ink)' }}>{r.in_only_days || ''}</td>
                  <td className="tnum" style={{ textAlign: 'center', color: r.absent_days ? 'var(--coral-ink)' : 'var(--ink-5)' }}>{r.absent_days}</td>
                  <td className="tnum" style={{ textAlign: 'center' }}>{r.leave_days || ''}</td>
                  <td className="tnum" style={{ textAlign: 'center', color: r.late_count ? 'var(--yellow-ink)' : 'var(--ink-5)' }}>{r.late_count || ''}</td>
                  <td className="tnum" style={{ textAlign: 'center', color: r.total_ot_min ? 'var(--mint-ink)' : 'var(--ink-5)' }}>{r.total_ot_min || ''}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

window.ReportPage = ReportPage;
