// Tenant-level audit log page

const TenantAuditPage = ({ auditLog, tenant }) => {
  const [q, setQ] = useState("");
  const [action, setAction] = useState("all");
  const rel = auditLog.filter(a => a.tenant_id === tenant.id && a.scope === "tenant");
  const filtered = rel.filter(a => (action==="all" || a.action===action) && (!q || JSON.stringify(a).toLowerCase().includes(q.toLowerCase())));

  const action_meta = {
    create:{ c:"emerald", i:"plus" },
    update:{ c:"sky", i:"edit" },
    delete:{ c:"rose", i:"trash" },
    status_change:{ c:"violet", i:"refresh" },
    login:{ c:"slate", i:"key" },
    password_reset:{ c:"indigo", i:"key" },
  };
  const actions = ["all", ...new Set(rel.map(a=>a.action))];

  return (
    <div className="p-6">
      <PageHeader title="Audit Logs" subtitle={`การเปลี่ยนแปลงในระบบทั้งหมดของ ${tenant.company_short}`}
        right={<Button icon="download" variant="secondary" onClick={()=>{
          downloadCsv(`${tenant.tenant_code}_audit_logs.csv`,
            ["เวลา","Action","Reason","Performed by"],
            filtered.map(a => [a.at, a.action, a.reason, a.performed_by]));
        }}>Export CSV</Button>}/>

      <div className="bg-white rounded-2xl border border-ink-100 overflow-hidden">
        <div className="px-4 py-3 border-b border-ink-100 flex items-center gap-2 flex-wrap">
          <div className="relative flex-1 max-w-md">
            <Icon name="search" size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-400"/>
            <input value={q} onChange={e=>setQ(e.target.value)} placeholder="ค้นหา reason / user…"
              className="w-full h-9 pl-9 pr-3 text-[13px] border border-ink-200 rounded-lg bg-white focus:border-brand-500 ring-focus"/>
          </div>
          <Select value={action} onChange={e=>setAction(e.target.value)} className="!w-[180px]">
            {actions.map(a => <option key={a} value={a}>{a === "all" ? "ทุก Action" : a}</option>)}
          </Select>
          <div className="ml-auto text-[12px] text-ink-500">{filtered.length} รายการ</div>
        </div>
        {filtered.length === 0 ? (
          <EmptyState icon="history" title="ยังไม่มีบันทึก" subtitle="การเปลี่ยนแปลงในระบบจะปรากฏที่นี่อัตโนมัติ"/>
        ) : (
          <table className="w-full text-[12.5px]">
            <thead>
              <tr className="bg-ink-50/60 text-ink-500 text-[10.5px] uppercase tracking-wider">
                {["เวลา","Action","Reason / Detail","Performed by"].map(h=>(<th key={h} className="text-left font-semibold px-3 py-2.5 border-b border-ink-100">{h}</th>))}
              </tr>
            </thead>
            <tbody>
              {filtered.map(a => {
                const m = action_meta[a.action] || { c:"slate", i:"info" };
                return (
                  <tr key={a.id} className="border-b border-ink-100 hover:bg-ink-50/40 last:border-0">
                    <td className="px-3 py-2.5 font-mono text-ink-700">{a.at}</td>
                    <td className="px-3 py-2.5"><Badge color={m.c} icon={m.i}>{a.action}</Badge></td>
                    <td className="px-3 py-2.5 text-ink-800">{a.reason}</td>
                    <td className="px-3 py-2.5">
                      <div className="flex items-center gap-2"><Avatar name={a.performed_by} size={22}/><span className="text-ink-700">{a.performed_by}</span></div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { TenantAuditPage });
