/* global React, window */
const { useState: useApprState, useEffect: useApprEffect } = React;

const APPR_LEAVE_TYPE = {
  sick:     { label: 'ลาป่วย',     chip: 'c-coral' },
  personal: { label: 'ลากิจ',      chip: 'c-amber' },
  vacation: { label: 'ลาพักผ่อน',  chip: 'c-green' },
  other:    { label: 'ลาอื่นๆ',     chip: 'c-blue' },
};
const APPR_EXPENSE_CAT = {
  'เดินทาง': 'c-blue', 'อาหาร': 'c-amber', 'อุปกรณ์': 'c-violet', 'ที่พัก': 'c-green', 'อื่นๆ': 'c-gray',
};

function apprLeaveDays(a, b) {
  try { const d1 = new Date(a), d2 = new Date(b); const n = Math.round((d2 - d1) / 86400000) + 1; return n > 0 ? n : 1; } catch (e) { return 1; }
}
function apprFmtRange(a, b) { return a === b ? a : `${a} – ${b}`; }
function apprFmtBaht(n) {
  const v = Number(n || 0);
  try { return v.toLocaleString('th-TH', { minimumFractionDigits: 0, maximumFractionDigits: 2 }); } catch (e) { return String(v); }
}

// Circular face avatar (clickable → profile).
function ApprAvatar({ id, size = 44 }) {
  const [err, setErr] = useApprState(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)' }} />;
}

// Person name + dept/id block shared by every row type.
function ApprPerson({ row }) {
  const name = `${row.first_name || ''} ${row.last_name || ''}`.trim() || row.employee_id || '—';
  return (
    <>
      <ApprAvatar id={row.employee_id} />
      <div style={{ minWidth: 140 }}>
        <div style={{ fontSize: 14.5, fontWeight: 600 }}>{name}</div>
        <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 2 }}>{row.employee_id}{row.department_name ? ` · ${row.department_name}` : ''}</div>
      </div>
    </>
  );
}

// อนุมัติ / Approvals — unified pending-approvals hub (admin/hr/manager only).
function ApprovalsPage({ role }) {
  const canApprove = role === 'admin' || role === 'hr' || role === 'manager';

  const [leaves, setLeaves] = useApprState([]);
  const [corrections, setCorrections] = useApprState([]);
  const [expenses, setExpenses] = useApprState([]);
  const [tab, setTab] = useApprState('leave');
  const [loading, setLoading] = useApprState(true);

  const loadLeaves = async () => {
    try { const r = await fetch('/api/leaves?status=pending', { credentials: 'include' }); if (r.ok) setLeaves(await r.json()); } catch (e) { /* keep prior */ }
  };
  const loadCorrections = async () => {
    try { const r = await fetch('/api/corrections?status=pending', { credentials: 'include' }); if (r.ok) setCorrections(await r.json()); } catch (e) { /* keep prior */ }
  };
  const loadExpenses = async () => {
    // /api/expenses is built by a teammate — tolerate 404 / errors by staying empty.
    try { const r = await fetch('/api/expenses?status=pending', { credentials: 'include' }); if (r.ok) setExpenses(await r.json()); else setExpenses([]); } catch (e) { setExpenses([]); }
  };

  useApprEffect(() => {
    if (!canApprove) { setLoading(false); return; }
    (async () => { setLoading(true); await Promise.all([loadLeaves(), loadCorrections(), loadExpenses()]); setLoading(false); })();
  }, []);

  if (!canApprove) {
    return (
      <div data-screen-label="Approvals">
        <div style={{ marginBottom: 16 }}>
          <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, margin: 0 }}>อนุมัติ / Approvals</h1>
          <div style={{ fontSize: 12.5, color: 'var(--ink-4)', marginTop: 4 }}>ศูนย์รวมรายการรออนุมัติ</div>
        </div>
        <div className="gv-empty">ไม่มีสิทธิ์</div>
      </div>
    );
  }

  // Leave actions.
  const approveLeave = async (id) => {
    await fetch(`/api/leaves/${id}/approve`, { method: 'PUT', credentials: 'include' });
    window.appToast && window.appToast('อนุมัติแล้ว', { tone: 'success' }); loadLeaves();
  };
  const rejectLeave = async (id) => {
    const reason = await window.appPrompt({ title: 'เหตุผลที่ไม่อนุมัติ', placeholder: 'ระบุเหตุผล (ไม่บังคับ)' });
    if (reason === null) return;
    await fetch(`/api/leaves/${id}/reject`, { method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ reason }) });
    window.appToast && window.appToast('ปฏิเสธแล้ว', { tone: 'info' }); loadLeaves();
  };

  // Correction actions.
  const approveCorrection = async (id) => {
    const r = await fetch(`/api/corrections/${id}/approve`, { method: 'PUT', credentials: 'include' });
    const d = await r.json().catch(() => ({}));
    if (!r.ok) { window.appToast && window.appToast(d.error || 'อนุมัติไม่สำเร็จ', { tone: 'error' }); return; }
    window.appToast && window.appToast('อนุมัติแล้ว', { tone: 'success' }); loadCorrections();
  };
  const rejectCorrection = async (id) => {
    const reason = await window.appPrompt({ title: 'เหตุผลที่ปฏิเสธ', placeholder: '(ไม่บังคับ)' });
    if (reason === null) return;
    await fetch(`/api/corrections/${id}/reject`, { method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ reason }) });
    window.appToast && window.appToast('ปฏิเสธแล้ว', { tone: 'info' }); loadCorrections();
  };

  // Expense actions.
  const approveExpense = async (id) => {
    await fetch(`/api/expenses/${id}/approve`, { method: 'PUT', credentials: 'include' });
    window.appToast && window.appToast('อนุมัติแล้ว', { tone: 'success' }); loadExpenses();
  };
  const rejectExpense = async (id) => {
    const reason = await window.appPrompt({ title: 'เหตุผลที่ไม่อนุมัติ', placeholder: 'ระบุเหตุผล (ไม่บังคับ)' });
    if (reason === null) return;
    await fetch(`/api/expenses/${id}/reject`, { method: 'PUT', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ reason }) });
    window.appToast && window.appToast('ปฏิเสธแล้ว', { tone: 'info' }); loadExpenses();
  };

  const nL = leaves.length, nC = corrections.length, nE = expenses.length;
  const stats = [
    ['ใบลารออนุมัติ', nL, 'var(--yellow-ink)'],
    ['ขอแก้เวลารออนุมัติ', nC, 'var(--primary)'],
    ['เบิกค่าใช้จ่ายรออนุมัติ', nE, 'var(--mint)'],
  ];
  const tabs = [['leave', `ใบลา (${nL})`], ['correction', `ขอแก้เวลา (${nC})`], ['expense', `เบิกค่าใช้จ่าย (${nE})`]];

  const actionBtns = (onReject, onApprove) => (
    <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
      <button className="gv-btn no sm" onClick={onReject}>ปฏิเสธ</button>
      <button className="gv-btn ok sm" onClick={onApprove}>อนุมัติ</button>
    </div>
  );

  const renderList = () => {
    if (loading) return <div className="gv-empty">กำลังโหลด…</div>;

    if (tab === 'leave') {
      if (leaves.length === 0) return <div className="gv-empty">ไม่มีรายการรออนุมัติ 🎉</div>;
      return leaves.map((l) => {
        const t = APPR_LEAVE_TYPE[l.leave_type] || APPR_LEAVE_TYPE.other;
        return (
          <div key={l.id} className="gv-row">
            <ApprPerson row={l} />
            <div style={{ minWidth: 150 }}>
              <span className={`gv-chip ${t.chip}`}>{t.label}</span>
              <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 4 }}>{apprFmtRange(l.start_date, l.end_date)} · {apprLeaveDays(l.start_date, l.end_date)} วัน</div>
            </div>
            <div style={{ flex: 1, fontSize: 13, color: 'var(--ink-4)', minWidth: 0 }}>{l.reason || '—'}</div>
            {actionBtns(() => rejectLeave(l.id), () => approveLeave(l.id))}
          </div>
        );
      });
    }

    if (tab === 'correction') {
      if (corrections.length === 0) return <div className="gv-empty">ไม่มีรายการรออนุมัติ 🎉</div>;
      return corrections.map((c) => (
        <div key={c.id} className="gv-row">
          <ApprPerson row={c} />
          <div style={{ minWidth: 140 }}>
            <div style={{ fontSize: 13.5 }}><span style={{ color: c.punch_type === 'out' ? 'var(--primary)' : 'var(--mint-ink)', fontWeight: 600 }}>{c.punch_type === 'out' ? 'ออกงาน' : 'เข้างาน'}</span> {c.proposed_time}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 2 }}>{c.date}</div>
          </div>
          <div style={{ flex: 1, fontSize: 13, color: 'var(--ink-4)', minWidth: 0 }}>{c.reason || '—'}</div>
          {actionBtns(() => rejectCorrection(c.id), () => approveCorrection(c.id))}
        </div>
      ));
    }

    // expense
    if (expenses.length === 0) return <div className="gv-empty">ไม่มีรายการรออนุมัติ 🎉</div>;
    return expenses.map((x) => {
      const catChip = APPR_EXPENSE_CAT[x.category] || 'c-gray';
      return (
        <div key={x.id} className="gv-row">
          <ApprPerson row={x} />
          <div style={{ minWidth: 150 }}>
            <span className={`gv-chip ${catChip}`}>{x.category || 'อื่นๆ'}</span>
            <div style={{ fontSize: 11.5, color: 'var(--ink-4)', marginTop: 4 }}>{x.date}</div>
          </div>
          <div style={{ flex: 1, fontSize: 13, minWidth: 0 }}>
            <div style={{ fontWeight: 600, color: 'var(--ink)' }}>{x.title || '—'}</div>
            <div className="tnum" style={{ fontSize: 12.5, color: 'var(--ink-4)', marginTop: 2 }}>฿ {apprFmtBaht(x.amount)}</div>
          </div>
          {actionBtns(() => rejectExpense(x.id), () => approveExpense(x.id))}
        </div>
      );
    });
  };

  return (
    <div data-screen-label="Approvals">
      <div style={{ marginBottom: 16 }}>
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, margin: 0 }}>อนุมัติ / Approvals</h1>
        <div style={{ fontSize: 12.5, color: 'var(--ink-4)', marginTop: 4 }}>ศูนย์รวมรายการรออนุมัติทั้งหมด · ใบลา · ขอแก้เวลา · เบิกค่าใช้จ่าย</div>
      </div>

      {/* stat pills */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 14, marginBottom: 16 }}>
        {stats.map(([k, v, c]) => (
          <div key={k} className="gv-card" style={{ padding: '16px 20px', boxShadow: 'var(--shadow-sm)', display: 'flex', alignItems: 'baseline', gap: 12 }}>
            <div className="tnum" style={{ fontFamily: 'var(--font-display)', fontSize: 34, fontWeight: 700, lineHeight: 1, color: c }}>{v}</div>
            <div style={{ fontSize: 13, color: 'var(--ink-4)', fontWeight: 500 }}>{k}</div>
          </div>
        ))}
      </div>

      <div className="gv-card">
        <div className="gv-card-h" style={{ flexWrap: 'wrap', gap: 10 }}>
          <b>รายการรออนุมัติ</b>
          <div className="gv-seg">
            {tabs.map(([k, lbl]) => (
              <button key={k} className={tab === k ? 'on' : ''} onClick={() => setTab(k)}>{lbl}</button>
            ))}
          </div>
        </div>
        <div className="gv-card-b" style={{ paddingTop: 6 }}>
          {renderList()}
        </div>
      </div>
    </div>
  );
}

window.ApprovalsPage = ApprovalsPage;
